PackageManagerService.java revision 3c458636494f28685146060e1252f52fe43ed38a
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.FIRST_APPLICATION_UID; 59import static android.os.Process.PACKAGE_INFO_GID; 60import static android.os.Process.SYSTEM_UID; 61import static android.system.OsConstants.O_CREAT; 62import static android.system.OsConstants.O_RDWR; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 67import static com.android.internal.util.ArrayUtils.appendInt; 68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 73 74import android.Manifest; 75import android.app.ActivityManager; 76import android.app.ActivityManagerNative; 77import android.app.AppGlobals; 78import android.app.IActivityManager; 79import android.app.admin.IDevicePolicyManager; 80import android.app.backup.IBackupManager; 81import android.app.usage.UsageStats; 82import android.app.usage.UsageStatsManager; 83import android.content.BroadcastReceiver; 84import android.content.ComponentName; 85import android.content.Context; 86import android.content.IIntentReceiver; 87import android.content.Intent; 88import android.content.IntentFilter; 89import android.content.IntentSender; 90import android.content.IntentSender.SendIntentException; 91import android.content.ServiceConnection; 92import android.content.pm.ActivityInfo; 93import android.content.pm.ApplicationInfo; 94import android.content.pm.FeatureInfo; 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.PackageParser; 114import android.content.pm.PackageParser.ActivityIntentInfo; 115import android.content.pm.PackageParser.PackageLite; 116import android.content.pm.PackageParser.PackageParserException; 117import android.content.pm.PackageStats; 118import android.content.pm.PackageUserState; 119import android.content.pm.ParceledListSlice; 120import android.content.pm.PermissionGroupInfo; 121import android.content.pm.PermissionInfo; 122import android.content.pm.ProviderInfo; 123import android.content.pm.ResolveInfo; 124import android.content.pm.ServiceInfo; 125import android.content.pm.Signature; 126import android.content.pm.UserInfo; 127import android.content.pm.VerificationParams; 128import android.content.pm.VerifierDeviceIdentity; 129import android.content.pm.VerifierInfo; 130import android.content.res.Resources; 131import android.hardware.display.DisplayManager; 132import android.net.Uri; 133import android.os.Binder; 134import android.os.Build; 135import android.os.Bundle; 136import android.os.Debug; 137import android.os.Environment; 138import android.os.Environment.UserEnvironment; 139import android.os.FileUtils; 140import android.os.Handler; 141import android.os.IBinder; 142import android.os.Looper; 143import android.os.Message; 144import android.os.Parcel; 145import android.os.ParcelFileDescriptor; 146import android.os.Process; 147import android.os.RemoteCallbackList; 148import android.os.RemoteException; 149import android.os.SELinux; 150import android.os.ServiceManager; 151import android.os.SystemClock; 152import android.os.SystemProperties; 153import android.os.UserHandle; 154import android.os.UserManager; 155import android.os.storage.IMountService; 156import android.os.storage.StorageEventListener; 157import android.os.storage.StorageManager; 158import android.os.storage.VolumeInfo; 159import android.os.storage.VolumeRecord; 160import android.security.KeyStore; 161import android.security.SystemKeyStore; 162import android.system.ErrnoException; 163import android.system.Os; 164import android.system.StructStat; 165import android.text.TextUtils; 166import android.text.format.DateUtils; 167import android.util.ArrayMap; 168import android.util.ArraySet; 169import android.util.AtomicFile; 170import android.util.DisplayMetrics; 171import android.util.EventLog; 172import android.util.ExceptionUtils; 173import android.util.Log; 174import android.util.LogPrinter; 175import android.util.MathUtils; 176import android.util.PrintStreamPrinter; 177import android.util.Slog; 178import android.util.SparseArray; 179import android.util.SparseBooleanArray; 180import android.util.SparseIntArray; 181import android.util.Xml; 182import android.view.Display; 183 184import dalvik.system.DexFile; 185import dalvik.system.VMRuntime; 186 187import libcore.io.IoUtils; 188import libcore.util.EmptyArray; 189 190import com.android.internal.R; 191import com.android.internal.app.IMediaContainerService; 192import com.android.internal.app.ResolverActivity; 193import com.android.internal.content.NativeLibraryHelper; 194import com.android.internal.content.PackageHelper; 195import com.android.internal.os.IParcelFileDescriptorFactory; 196import com.android.internal.os.SomeArgs; 197import com.android.internal.util.ArrayUtils; 198import com.android.internal.util.FastPrintWriter; 199import com.android.internal.util.FastXmlSerializer; 200import com.android.internal.util.IndentingPrintWriter; 201import com.android.internal.util.Preconditions; 202import com.android.server.EventLogTags; 203import com.android.server.FgThread; 204import com.android.server.IntentResolver; 205import com.android.server.LocalServices; 206import com.android.server.ServiceThread; 207import com.android.server.SystemConfig; 208import com.android.server.Watchdog; 209import com.android.server.pm.Settings.DatabaseVersion; 210import com.android.server.pm.PermissionsState.PermissionState; 211import com.android.server.storage.DeviceStorageMonitorInternal; 212 213import org.xmlpull.v1.XmlPullParser; 214import org.xmlpull.v1.XmlSerializer; 215 216import java.io.BufferedInputStream; 217import java.io.BufferedOutputStream; 218import java.io.BufferedReader; 219import java.io.ByteArrayInputStream; 220import java.io.ByteArrayOutputStream; 221import java.io.File; 222import java.io.FileDescriptor; 223import java.io.FileNotFoundException; 224import java.io.FileOutputStream; 225import java.io.FileReader; 226import java.io.FilenameFilter; 227import java.io.IOException; 228import java.io.InputStream; 229import java.io.PrintWriter; 230import java.nio.charset.StandardCharsets; 231import java.security.NoSuchAlgorithmException; 232import java.security.PublicKey; 233import java.security.cert.CertificateEncodingException; 234import java.security.cert.CertificateException; 235import java.text.SimpleDateFormat; 236import java.util.ArrayList; 237import java.util.Arrays; 238import java.util.Collection; 239import java.util.Collections; 240import java.util.Comparator; 241import java.util.Date; 242import java.util.Iterator; 243import java.util.List; 244import java.util.Map; 245import java.util.Objects; 246import java.util.Set; 247import java.util.concurrent.CountDownLatch; 248import java.util.concurrent.TimeUnit; 249import java.util.concurrent.atomic.AtomicBoolean; 250import java.util.concurrent.atomic.AtomicInteger; 251import java.util.concurrent.atomic.AtomicLong; 252 253/** 254 * Keep track of all those .apks everywhere. 255 * 256 * This is very central to the platform's security; please run the unit 257 * tests whenever making modifications here: 258 * 259mmm frameworks/base/tests/AndroidTests 260adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 261adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 262 * 263 * {@hide} 264 */ 265public class PackageManagerService extends IPackageManager.Stub { 266 static final String TAG = "PackageManager"; 267 static final boolean DEBUG_SETTINGS = false; 268 static final boolean DEBUG_PREFERRED = false; 269 static final boolean DEBUG_UPGRADE = false; 270 private static final boolean DEBUG_BACKUP = true; 271 private static final boolean DEBUG_INSTALL = false; 272 private static final boolean DEBUG_REMOVE = false; 273 private static final boolean DEBUG_BROADCASTS = false; 274 private static final boolean DEBUG_SHOW_INFO = false; 275 private static final boolean DEBUG_PACKAGE_INFO = false; 276 private static final boolean DEBUG_INTENT_MATCHING = false; 277 private static final boolean DEBUG_PACKAGE_SCANNING = false; 278 private static final boolean DEBUG_VERIFY = false; 279 private static final boolean DEBUG_DEXOPT = false; 280 private static final boolean DEBUG_ABI_SELECTION = false; 281 private static final boolean DEBUG_DOMAIN_VERIFICATION = false; 282 283 private static final int RADIO_UID = Process.PHONE_UID; 284 private static final int LOG_UID = Process.LOG_UID; 285 private static final int NFC_UID = Process.NFC_UID; 286 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 287 private static final int SHELL_UID = Process.SHELL_UID; 288 289 // Cap the size of permission trees that 3rd party apps can define 290 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 291 292 // Suffix used during package installation when copying/moving 293 // package apks to install directory. 294 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 295 296 static final int SCAN_NO_DEX = 1<<1; 297 static final int SCAN_FORCE_DEX = 1<<2; 298 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 299 static final int SCAN_NEW_INSTALL = 1<<4; 300 static final int SCAN_NO_PATHS = 1<<5; 301 static final int SCAN_UPDATE_TIME = 1<<6; 302 static final int SCAN_DEFER_DEX = 1<<7; 303 static final int SCAN_BOOTING = 1<<8; 304 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 305 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 306 static final int SCAN_REQUIRE_KNOWN = 1<<12; 307 static final int SCAN_MOVE = 1<<13; 308 309 static final int REMOVE_CHATTY = 1<<16; 310 311 private static final int[] EMPTY_INT_ARRAY = new int[0]; 312 313 /** 314 * Timeout (in milliseconds) after which the watchdog should declare that 315 * our handler thread is wedged. The usual default for such things is one 316 * minute but we sometimes do very lengthy I/O operations on this thread, 317 * such as installing multi-gigabyte applications, so ours needs to be longer. 318 */ 319 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 320 321 /** 322 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 323 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 324 * settings entry if available, otherwise we use the hardcoded default. If it's been 325 * more than this long since the last fstrim, we force one during the boot sequence. 326 * 327 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 328 * one gets run at the next available charging+idle time. This final mandatory 329 * no-fstrim check kicks in only of the other scheduling criteria is never met. 330 */ 331 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 332 333 /** 334 * Whether verification is enabled by default. 335 */ 336 private static final boolean DEFAULT_VERIFY_ENABLE = true; 337 338 /** 339 * The default maximum time to wait for the verification agent to return in 340 * milliseconds. 341 */ 342 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 343 344 /** 345 * The default response for package verification timeout. 346 * 347 * This can be either PackageManager.VERIFICATION_ALLOW or 348 * PackageManager.VERIFICATION_REJECT. 349 */ 350 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 351 352 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 353 354 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 355 DEFAULT_CONTAINER_PACKAGE, 356 "com.android.defcontainer.DefaultContainerService"); 357 358 private static final String KILL_APP_REASON_GIDS_CHANGED = 359 "permission grant or revoke changed gids"; 360 361 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 362 "permissions revoked"; 363 364 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 365 366 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 367 368 /** Permission grant: not grant the permission. */ 369 private static final int GRANT_DENIED = 1; 370 371 /** Permission grant: grant the permission as an install permission. */ 372 private static final int GRANT_INSTALL = 2; 373 374 /** Permission grant: grant the permission as an install permission for a legacy app. */ 375 private static final int GRANT_INSTALL_LEGACY = 3; 376 377 /** Permission grant: grant the permission as a runtime one. */ 378 private static final int GRANT_RUNTIME = 4; 379 380 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 381 private static final int GRANT_UPGRADE = 5; 382 383 final ServiceThread mHandlerThread; 384 385 final PackageHandler mHandler; 386 387 /** 388 * Messages for {@link #mHandler} that need to wait for system ready before 389 * being dispatched. 390 */ 391 private ArrayList<Message> mPostSystemReadyMessages; 392 393 final int mSdkVersion = Build.VERSION.SDK_INT; 394 395 final Context mContext; 396 final boolean mFactoryTest; 397 final boolean mOnlyCore; 398 final boolean mLazyDexOpt; 399 final long mDexOptLRUThresholdInMills; 400 final DisplayMetrics mMetrics; 401 final int mDefParseFlags; 402 final String[] mSeparateProcesses; 403 final boolean mIsUpgrade; 404 405 // This is where all application persistent data goes. 406 final File mAppDataDir; 407 408 // This is where all application persistent data goes for secondary users. 409 final File mUserAppDataDir; 410 411 /** The location for ASEC container files on internal storage. */ 412 final String mAsecInternalPath; 413 414 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 415 // LOCK HELD. Can be called with mInstallLock held. 416 final Installer mInstaller; 417 418 /** Directory where installed third-party apps stored */ 419 final File mAppInstallDir; 420 421 /** 422 * Directory to which applications installed internally have their 423 * 32 bit native libraries copied. 424 */ 425 private File mAppLib32InstallDir; 426 427 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 428 // apps. 429 final File mDrmAppPrivateInstallDir; 430 431 // ---------------------------------------------------------------- 432 433 // Lock for state used when installing and doing other long running 434 // operations. Methods that must be called with this lock held have 435 // the suffix "LI". 436 final Object mInstallLock = new Object(); 437 438 // ---------------------------------------------------------------- 439 440 // Keys are String (package name), values are Package. This also serves 441 // as the lock for the global state. Methods that must be called with 442 // this lock held have the prefix "LP". 443 final ArrayMap<String, PackageParser.Package> mPackages = 444 new ArrayMap<String, PackageParser.Package>(); 445 446 // Tracks available target package names -> overlay package paths. 447 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 448 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 449 450 final Settings mSettings; 451 boolean mRestoredSettings; 452 453 // System configuration read by SystemConfig. 454 final int[] mGlobalGids; 455 final SparseArray<ArraySet<String>> mSystemPermissions; 456 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 457 458 // If mac_permissions.xml was found for seinfo labeling. 459 boolean mFoundPolicyFile; 460 461 // If a recursive restorecon of /data/data/<pkg> is needed. 462 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 463 464 public static final class SharedLibraryEntry { 465 public final String path; 466 public final String apk; 467 468 SharedLibraryEntry(String _path, String _apk) { 469 path = _path; 470 apk = _apk; 471 } 472 } 473 474 // Currently known shared libraries. 475 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 476 new ArrayMap<String, SharedLibraryEntry>(); 477 478 // All available activities, for your resolving pleasure. 479 final ActivityIntentResolver mActivities = 480 new ActivityIntentResolver(); 481 482 // All available receivers, for your resolving pleasure. 483 final ActivityIntentResolver mReceivers = 484 new ActivityIntentResolver(); 485 486 // All available services, for your resolving pleasure. 487 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 488 489 // All available providers, for your resolving pleasure. 490 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 491 492 // Mapping from provider base names (first directory in content URI codePath) 493 // to the provider information. 494 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 495 new ArrayMap<String, PackageParser.Provider>(); 496 497 // Mapping from instrumentation class names to info about them. 498 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 499 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 500 501 // Mapping from permission names to info about them. 502 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 503 new ArrayMap<String, PackageParser.PermissionGroup>(); 504 505 // Packages whose data we have transfered into another package, thus 506 // should no longer exist. 507 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 508 509 // Broadcast actions that are only available to the system. 510 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 511 512 /** List of packages waiting for verification. */ 513 final SparseArray<PackageVerificationState> mPendingVerification 514 = new SparseArray<PackageVerificationState>(); 515 516 /** Set of packages associated with each app op permission. */ 517 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 518 519 final PackageInstallerService mInstallerService; 520 521 private final PackageDexOptimizer mPackageDexOptimizer; 522 523 private AtomicInteger mNextMoveId = new AtomicInteger(); 524 private final MoveCallbacks mMoveCallbacks; 525 526 // Cache of users who need badging. 527 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 528 529 /** Token for keys in mPendingVerification. */ 530 private int mPendingVerificationToken = 0; 531 532 volatile boolean mSystemReady; 533 volatile boolean mSafeMode; 534 volatile boolean mHasSystemUidErrors; 535 536 ApplicationInfo mAndroidApplication; 537 final ActivityInfo mResolveActivity = new ActivityInfo(); 538 final ResolveInfo mResolveInfo = new ResolveInfo(); 539 ComponentName mResolveComponentName; 540 PackageParser.Package mPlatformPackage; 541 ComponentName mCustomResolverComponentName; 542 543 boolean mResolverReplaced = false; 544 545 private final ComponentName mIntentFilterVerifierComponent; 546 private int mIntentFilterVerificationToken = 0; 547 548 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 549 = new SparseArray<IntentFilterVerificationState>(); 550 551 private interface IntentFilterVerifier<T extends IntentFilter> { 552 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 553 T filter, String packageName); 554 void startVerifications(int userId); 555 void receiveVerificationResponse(int verificationId); 556 } 557 558 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 559 private Context mContext; 560 private ComponentName mIntentFilterVerifierComponent; 561 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 562 563 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 564 mContext = context; 565 mIntentFilterVerifierComponent = verifierComponent; 566 } 567 568 private String getDefaultScheme() { 569 return IntentFilter.SCHEME_HTTPS; 570 } 571 572 @Override 573 public void startVerifications(int userId) { 574 // Launch verifications requests 575 int count = mCurrentIntentFilterVerifications.size(); 576 for (int n=0; n<count; n++) { 577 int verificationId = mCurrentIntentFilterVerifications.get(n); 578 final IntentFilterVerificationState ivs = 579 mIntentFilterVerificationStates.get(verificationId); 580 581 String packageName = ivs.getPackageName(); 582 583 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 584 final int filterCount = filters.size(); 585 ArraySet<String> domainsSet = new ArraySet<>(); 586 for (int m=0; m<filterCount; m++) { 587 PackageParser.ActivityIntentInfo filter = filters.get(m); 588 domainsSet.addAll(filter.getHostsList()); 589 } 590 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 591 synchronized (mPackages) { 592 if (mSettings.createIntentFilterVerificationIfNeededLPw( 593 packageName, domainsList) != null) { 594 scheduleWriteSettingsLocked(); 595 } 596 } 597 sendVerificationRequest(userId, verificationId, ivs); 598 } 599 mCurrentIntentFilterVerifications.clear(); 600 } 601 602 private void sendVerificationRequest(int userId, int verificationId, 603 IntentFilterVerificationState ivs) { 604 605 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 606 verificationIntent.putExtra( 607 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 608 verificationId); 609 verificationIntent.putExtra( 610 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 611 getDefaultScheme()); 612 verificationIntent.putExtra( 613 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 614 ivs.getHostsString()); 615 verificationIntent.putExtra( 616 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 617 ivs.getPackageName()); 618 verificationIntent.setComponent(mIntentFilterVerifierComponent); 619 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 620 621 UserHandle user = new UserHandle(userId); 622 mContext.sendBroadcastAsUser(verificationIntent, user); 623 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 624 "Sending IntenFilter verification broadcast"); 625 } 626 627 public void receiveVerificationResponse(int verificationId) { 628 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 629 630 final boolean verified = ivs.isVerified(); 631 632 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 633 final int count = filters.size(); 634 for (int n=0; n<count; n++) { 635 PackageParser.ActivityIntentInfo filter = filters.get(n); 636 filter.setVerified(verified); 637 638 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 639 + " verified with result:" + verified + " and hosts:" 640 + ivs.getHostsString()); 641 } 642 643 mIntentFilterVerificationStates.remove(verificationId); 644 645 final String packageName = ivs.getPackageName(); 646 IntentFilterVerificationInfo ivi = null; 647 648 synchronized (mPackages) { 649 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 650 } 651 if (ivi == null) { 652 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 653 + verificationId + " packageName:" + packageName); 654 return; 655 } 656 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 657 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 658 659 synchronized (mPackages) { 660 if (verified) { 661 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 662 } else { 663 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 664 } 665 scheduleWriteSettingsLocked(); 666 667 final int userId = ivs.getUserId(); 668 if (userId != UserHandle.USER_ALL) { 669 final int userStatus = 670 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 671 672 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 673 boolean needUpdate = false; 674 675 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 676 // already been set by the User thru the Disambiguation dialog 677 switch (userStatus) { 678 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 679 if (verified) { 680 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 681 } else { 682 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 683 } 684 needUpdate = true; 685 break; 686 687 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 688 if (verified) { 689 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 690 needUpdate = true; 691 } 692 break; 693 694 default: 695 // Nothing to do 696 } 697 698 if (needUpdate) { 699 mSettings.updateIntentFilterVerificationStatusLPw( 700 packageName, updatedStatus, userId); 701 scheduleWritePackageRestrictionsLocked(userId); 702 } 703 } 704 } 705 } 706 707 @Override 708 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 709 ActivityIntentInfo filter, String packageName) { 710 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 711 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 712 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 713 "IntentFilter does not contain HTTP nor HTTPS data scheme"); 714 return false; 715 } 716 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 717 if (ivs == null) { 718 ivs = createDomainVerificationState(verifierId, userId, verificationId, 719 packageName); 720 } 721 if (!hasValidDomains(filter)) { 722 return false; 723 } 724 ivs.addFilter(filter); 725 return true; 726 } 727 728 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 729 int userId, int verificationId, String packageName) { 730 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 731 verifierId, userId, packageName); 732 ivs.setPendingState(); 733 synchronized (mPackages) { 734 mIntentFilterVerificationStates.append(verificationId, ivs); 735 mCurrentIntentFilterVerifications.add(verificationId); 736 } 737 return ivs; 738 } 739 } 740 741 private static boolean hasValidDomains(ActivityIntentInfo filter) { 742 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 743 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 744 if (!hasHTTPorHTTPS) { 745 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 746 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 747 return false; 748 } 749 return true; 750 } 751 752 private IntentFilterVerifier mIntentFilterVerifier; 753 754 // Set of pending broadcasts for aggregating enable/disable of components. 755 static class PendingPackageBroadcasts { 756 // for each user id, a map of <package name -> components within that package> 757 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 758 759 public PendingPackageBroadcasts() { 760 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 761 } 762 763 public ArrayList<String> get(int userId, String packageName) { 764 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 765 return packages.get(packageName); 766 } 767 768 public void put(int userId, String packageName, ArrayList<String> components) { 769 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 770 packages.put(packageName, components); 771 } 772 773 public void remove(int userId, String packageName) { 774 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 775 if (packages != null) { 776 packages.remove(packageName); 777 } 778 } 779 780 public void remove(int userId) { 781 mUidMap.remove(userId); 782 } 783 784 public int userIdCount() { 785 return mUidMap.size(); 786 } 787 788 public int userIdAt(int n) { 789 return mUidMap.keyAt(n); 790 } 791 792 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 793 return mUidMap.get(userId); 794 } 795 796 public int size() { 797 // total number of pending broadcast entries across all userIds 798 int num = 0; 799 for (int i = 0; i< mUidMap.size(); i++) { 800 num += mUidMap.valueAt(i).size(); 801 } 802 return num; 803 } 804 805 public void clear() { 806 mUidMap.clear(); 807 } 808 809 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 810 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 811 if (map == null) { 812 map = new ArrayMap<String, ArrayList<String>>(); 813 mUidMap.put(userId, map); 814 } 815 return map; 816 } 817 } 818 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 819 820 // Service Connection to remote media container service to copy 821 // package uri's from external media onto secure containers 822 // or internal storage. 823 private IMediaContainerService mContainerService = null; 824 825 static final int SEND_PENDING_BROADCAST = 1; 826 static final int MCS_BOUND = 3; 827 static final int END_COPY = 4; 828 static final int INIT_COPY = 5; 829 static final int MCS_UNBIND = 6; 830 static final int START_CLEANING_PACKAGE = 7; 831 static final int FIND_INSTALL_LOC = 8; 832 static final int POST_INSTALL = 9; 833 static final int MCS_RECONNECT = 10; 834 static final int MCS_GIVE_UP = 11; 835 static final int UPDATED_MEDIA_STATUS = 12; 836 static final int WRITE_SETTINGS = 13; 837 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 838 static final int PACKAGE_VERIFIED = 15; 839 static final int CHECK_PENDING_VERIFICATION = 16; 840 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 841 static final int INTENT_FILTER_VERIFIED = 18; 842 843 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 844 845 // Delay time in millisecs 846 static final int BROADCAST_DELAY = 10 * 1000; 847 848 static UserManagerService sUserManager; 849 850 // Stores a list of users whose package restrictions file needs to be updated 851 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 852 853 final private DefaultContainerConnection mDefContainerConn = 854 new DefaultContainerConnection(); 855 class DefaultContainerConnection implements ServiceConnection { 856 public void onServiceConnected(ComponentName name, IBinder service) { 857 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 858 IMediaContainerService imcs = 859 IMediaContainerService.Stub.asInterface(service); 860 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 861 } 862 863 public void onServiceDisconnected(ComponentName name) { 864 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 865 } 866 }; 867 868 // Recordkeeping of restore-after-install operations that are currently in flight 869 // between the Package Manager and the Backup Manager 870 class PostInstallData { 871 public InstallArgs args; 872 public PackageInstalledInfo res; 873 874 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 875 args = _a; 876 res = _r; 877 } 878 }; 879 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 880 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 881 882 // backup/restore of preferred activity state 883 private static final String TAG_PREFERRED_BACKUP = "pa"; 884 885 private final String mRequiredVerifierPackage; 886 887 private final PackageUsage mPackageUsage = new PackageUsage(); 888 889 private class PackageUsage { 890 private static final int WRITE_INTERVAL 891 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 892 893 private final Object mFileLock = new Object(); 894 private final AtomicLong mLastWritten = new AtomicLong(0); 895 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 896 897 private boolean mIsHistoricalPackageUsageAvailable = true; 898 899 boolean isHistoricalPackageUsageAvailable() { 900 return mIsHistoricalPackageUsageAvailable; 901 } 902 903 void write(boolean force) { 904 if (force) { 905 writeInternal(); 906 return; 907 } 908 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 909 && !DEBUG_DEXOPT) { 910 return; 911 } 912 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 913 new Thread("PackageUsage_DiskWriter") { 914 @Override 915 public void run() { 916 try { 917 writeInternal(); 918 } finally { 919 mBackgroundWriteRunning.set(false); 920 } 921 } 922 }.start(); 923 } 924 } 925 926 private void writeInternal() { 927 synchronized (mPackages) { 928 synchronized (mFileLock) { 929 AtomicFile file = getFile(); 930 FileOutputStream f = null; 931 try { 932 f = file.startWrite(); 933 BufferedOutputStream out = new BufferedOutputStream(f); 934 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 935 StringBuilder sb = new StringBuilder(); 936 for (PackageParser.Package pkg : mPackages.values()) { 937 if (pkg.mLastPackageUsageTimeInMills == 0) { 938 continue; 939 } 940 sb.setLength(0); 941 sb.append(pkg.packageName); 942 sb.append(' '); 943 sb.append((long)pkg.mLastPackageUsageTimeInMills); 944 sb.append('\n'); 945 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 946 } 947 out.flush(); 948 file.finishWrite(f); 949 } catch (IOException e) { 950 if (f != null) { 951 file.failWrite(f); 952 } 953 Log.e(TAG, "Failed to write package usage times", e); 954 } 955 } 956 } 957 mLastWritten.set(SystemClock.elapsedRealtime()); 958 } 959 960 void readLP() { 961 synchronized (mFileLock) { 962 AtomicFile file = getFile(); 963 BufferedInputStream in = null; 964 try { 965 in = new BufferedInputStream(file.openRead()); 966 StringBuffer sb = new StringBuffer(); 967 while (true) { 968 String packageName = readToken(in, sb, ' '); 969 if (packageName == null) { 970 break; 971 } 972 String timeInMillisString = readToken(in, sb, '\n'); 973 if (timeInMillisString == null) { 974 throw new IOException("Failed to find last usage time for package " 975 + packageName); 976 } 977 PackageParser.Package pkg = mPackages.get(packageName); 978 if (pkg == null) { 979 continue; 980 } 981 long timeInMillis; 982 try { 983 timeInMillis = Long.parseLong(timeInMillisString.toString()); 984 } catch (NumberFormatException e) { 985 throw new IOException("Failed to parse " + timeInMillisString 986 + " as a long.", e); 987 } 988 pkg.mLastPackageUsageTimeInMills = timeInMillis; 989 } 990 } catch (FileNotFoundException expected) { 991 mIsHistoricalPackageUsageAvailable = false; 992 } catch (IOException e) { 993 Log.w(TAG, "Failed to read package usage times", e); 994 } finally { 995 IoUtils.closeQuietly(in); 996 } 997 } 998 mLastWritten.set(SystemClock.elapsedRealtime()); 999 } 1000 1001 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1002 throws IOException { 1003 sb.setLength(0); 1004 while (true) { 1005 int ch = in.read(); 1006 if (ch == -1) { 1007 if (sb.length() == 0) { 1008 return null; 1009 } 1010 throw new IOException("Unexpected EOF"); 1011 } 1012 if (ch == endOfToken) { 1013 return sb.toString(); 1014 } 1015 sb.append((char)ch); 1016 } 1017 } 1018 1019 private AtomicFile getFile() { 1020 File dataDir = Environment.getDataDirectory(); 1021 File systemDir = new File(dataDir, "system"); 1022 File fname = new File(systemDir, "package-usage.list"); 1023 return new AtomicFile(fname); 1024 } 1025 } 1026 1027 class PackageHandler extends Handler { 1028 private boolean mBound = false; 1029 final ArrayList<HandlerParams> mPendingInstalls = 1030 new ArrayList<HandlerParams>(); 1031 1032 private boolean connectToService() { 1033 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1034 " DefaultContainerService"); 1035 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1037 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1038 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1039 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1040 mBound = true; 1041 return true; 1042 } 1043 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1044 return false; 1045 } 1046 1047 private void disconnectService() { 1048 mContainerService = null; 1049 mBound = false; 1050 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1051 mContext.unbindService(mDefContainerConn); 1052 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1053 } 1054 1055 PackageHandler(Looper looper) { 1056 super(looper); 1057 } 1058 1059 public void handleMessage(Message msg) { 1060 try { 1061 doHandleMessage(msg); 1062 } finally { 1063 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1064 } 1065 } 1066 1067 void doHandleMessage(Message msg) { 1068 switch (msg.what) { 1069 case INIT_COPY: { 1070 HandlerParams params = (HandlerParams) msg.obj; 1071 int idx = mPendingInstalls.size(); 1072 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1073 // If a bind was already initiated we dont really 1074 // need to do anything. The pending install 1075 // will be processed later on. 1076 if (!mBound) { 1077 // If this is the only one pending we might 1078 // have to bind to the service again. 1079 if (!connectToService()) { 1080 Slog.e(TAG, "Failed to bind to media container service"); 1081 params.serviceError(); 1082 return; 1083 } else { 1084 // Once we bind to the service, the first 1085 // pending request will be processed. 1086 mPendingInstalls.add(idx, params); 1087 } 1088 } else { 1089 mPendingInstalls.add(idx, params); 1090 // Already bound to the service. Just make 1091 // sure we trigger off processing the first request. 1092 if (idx == 0) { 1093 mHandler.sendEmptyMessage(MCS_BOUND); 1094 } 1095 } 1096 break; 1097 } 1098 case MCS_BOUND: { 1099 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1100 if (msg.obj != null) { 1101 mContainerService = (IMediaContainerService) msg.obj; 1102 } 1103 if (mContainerService == null) { 1104 // Something seriously wrong. Bail out 1105 Slog.e(TAG, "Cannot bind to media container service"); 1106 for (HandlerParams params : mPendingInstalls) { 1107 // Indicate service bind error 1108 params.serviceError(); 1109 } 1110 mPendingInstalls.clear(); 1111 } else if (mPendingInstalls.size() > 0) { 1112 HandlerParams params = mPendingInstalls.get(0); 1113 if (params != null) { 1114 if (params.startCopy()) { 1115 // We are done... look for more work or to 1116 // go idle. 1117 if (DEBUG_SD_INSTALL) Log.i(TAG, 1118 "Checking for more work or unbind..."); 1119 // Delete pending install 1120 if (mPendingInstalls.size() > 0) { 1121 mPendingInstalls.remove(0); 1122 } 1123 if (mPendingInstalls.size() == 0) { 1124 if (mBound) { 1125 if (DEBUG_SD_INSTALL) Log.i(TAG, 1126 "Posting delayed MCS_UNBIND"); 1127 removeMessages(MCS_UNBIND); 1128 Message ubmsg = obtainMessage(MCS_UNBIND); 1129 // Unbind after a little delay, to avoid 1130 // continual thrashing. 1131 sendMessageDelayed(ubmsg, 10000); 1132 } 1133 } else { 1134 // There are more pending requests in queue. 1135 // Just post MCS_BOUND message to trigger processing 1136 // of next pending install. 1137 if (DEBUG_SD_INSTALL) Log.i(TAG, 1138 "Posting MCS_BOUND for next work"); 1139 mHandler.sendEmptyMessage(MCS_BOUND); 1140 } 1141 } 1142 } 1143 } else { 1144 // Should never happen ideally. 1145 Slog.w(TAG, "Empty queue"); 1146 } 1147 break; 1148 } 1149 case MCS_RECONNECT: { 1150 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1151 if (mPendingInstalls.size() > 0) { 1152 if (mBound) { 1153 disconnectService(); 1154 } 1155 if (!connectToService()) { 1156 Slog.e(TAG, "Failed to bind to media container service"); 1157 for (HandlerParams params : mPendingInstalls) { 1158 // Indicate service bind error 1159 params.serviceError(); 1160 } 1161 mPendingInstalls.clear(); 1162 } 1163 } 1164 break; 1165 } 1166 case MCS_UNBIND: { 1167 // If there is no actual work left, then time to unbind. 1168 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1169 1170 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1171 if (mBound) { 1172 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1173 1174 disconnectService(); 1175 } 1176 } else if (mPendingInstalls.size() > 0) { 1177 // There are more pending requests in queue. 1178 // Just post MCS_BOUND message to trigger processing 1179 // of next pending install. 1180 mHandler.sendEmptyMessage(MCS_BOUND); 1181 } 1182 1183 break; 1184 } 1185 case MCS_GIVE_UP: { 1186 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1187 mPendingInstalls.remove(0); 1188 break; 1189 } 1190 case SEND_PENDING_BROADCAST: { 1191 String packages[]; 1192 ArrayList<String> components[]; 1193 int size = 0; 1194 int uids[]; 1195 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1196 synchronized (mPackages) { 1197 if (mPendingBroadcasts == null) { 1198 return; 1199 } 1200 size = mPendingBroadcasts.size(); 1201 if (size <= 0) { 1202 // Nothing to be done. Just return 1203 return; 1204 } 1205 packages = new String[size]; 1206 components = new ArrayList[size]; 1207 uids = new int[size]; 1208 int i = 0; // filling out the above arrays 1209 1210 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1211 int packageUserId = mPendingBroadcasts.userIdAt(n); 1212 Iterator<Map.Entry<String, ArrayList<String>>> it 1213 = mPendingBroadcasts.packagesForUserId(packageUserId) 1214 .entrySet().iterator(); 1215 while (it.hasNext() && i < size) { 1216 Map.Entry<String, ArrayList<String>> ent = it.next(); 1217 packages[i] = ent.getKey(); 1218 components[i] = ent.getValue(); 1219 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1220 uids[i] = (ps != null) 1221 ? UserHandle.getUid(packageUserId, ps.appId) 1222 : -1; 1223 i++; 1224 } 1225 } 1226 size = i; 1227 mPendingBroadcasts.clear(); 1228 } 1229 // Send broadcasts 1230 for (int i = 0; i < size; i++) { 1231 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1232 } 1233 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1234 break; 1235 } 1236 case START_CLEANING_PACKAGE: { 1237 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1238 final String packageName = (String)msg.obj; 1239 final int userId = msg.arg1; 1240 final boolean andCode = msg.arg2 != 0; 1241 synchronized (mPackages) { 1242 if (userId == UserHandle.USER_ALL) { 1243 int[] users = sUserManager.getUserIds(); 1244 for (int user : users) { 1245 mSettings.addPackageToCleanLPw( 1246 new PackageCleanItem(user, packageName, andCode)); 1247 } 1248 } else { 1249 mSettings.addPackageToCleanLPw( 1250 new PackageCleanItem(userId, packageName, andCode)); 1251 } 1252 } 1253 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1254 startCleaningPackages(); 1255 } break; 1256 case POST_INSTALL: { 1257 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1258 PostInstallData data = mRunningInstalls.get(msg.arg1); 1259 mRunningInstalls.delete(msg.arg1); 1260 boolean deleteOld = false; 1261 1262 if (data != null) { 1263 InstallArgs args = data.args; 1264 PackageInstalledInfo res = data.res; 1265 1266 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1267 res.removedInfo.sendBroadcast(false, true, false); 1268 Bundle extras = new Bundle(1); 1269 extras.putInt(Intent.EXTRA_UID, res.uid); 1270 1271 // Now that we successfully installed the package, grant runtime 1272 // permissions if requested before broadcasting the install. 1273 if ((args.installFlags 1274 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1275 grantRequestedRuntimePermissions(res.pkg, 1276 args.user.getIdentifier()); 1277 } 1278 1279 // Determine the set of users who are adding this 1280 // package for the first time vs. those who are seeing 1281 // an update. 1282 int[] firstUsers; 1283 int[] updateUsers = new int[0]; 1284 if (res.origUsers == null || res.origUsers.length == 0) { 1285 firstUsers = res.newUsers; 1286 } else { 1287 firstUsers = new int[0]; 1288 for (int i=0; i<res.newUsers.length; i++) { 1289 int user = res.newUsers[i]; 1290 boolean isNew = true; 1291 for (int j=0; j<res.origUsers.length; j++) { 1292 if (res.origUsers[j] == user) { 1293 isNew = false; 1294 break; 1295 } 1296 } 1297 if (isNew) { 1298 int[] newFirst = new int[firstUsers.length+1]; 1299 System.arraycopy(firstUsers, 0, newFirst, 0, 1300 firstUsers.length); 1301 newFirst[firstUsers.length] = user; 1302 firstUsers = newFirst; 1303 } else { 1304 int[] newUpdate = new int[updateUsers.length+1]; 1305 System.arraycopy(updateUsers, 0, newUpdate, 0, 1306 updateUsers.length); 1307 newUpdate[updateUsers.length] = user; 1308 updateUsers = newUpdate; 1309 } 1310 } 1311 } 1312 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1313 res.pkg.applicationInfo.packageName, 1314 extras, null, null, firstUsers); 1315 final boolean update = res.removedInfo.removedPackage != null; 1316 if (update) { 1317 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1318 } 1319 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1320 res.pkg.applicationInfo.packageName, 1321 extras, null, null, updateUsers); 1322 if (update) { 1323 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1324 res.pkg.applicationInfo.packageName, 1325 extras, null, null, updateUsers); 1326 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1327 null, null, 1328 res.pkg.applicationInfo.packageName, null, updateUsers); 1329 1330 // treat asec-hosted packages like removable media on upgrade 1331 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1332 if (DEBUG_INSTALL) { 1333 Slog.i(TAG, "upgrading pkg " + res.pkg 1334 + " is ASEC-hosted -> AVAILABLE"); 1335 } 1336 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1337 ArrayList<String> pkgList = new ArrayList<String>(1); 1338 pkgList.add(res.pkg.applicationInfo.packageName); 1339 sendResourcesChangedBroadcast(true, true, 1340 pkgList,uidArray, null); 1341 } 1342 } 1343 if (res.removedInfo.args != null) { 1344 // Remove the replaced package's older resources safely now 1345 deleteOld = true; 1346 } 1347 1348 // Log current value of "unknown sources" setting 1349 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1350 getUnknownSourcesSettings()); 1351 } 1352 // Force a gc to clear up things 1353 Runtime.getRuntime().gc(); 1354 // We delete after a gc for applications on sdcard. 1355 if (deleteOld) { 1356 synchronized (mInstallLock) { 1357 res.removedInfo.args.doPostDeleteLI(true); 1358 } 1359 } 1360 if (args.observer != null) { 1361 try { 1362 Bundle extras = extrasForInstallResult(res); 1363 args.observer.onPackageInstalled(res.name, res.returnCode, 1364 res.returnMsg, extras); 1365 } catch (RemoteException e) { 1366 Slog.i(TAG, "Observer no longer exists."); 1367 } 1368 } 1369 } else { 1370 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1371 } 1372 } break; 1373 case UPDATED_MEDIA_STATUS: { 1374 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1375 boolean reportStatus = msg.arg1 == 1; 1376 boolean doGc = msg.arg2 == 1; 1377 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1378 if (doGc) { 1379 // Force a gc to clear up stale containers. 1380 Runtime.getRuntime().gc(); 1381 } 1382 if (msg.obj != null) { 1383 @SuppressWarnings("unchecked") 1384 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1385 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1386 // Unload containers 1387 unloadAllContainers(args); 1388 } 1389 if (reportStatus) { 1390 try { 1391 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1392 PackageHelper.getMountService().finishMediaUpdate(); 1393 } catch (RemoteException e) { 1394 Log.e(TAG, "MountService not running?"); 1395 } 1396 } 1397 } break; 1398 case WRITE_SETTINGS: { 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1400 synchronized (mPackages) { 1401 removeMessages(WRITE_SETTINGS); 1402 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1403 mSettings.writeLPr(); 1404 mDirtyUsers.clear(); 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 } break; 1408 case WRITE_PACKAGE_RESTRICTIONS: { 1409 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1410 synchronized (mPackages) { 1411 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1412 for (int userId : mDirtyUsers) { 1413 mSettings.writePackageRestrictionsLPr(userId); 1414 } 1415 mDirtyUsers.clear(); 1416 } 1417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1418 } break; 1419 case CHECK_PENDING_VERIFICATION: { 1420 final int verificationId = msg.arg1; 1421 final PackageVerificationState state = mPendingVerification.get(verificationId); 1422 1423 if ((state != null) && !state.timeoutExtended()) { 1424 final InstallArgs args = state.getInstallArgs(); 1425 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1426 1427 Slog.i(TAG, "Verification timed out for " + originUri); 1428 mPendingVerification.remove(verificationId); 1429 1430 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1431 1432 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1433 Slog.i(TAG, "Continuing with installation of " + originUri); 1434 state.setVerifierResponse(Binder.getCallingUid(), 1435 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1436 broadcastPackageVerified(verificationId, originUri, 1437 PackageManager.VERIFICATION_ALLOW, 1438 state.getInstallArgs().getUser()); 1439 try { 1440 ret = args.copyApk(mContainerService, true); 1441 } catch (RemoteException e) { 1442 Slog.e(TAG, "Could not contact the ContainerService"); 1443 } 1444 } else { 1445 broadcastPackageVerified(verificationId, originUri, 1446 PackageManager.VERIFICATION_REJECT, 1447 state.getInstallArgs().getUser()); 1448 } 1449 1450 processPendingInstall(args, ret); 1451 mHandler.sendEmptyMessage(MCS_UNBIND); 1452 } 1453 break; 1454 } 1455 case PACKAGE_VERIFIED: { 1456 final int verificationId = msg.arg1; 1457 1458 final PackageVerificationState state = mPendingVerification.get(verificationId); 1459 if (state == null) { 1460 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1461 break; 1462 } 1463 1464 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1465 1466 state.setVerifierResponse(response.callerUid, response.code); 1467 1468 if (state.isVerificationComplete()) { 1469 mPendingVerification.remove(verificationId); 1470 1471 final InstallArgs args = state.getInstallArgs(); 1472 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1473 1474 int ret; 1475 if (state.isInstallAllowed()) { 1476 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1477 broadcastPackageVerified(verificationId, originUri, 1478 response.code, state.getInstallArgs().getUser()); 1479 try { 1480 ret = args.copyApk(mContainerService, true); 1481 } catch (RemoteException e) { 1482 Slog.e(TAG, "Could not contact the ContainerService"); 1483 } 1484 } else { 1485 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1486 } 1487 1488 processPendingInstall(args, ret); 1489 1490 mHandler.sendEmptyMessage(MCS_UNBIND); 1491 } 1492 1493 break; 1494 } 1495 case START_INTENT_FILTER_VERIFICATIONS: { 1496 int userId = msg.arg1; 1497 int verifierUid = msg.arg2; 1498 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1499 1500 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1501 break; 1502 } 1503 case INTENT_FILTER_VERIFIED: { 1504 final int verificationId = msg.arg1; 1505 1506 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1507 verificationId); 1508 if (state == null) { 1509 Slog.w(TAG, "Invalid IntentFilter verification token " 1510 + verificationId + " received"); 1511 break; 1512 } 1513 1514 final int userId = state.getUserId(); 1515 1516 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1517 "Processing IntentFilter verification with token:" 1518 + verificationId + " and userId:" + userId); 1519 1520 final IntentFilterVerificationResponse response = 1521 (IntentFilterVerificationResponse) msg.obj; 1522 1523 state.setVerifierResponse(response.callerUid, response.code); 1524 1525 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1526 "IntentFilter verification with token:" + verificationId 1527 + " and userId:" + userId 1528 + " is settings verifier response with response code:" 1529 + response.code); 1530 1531 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1532 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1533 + response.getFailedDomainsString()); 1534 } 1535 1536 if (state.isVerificationComplete()) { 1537 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1538 } else { 1539 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1540 "IntentFilter verification with token:" + verificationId 1541 + " was not said to be complete"); 1542 } 1543 1544 break; 1545 } 1546 } 1547 } 1548 } 1549 1550 private StorageEventListener mStorageListener = new StorageEventListener() { 1551 @Override 1552 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1553 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1554 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1555 // TODO: ensure that private directories exist for all active users 1556 // TODO: remove user data whose serial number doesn't match 1557 loadPrivatePackages(vol); 1558 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1559 unloadPrivatePackages(vol); 1560 } 1561 } 1562 1563 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1564 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1565 updateExternalMediaStatus(true, false); 1566 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1567 updateExternalMediaStatus(false, false); 1568 } 1569 } 1570 } 1571 1572 @Override 1573 public void onVolumeForgotten(String fsUuid) { 1574 // TODO: remove all packages hosted on this uuid 1575 } 1576 }; 1577 1578 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1579 if (userId >= UserHandle.USER_OWNER) { 1580 grantRequestedRuntimePermissionsForUser(pkg, userId); 1581 } else if (userId == UserHandle.USER_ALL) { 1582 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1583 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1584 } 1585 } 1586 } 1587 1588 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1589 SettingBase sb = (SettingBase) pkg.mExtras; 1590 if (sb == null) { 1591 return; 1592 } 1593 1594 PermissionsState permissionsState = sb.getPermissionsState(); 1595 1596 for (String permission : pkg.requestedPermissions) { 1597 BasePermission bp = mSettings.mPermissions.get(permission); 1598 if (bp != null && bp.isRuntime()) { 1599 permissionsState.grantRuntimePermission(bp, userId); 1600 } 1601 } 1602 } 1603 1604 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1605 Bundle extras = null; 1606 switch (res.returnCode) { 1607 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1608 extras = new Bundle(); 1609 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1610 res.origPermission); 1611 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1612 res.origPackage); 1613 break; 1614 } 1615 case PackageManager.INSTALL_SUCCEEDED: { 1616 extras = new Bundle(); 1617 extras.putBoolean(Intent.EXTRA_REPLACING, 1618 res.removedInfo != null && res.removedInfo.removedPackage != null); 1619 break; 1620 } 1621 } 1622 return extras; 1623 } 1624 1625 void scheduleWriteSettingsLocked() { 1626 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1627 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1628 } 1629 } 1630 1631 void scheduleWritePackageRestrictionsLocked(int userId) { 1632 if (!sUserManager.exists(userId)) return; 1633 mDirtyUsers.add(userId); 1634 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1635 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1636 } 1637 } 1638 1639 public static PackageManagerService main(Context context, Installer installer, 1640 boolean factoryTest, boolean onlyCore) { 1641 PackageManagerService m = new PackageManagerService(context, installer, 1642 factoryTest, onlyCore); 1643 ServiceManager.addService("package", m); 1644 return m; 1645 } 1646 1647 static String[] splitString(String str, char sep) { 1648 int count = 1; 1649 int i = 0; 1650 while ((i=str.indexOf(sep, i)) >= 0) { 1651 count++; 1652 i++; 1653 } 1654 1655 String[] res = new String[count]; 1656 i=0; 1657 count = 0; 1658 int lastI=0; 1659 while ((i=str.indexOf(sep, i)) >= 0) { 1660 res[count] = str.substring(lastI, i); 1661 count++; 1662 i++; 1663 lastI = i; 1664 } 1665 res[count] = str.substring(lastI, str.length()); 1666 return res; 1667 } 1668 1669 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1670 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1671 Context.DISPLAY_SERVICE); 1672 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1673 } 1674 1675 public PackageManagerService(Context context, Installer installer, 1676 boolean factoryTest, boolean onlyCore) { 1677 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1678 SystemClock.uptimeMillis()); 1679 1680 if (mSdkVersion <= 0) { 1681 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1682 } 1683 1684 mContext = context; 1685 mFactoryTest = factoryTest; 1686 mOnlyCore = onlyCore; 1687 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1688 mMetrics = new DisplayMetrics(); 1689 mSettings = new Settings(mPackages); 1690 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1691 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1692 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1693 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1694 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1695 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1696 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1697 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1698 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1699 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1700 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1701 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1702 1703 // TODO: add a property to control this? 1704 long dexOptLRUThresholdInMinutes; 1705 if (mLazyDexOpt) { 1706 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1707 } else { 1708 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1709 } 1710 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1711 1712 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1713 if (separateProcesses != null && separateProcesses.length() > 0) { 1714 if ("*".equals(separateProcesses)) { 1715 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1716 mSeparateProcesses = null; 1717 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1718 } else { 1719 mDefParseFlags = 0; 1720 mSeparateProcesses = separateProcesses.split(","); 1721 Slog.w(TAG, "Running with debug.separate_processes: " 1722 + separateProcesses); 1723 } 1724 } else { 1725 mDefParseFlags = 0; 1726 mSeparateProcesses = null; 1727 } 1728 1729 mInstaller = installer; 1730 mPackageDexOptimizer = new PackageDexOptimizer(this); 1731 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1732 1733 getDefaultDisplayMetrics(context, mMetrics); 1734 1735 SystemConfig systemConfig = SystemConfig.getInstance(); 1736 mGlobalGids = systemConfig.getGlobalGids(); 1737 mSystemPermissions = systemConfig.getSystemPermissions(); 1738 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1739 1740 synchronized (mInstallLock) { 1741 // writer 1742 synchronized (mPackages) { 1743 mHandlerThread = new ServiceThread(TAG, 1744 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1745 mHandlerThread.start(); 1746 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1747 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1748 1749 File dataDir = Environment.getDataDirectory(); 1750 mAppDataDir = new File(dataDir, "data"); 1751 mAppInstallDir = new File(dataDir, "app"); 1752 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1753 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1754 mUserAppDataDir = new File(dataDir, "user"); 1755 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1756 1757 sUserManager = new UserManagerService(context, this, 1758 mInstallLock, mPackages); 1759 1760 // Propagate permission configuration in to package manager. 1761 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1762 = systemConfig.getPermissions(); 1763 for (int i=0; i<permConfig.size(); i++) { 1764 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1765 BasePermission bp = mSettings.mPermissions.get(perm.name); 1766 if (bp == null) { 1767 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1768 mSettings.mPermissions.put(perm.name, bp); 1769 } 1770 if (perm.gids != null) { 1771 bp.setGids(perm.gids, perm.perUser); 1772 } 1773 } 1774 1775 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1776 for (int i=0; i<libConfig.size(); i++) { 1777 mSharedLibraries.put(libConfig.keyAt(i), 1778 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1779 } 1780 1781 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1782 1783 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1784 mSdkVersion, mOnlyCore); 1785 1786 String customResolverActivity = Resources.getSystem().getString( 1787 R.string.config_customResolverActivity); 1788 if (TextUtils.isEmpty(customResolverActivity)) { 1789 customResolverActivity = null; 1790 } else { 1791 mCustomResolverComponentName = ComponentName.unflattenFromString( 1792 customResolverActivity); 1793 } 1794 1795 long startTime = SystemClock.uptimeMillis(); 1796 1797 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1798 startTime); 1799 1800 // Set flag to monitor and not change apk file paths when 1801 // scanning install directories. 1802 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1803 1804 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1805 1806 /** 1807 * Add everything in the in the boot class path to the 1808 * list of process files because dexopt will have been run 1809 * if necessary during zygote startup. 1810 */ 1811 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1812 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1813 1814 if (bootClassPath != null) { 1815 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1816 for (String element : bootClassPathElements) { 1817 alreadyDexOpted.add(element); 1818 } 1819 } else { 1820 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1821 } 1822 1823 if (systemServerClassPath != null) { 1824 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1825 for (String element : systemServerClassPathElements) { 1826 alreadyDexOpted.add(element); 1827 } 1828 } else { 1829 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1830 } 1831 1832 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1833 final String[] dexCodeInstructionSets = 1834 getDexCodeInstructionSets( 1835 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1836 1837 /** 1838 * Ensure all external libraries have had dexopt run on them. 1839 */ 1840 if (mSharedLibraries.size() > 0) { 1841 // NOTE: For now, we're compiling these system "shared libraries" 1842 // (and framework jars) into all available architectures. It's possible 1843 // to compile them only when we come across an app that uses them (there's 1844 // already logic for that in scanPackageLI) but that adds some complexity. 1845 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1846 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1847 final String lib = libEntry.path; 1848 if (lib == null) { 1849 continue; 1850 } 1851 1852 try { 1853 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1854 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1855 alreadyDexOpted.add(lib); 1856 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1857 } 1858 } catch (FileNotFoundException e) { 1859 Slog.w(TAG, "Library not found: " + lib); 1860 } catch (IOException e) { 1861 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1862 + e.getMessage()); 1863 } 1864 } 1865 } 1866 } 1867 1868 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1869 1870 // Gross hack for now: we know this file doesn't contain any 1871 // code, so don't dexopt it to avoid the resulting log spew. 1872 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1873 1874 // Gross hack for now: we know this file is only part of 1875 // the boot class path for art, so don't dexopt it to 1876 // avoid the resulting log spew. 1877 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1878 1879 /** 1880 * There are a number of commands implemented in Java, which 1881 * we currently need to do the dexopt on so that they can be 1882 * run from a non-root shell. 1883 */ 1884 String[] frameworkFiles = frameworkDir.list(); 1885 if (frameworkFiles != null) { 1886 // TODO: We could compile these only for the most preferred ABI. We should 1887 // first double check that the dex files for these commands are not referenced 1888 // by other system apps. 1889 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1890 for (int i=0; i<frameworkFiles.length; i++) { 1891 File libPath = new File(frameworkDir, frameworkFiles[i]); 1892 String path = libPath.getPath(); 1893 // Skip the file if we already did it. 1894 if (alreadyDexOpted.contains(path)) { 1895 continue; 1896 } 1897 // Skip the file if it is not a type we want to dexopt. 1898 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1899 continue; 1900 } 1901 try { 1902 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1903 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1904 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1905 } 1906 } catch (FileNotFoundException e) { 1907 Slog.w(TAG, "Jar not found: " + path); 1908 } catch (IOException e) { 1909 Slog.w(TAG, "Exception reading jar: " + path, e); 1910 } 1911 } 1912 } 1913 } 1914 1915 // Collect vendor overlay packages. 1916 // (Do this before scanning any apps.) 1917 // For security and version matching reason, only consider 1918 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1919 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1920 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1921 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1922 1923 // Find base frameworks (resource packages without code). 1924 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1925 | PackageParser.PARSE_IS_SYSTEM_DIR 1926 | PackageParser.PARSE_IS_PRIVILEGED, 1927 scanFlags | SCAN_NO_DEX, 0); 1928 1929 // Collected privileged system packages. 1930 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1931 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR 1933 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1934 1935 // Collect ordinary system packages. 1936 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1937 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1938 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1939 1940 // Collect all vendor packages. 1941 File vendorAppDir = new File("/vendor/app"); 1942 try { 1943 vendorAppDir = vendorAppDir.getCanonicalFile(); 1944 } catch (IOException e) { 1945 // failed to look up canonical path, continue with original one 1946 } 1947 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1948 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1949 1950 // Collect all OEM packages. 1951 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1952 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1953 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1954 1955 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1956 mInstaller.moveFiles(); 1957 1958 // Prune any system packages that no longer exist. 1959 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1960 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1961 if (!mOnlyCore) { 1962 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1963 while (psit.hasNext()) { 1964 PackageSetting ps = psit.next(); 1965 1966 /* 1967 * If this is not a system app, it can't be a 1968 * disable system app. 1969 */ 1970 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1971 continue; 1972 } 1973 1974 /* 1975 * If the package is scanned, it's not erased. 1976 */ 1977 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1978 if (scannedPkg != null) { 1979 /* 1980 * If the system app is both scanned and in the 1981 * disabled packages list, then it must have been 1982 * added via OTA. Remove it from the currently 1983 * scanned package so the previously user-installed 1984 * application can be scanned. 1985 */ 1986 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1987 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1988 + ps.name + "; removing system app. Last known codePath=" 1989 + ps.codePathString + ", installStatus=" + ps.installStatus 1990 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1991 + scannedPkg.mVersionCode); 1992 removePackageLI(ps, true); 1993 expectingBetter.put(ps.name, ps.codePath); 1994 } 1995 1996 continue; 1997 } 1998 1999 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2000 psit.remove(); 2001 logCriticalInfo(Log.WARN, "System package " + ps.name 2002 + " no longer exists; wiping its data"); 2003 removeDataDirsLI(null, ps.name); 2004 } else { 2005 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2006 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2007 possiblyDeletedUpdatedSystemApps.add(ps.name); 2008 } 2009 } 2010 } 2011 } 2012 2013 //look for any incomplete package installations 2014 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2015 //clean up list 2016 for(int i = 0; i < deletePkgsList.size(); i++) { 2017 //clean up here 2018 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2019 } 2020 //delete tmp files 2021 deleteTempPackageFiles(); 2022 2023 // Remove any shared userIDs that have no associated packages 2024 mSettings.pruneSharedUsersLPw(); 2025 2026 if (!mOnlyCore) { 2027 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2028 SystemClock.uptimeMillis()); 2029 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2030 2031 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2032 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2033 2034 /** 2035 * Remove disable package settings for any updated system 2036 * apps that were removed via an OTA. If they're not a 2037 * previously-updated app, remove them completely. 2038 * Otherwise, just revoke their system-level permissions. 2039 */ 2040 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2041 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2042 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2043 2044 String msg; 2045 if (deletedPkg == null) { 2046 msg = "Updated system package " + deletedAppName 2047 + " no longer exists; wiping its data"; 2048 removeDataDirsLI(null, deletedAppName); 2049 } else { 2050 msg = "Updated system app + " + deletedAppName 2051 + " no longer present; removing system privileges for " 2052 + deletedAppName; 2053 2054 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2055 2056 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2057 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2058 } 2059 logCriticalInfo(Log.WARN, msg); 2060 } 2061 2062 /** 2063 * Make sure all system apps that we expected to appear on 2064 * the userdata partition actually showed up. If they never 2065 * appeared, crawl back and revive the system version. 2066 */ 2067 for (int i = 0; i < expectingBetter.size(); i++) { 2068 final String packageName = expectingBetter.keyAt(i); 2069 if (!mPackages.containsKey(packageName)) { 2070 final File scanFile = expectingBetter.valueAt(i); 2071 2072 logCriticalInfo(Log.WARN, "Expected better " + packageName 2073 + " but never showed up; reverting to system"); 2074 2075 final int reparseFlags; 2076 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2077 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2078 | PackageParser.PARSE_IS_SYSTEM_DIR 2079 | PackageParser.PARSE_IS_PRIVILEGED; 2080 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2081 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR; 2083 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2084 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2085 | PackageParser.PARSE_IS_SYSTEM_DIR; 2086 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2087 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2088 | PackageParser.PARSE_IS_SYSTEM_DIR; 2089 } else { 2090 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2091 continue; 2092 } 2093 2094 mSettings.enableSystemPackageLPw(packageName); 2095 2096 try { 2097 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2098 } catch (PackageManagerException e) { 2099 Slog.e(TAG, "Failed to parse original system package: " 2100 + e.getMessage()); 2101 } 2102 } 2103 } 2104 } 2105 2106 // Now that we know all of the shared libraries, update all clients to have 2107 // the correct library paths. 2108 updateAllSharedLibrariesLPw(); 2109 2110 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2111 // NOTE: We ignore potential failures here during a system scan (like 2112 // the rest of the commands above) because there's precious little we 2113 // can do about it. A settings error is reported, though. 2114 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2115 false /* force dexopt */, false /* defer dexopt */); 2116 } 2117 2118 // Now that we know all the packages we are keeping, 2119 // read and update their last usage times. 2120 mPackageUsage.readLP(); 2121 2122 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2123 SystemClock.uptimeMillis()); 2124 Slog.i(TAG, "Time to scan packages: " 2125 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2126 + " seconds"); 2127 2128 // If the platform SDK has changed since the last time we booted, 2129 // we need to re-grant app permission to catch any new ones that 2130 // appear. This is really a hack, and means that apps can in some 2131 // cases get permissions that the user didn't initially explicitly 2132 // allow... it would be nice to have some better way to handle 2133 // this situation. 2134 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2135 != mSdkVersion; 2136 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2137 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2138 + "; regranting permissions for internal storage"); 2139 mSettings.mInternalSdkPlatform = mSdkVersion; 2140 2141 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2142 | (regrantPermissions 2143 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2144 : 0)); 2145 2146 // If this is the first boot, and it is a normal boot, then 2147 // we need to initialize the default preferred apps. 2148 if (!mRestoredSettings && !onlyCore) { 2149 mSettings.readDefaultPreferredAppsLPw(this, 0); 2150 } 2151 2152 // If this is first boot after an OTA, and a normal boot, then 2153 // we need to clear code cache directories. 2154 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2155 if (mIsUpgrade && !onlyCore) { 2156 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2157 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2158 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2159 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2160 } 2161 mSettings.mFingerprint = Build.FINGERPRINT; 2162 } 2163 2164 primeDomainVerificationsLPw(); 2165 checkDefaultBrowser(); 2166 2167 // All the changes are done during package scanning. 2168 mSettings.updateInternalDatabaseVersion(); 2169 2170 // can downgrade to reader 2171 mSettings.writeLPr(); 2172 2173 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2174 SystemClock.uptimeMillis()); 2175 2176 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2177 2178 mInstallerService = new PackageInstallerService(context, this); 2179 2180 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2181 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2182 mIntentFilterVerifierComponent); 2183 2184 } // synchronized (mPackages) 2185 } // synchronized (mInstallLock) 2186 2187 // Now after opening every single application zip, make sure they 2188 // are all flushed. Not really needed, but keeps things nice and 2189 // tidy. 2190 Runtime.getRuntime().gc(); 2191 } 2192 2193 @Override 2194 public boolean isFirstBoot() { 2195 return !mRestoredSettings; 2196 } 2197 2198 @Override 2199 public boolean isOnlyCoreApps() { 2200 return mOnlyCore; 2201 } 2202 2203 @Override 2204 public boolean isUpgrade() { 2205 return mIsUpgrade; 2206 } 2207 2208 private String getRequiredVerifierLPr() { 2209 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2210 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2211 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2212 2213 String requiredVerifier = null; 2214 2215 final int N = receivers.size(); 2216 for (int i = 0; i < N; i++) { 2217 final ResolveInfo info = receivers.get(i); 2218 2219 if (info.activityInfo == null) { 2220 continue; 2221 } 2222 2223 final String packageName = info.activityInfo.packageName; 2224 2225 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2226 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2227 continue; 2228 } 2229 2230 if (requiredVerifier != null) { 2231 throw new RuntimeException("There can be only one required verifier"); 2232 } 2233 2234 requiredVerifier = packageName; 2235 } 2236 2237 return requiredVerifier; 2238 } 2239 2240 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2241 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2242 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2243 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2244 2245 ComponentName verifierComponentName = null; 2246 2247 int priority = -1000; 2248 final int N = receivers.size(); 2249 for (int i = 0; i < N; i++) { 2250 final ResolveInfo info = receivers.get(i); 2251 2252 if (info.activityInfo == null) { 2253 continue; 2254 } 2255 2256 final String packageName = info.activityInfo.packageName; 2257 2258 final PackageSetting ps = mSettings.mPackages.get(packageName); 2259 if (ps == null) { 2260 continue; 2261 } 2262 2263 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2264 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2265 continue; 2266 } 2267 2268 // Select the IntentFilterVerifier with the highest priority 2269 if (priority < info.priority) { 2270 priority = info.priority; 2271 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2272 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2273 + verifierComponentName + " with priority: " + info.priority); 2274 } 2275 } 2276 2277 return verifierComponentName; 2278 } 2279 2280 private void primeDomainVerificationsLPw() { 2281 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2282 boolean updated = false; 2283 ArraySet<String> allHostsSet = new ArraySet<>(); 2284 for (PackageParser.Package pkg : mPackages.values()) { 2285 final String packageName = pkg.packageName; 2286 if (!hasDomainURLs(pkg)) { 2287 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2288 "package with no domain URLs: " + packageName); 2289 continue; 2290 } 2291 if (!pkg.isSystemApp()) { 2292 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2293 "No priming domain verifications for a non system package : " + 2294 packageName); 2295 continue; 2296 } 2297 for (PackageParser.Activity a : pkg.activities) { 2298 for (ActivityIntentInfo filter : a.intents) { 2299 if (hasValidDomains(filter)) { 2300 allHostsSet.addAll(filter.getHostsList()); 2301 } 2302 } 2303 } 2304 if (allHostsSet.size() == 0) { 2305 allHostsSet.add("*"); 2306 } 2307 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2308 IntentFilterVerificationInfo ivi = 2309 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2310 if (ivi != null) { 2311 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2312 "Priming domain verifications for package: " + packageName + 2313 " with hosts:" + ivi.getDomainsString()); 2314 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2315 updated = true; 2316 } 2317 else { 2318 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2319 "No priming domain verifications for package: " + packageName); 2320 } 2321 allHostsSet.clear(); 2322 } 2323 if (updated) { 2324 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2325 "Will need to write primed domain verifications"); 2326 } 2327 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2328 } 2329 2330 private void checkDefaultBrowser() { 2331 final int myUserId = UserHandle.myUserId(); 2332 final String packageName = getDefaultBrowserPackageName(myUserId); 2333 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2334 if (info == null) { 2335 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2336 packageName); 2337 setDefaultBrowserPackageName(null, myUserId); 2338 } 2339 } 2340 2341 @Override 2342 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2343 throws RemoteException { 2344 try { 2345 return super.onTransact(code, data, reply, flags); 2346 } catch (RuntimeException e) { 2347 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2348 Slog.wtf(TAG, "Package Manager Crash", e); 2349 } 2350 throw e; 2351 } 2352 } 2353 2354 void cleanupInstallFailedPackage(PackageSetting ps) { 2355 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2356 2357 removeDataDirsLI(ps.volumeUuid, ps.name); 2358 if (ps.codePath != null) { 2359 if (ps.codePath.isDirectory()) { 2360 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2361 } else { 2362 ps.codePath.delete(); 2363 } 2364 } 2365 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2366 if (ps.resourcePath.isDirectory()) { 2367 FileUtils.deleteContents(ps.resourcePath); 2368 } 2369 ps.resourcePath.delete(); 2370 } 2371 mSettings.removePackageLPw(ps.name); 2372 } 2373 2374 static int[] appendInts(int[] cur, int[] add) { 2375 if (add == null) return cur; 2376 if (cur == null) return add; 2377 final int N = add.length; 2378 for (int i=0; i<N; i++) { 2379 cur = appendInt(cur, add[i]); 2380 } 2381 return cur; 2382 } 2383 2384 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2385 if (!sUserManager.exists(userId)) return null; 2386 final PackageSetting ps = (PackageSetting) p.mExtras; 2387 if (ps == null) { 2388 return null; 2389 } 2390 2391 final PermissionsState permissionsState = ps.getPermissionsState(); 2392 2393 final int[] gids = permissionsState.computeGids(userId); 2394 final Set<String> permissions = permissionsState.getPermissions(userId); 2395 final PackageUserState state = ps.readUserState(userId); 2396 2397 return PackageParser.generatePackageInfo(p, gids, flags, 2398 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2399 } 2400 2401 @Override 2402 public boolean isPackageFrozen(String packageName) { 2403 synchronized (mPackages) { 2404 final PackageSetting ps = mSettings.mPackages.get(packageName); 2405 if (ps != null) { 2406 return ps.frozen; 2407 } 2408 } 2409 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2410 return true; 2411 } 2412 2413 @Override 2414 public boolean isPackageAvailable(String packageName, int userId) { 2415 if (!sUserManager.exists(userId)) return false; 2416 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2417 synchronized (mPackages) { 2418 PackageParser.Package p = mPackages.get(packageName); 2419 if (p != null) { 2420 final PackageSetting ps = (PackageSetting) p.mExtras; 2421 if (ps != null) { 2422 final PackageUserState state = ps.readUserState(userId); 2423 if (state != null) { 2424 return PackageParser.isAvailable(state); 2425 } 2426 } 2427 } 2428 } 2429 return false; 2430 } 2431 2432 @Override 2433 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2434 if (!sUserManager.exists(userId)) return null; 2435 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2436 // reader 2437 synchronized (mPackages) { 2438 PackageParser.Package p = mPackages.get(packageName); 2439 if (DEBUG_PACKAGE_INFO) 2440 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2441 if (p != null) { 2442 return generatePackageInfo(p, flags, userId); 2443 } 2444 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2445 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2446 } 2447 } 2448 return null; 2449 } 2450 2451 @Override 2452 public String[] currentToCanonicalPackageNames(String[] names) { 2453 String[] out = new String[names.length]; 2454 // reader 2455 synchronized (mPackages) { 2456 for (int i=names.length-1; i>=0; i--) { 2457 PackageSetting ps = mSettings.mPackages.get(names[i]); 2458 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2459 } 2460 } 2461 return out; 2462 } 2463 2464 @Override 2465 public String[] canonicalToCurrentPackageNames(String[] names) { 2466 String[] out = new String[names.length]; 2467 // reader 2468 synchronized (mPackages) { 2469 for (int i=names.length-1; i>=0; i--) { 2470 String cur = mSettings.mRenamedPackages.get(names[i]); 2471 out[i] = cur != null ? cur : names[i]; 2472 } 2473 } 2474 return out; 2475 } 2476 2477 @Override 2478 public int getPackageUid(String packageName, int userId) { 2479 if (!sUserManager.exists(userId)) return -1; 2480 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2481 2482 // reader 2483 synchronized (mPackages) { 2484 PackageParser.Package p = mPackages.get(packageName); 2485 if(p != null) { 2486 return UserHandle.getUid(userId, p.applicationInfo.uid); 2487 } 2488 PackageSetting ps = mSettings.mPackages.get(packageName); 2489 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2490 return -1; 2491 } 2492 p = ps.pkg; 2493 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2494 } 2495 } 2496 2497 @Override 2498 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2499 if (!sUserManager.exists(userId)) { 2500 return null; 2501 } 2502 2503 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2504 "getPackageGids"); 2505 2506 // reader 2507 synchronized (mPackages) { 2508 PackageParser.Package p = mPackages.get(packageName); 2509 if (DEBUG_PACKAGE_INFO) { 2510 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2511 } 2512 if (p != null) { 2513 PackageSetting ps = (PackageSetting) p.mExtras; 2514 return ps.getPermissionsState().computeGids(userId); 2515 } 2516 } 2517 2518 return null; 2519 } 2520 2521 static PermissionInfo generatePermissionInfo( 2522 BasePermission bp, int flags) { 2523 if (bp.perm != null) { 2524 return PackageParser.generatePermissionInfo(bp.perm, flags); 2525 } 2526 PermissionInfo pi = new PermissionInfo(); 2527 pi.name = bp.name; 2528 pi.packageName = bp.sourcePackage; 2529 pi.nonLocalizedLabel = bp.name; 2530 pi.protectionLevel = bp.protectionLevel; 2531 return pi; 2532 } 2533 2534 @Override 2535 public PermissionInfo getPermissionInfo(String name, int flags) { 2536 // reader 2537 synchronized (mPackages) { 2538 final BasePermission p = mSettings.mPermissions.get(name); 2539 if (p != null) { 2540 return generatePermissionInfo(p, flags); 2541 } 2542 return null; 2543 } 2544 } 2545 2546 @Override 2547 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2548 // reader 2549 synchronized (mPackages) { 2550 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2551 for (BasePermission p : mSettings.mPermissions.values()) { 2552 if (group == null) { 2553 if (p.perm == null || p.perm.info.group == null) { 2554 out.add(generatePermissionInfo(p, flags)); 2555 } 2556 } else { 2557 if (p.perm != null && group.equals(p.perm.info.group)) { 2558 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2559 } 2560 } 2561 } 2562 2563 if (out.size() > 0) { 2564 return out; 2565 } 2566 return mPermissionGroups.containsKey(group) ? out : null; 2567 } 2568 } 2569 2570 @Override 2571 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2572 // reader 2573 synchronized (mPackages) { 2574 return PackageParser.generatePermissionGroupInfo( 2575 mPermissionGroups.get(name), flags); 2576 } 2577 } 2578 2579 @Override 2580 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2581 // reader 2582 synchronized (mPackages) { 2583 final int N = mPermissionGroups.size(); 2584 ArrayList<PermissionGroupInfo> out 2585 = new ArrayList<PermissionGroupInfo>(N); 2586 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2587 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2588 } 2589 return out; 2590 } 2591 } 2592 2593 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2594 int userId) { 2595 if (!sUserManager.exists(userId)) return null; 2596 PackageSetting ps = mSettings.mPackages.get(packageName); 2597 if (ps != null) { 2598 if (ps.pkg == null) { 2599 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2600 flags, userId); 2601 if (pInfo != null) { 2602 return pInfo.applicationInfo; 2603 } 2604 return null; 2605 } 2606 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2607 ps.readUserState(userId), userId); 2608 } 2609 return null; 2610 } 2611 2612 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2613 int userId) { 2614 if (!sUserManager.exists(userId)) return null; 2615 PackageSetting ps = mSettings.mPackages.get(packageName); 2616 if (ps != null) { 2617 PackageParser.Package pkg = ps.pkg; 2618 if (pkg == null) { 2619 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2620 return null; 2621 } 2622 // Only data remains, so we aren't worried about code paths 2623 pkg = new PackageParser.Package(packageName); 2624 pkg.applicationInfo.packageName = packageName; 2625 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2626 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2627 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2628 packageName, userId).getAbsolutePath(); 2629 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2630 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2631 } 2632 return generatePackageInfo(pkg, flags, userId); 2633 } 2634 return null; 2635 } 2636 2637 @Override 2638 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2639 if (!sUserManager.exists(userId)) return null; 2640 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2641 // writer 2642 synchronized (mPackages) { 2643 PackageParser.Package p = mPackages.get(packageName); 2644 if (DEBUG_PACKAGE_INFO) Log.v( 2645 TAG, "getApplicationInfo " + packageName 2646 + ": " + p); 2647 if (p != null) { 2648 PackageSetting ps = mSettings.mPackages.get(packageName); 2649 if (ps == null) return null; 2650 // Note: isEnabledLP() does not apply here - always return info 2651 return PackageParser.generateApplicationInfo( 2652 p, flags, ps.readUserState(userId), userId); 2653 } 2654 if ("android".equals(packageName)||"system".equals(packageName)) { 2655 return mAndroidApplication; 2656 } 2657 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2658 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2659 } 2660 } 2661 return null; 2662 } 2663 2664 @Override 2665 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2666 final IPackageDataObserver observer) { 2667 mContext.enforceCallingOrSelfPermission( 2668 android.Manifest.permission.CLEAR_APP_CACHE, null); 2669 // Queue up an async operation since clearing cache may take a little while. 2670 mHandler.post(new Runnable() { 2671 public void run() { 2672 mHandler.removeCallbacks(this); 2673 int retCode = -1; 2674 synchronized (mInstallLock) { 2675 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2676 if (retCode < 0) { 2677 Slog.w(TAG, "Couldn't clear application caches"); 2678 } 2679 } 2680 if (observer != null) { 2681 try { 2682 observer.onRemoveCompleted(null, (retCode >= 0)); 2683 } catch (RemoteException e) { 2684 Slog.w(TAG, "RemoveException when invoking call back"); 2685 } 2686 } 2687 } 2688 }); 2689 } 2690 2691 @Override 2692 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2693 final IntentSender pi) { 2694 mContext.enforceCallingOrSelfPermission( 2695 android.Manifest.permission.CLEAR_APP_CACHE, null); 2696 // Queue up an async operation since clearing cache may take a little while. 2697 mHandler.post(new Runnable() { 2698 public void run() { 2699 mHandler.removeCallbacks(this); 2700 int retCode = -1; 2701 synchronized (mInstallLock) { 2702 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2703 if (retCode < 0) { 2704 Slog.w(TAG, "Couldn't clear application caches"); 2705 } 2706 } 2707 if(pi != null) { 2708 try { 2709 // Callback via pending intent 2710 int code = (retCode >= 0) ? 1 : 0; 2711 pi.sendIntent(null, code, null, 2712 null, null); 2713 } catch (SendIntentException e1) { 2714 Slog.i(TAG, "Failed to send pending intent"); 2715 } 2716 } 2717 } 2718 }); 2719 } 2720 2721 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2722 synchronized (mInstallLock) { 2723 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2724 throw new IOException("Failed to free enough space"); 2725 } 2726 } 2727 } 2728 2729 @Override 2730 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2731 if (!sUserManager.exists(userId)) return null; 2732 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2733 synchronized (mPackages) { 2734 PackageParser.Activity a = mActivities.mActivities.get(component); 2735 2736 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2737 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2738 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2739 if (ps == null) return null; 2740 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2741 userId); 2742 } 2743 if (mResolveComponentName.equals(component)) { 2744 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2745 new PackageUserState(), userId); 2746 } 2747 } 2748 return null; 2749 } 2750 2751 @Override 2752 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2753 String resolvedType) { 2754 synchronized (mPackages) { 2755 PackageParser.Activity a = mActivities.mActivities.get(component); 2756 if (a == null) { 2757 return false; 2758 } 2759 for (int i=0; i<a.intents.size(); i++) { 2760 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2761 intent.getData(), intent.getCategories(), TAG) >= 0) { 2762 return true; 2763 } 2764 } 2765 return false; 2766 } 2767 } 2768 2769 @Override 2770 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2771 if (!sUserManager.exists(userId)) return null; 2772 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2773 synchronized (mPackages) { 2774 PackageParser.Activity a = mReceivers.mActivities.get(component); 2775 if (DEBUG_PACKAGE_INFO) Log.v( 2776 TAG, "getReceiverInfo " + component + ": " + a); 2777 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2778 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2779 if (ps == null) return null; 2780 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2781 userId); 2782 } 2783 } 2784 return null; 2785 } 2786 2787 @Override 2788 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2789 if (!sUserManager.exists(userId)) return null; 2790 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2791 synchronized (mPackages) { 2792 PackageParser.Service s = mServices.mServices.get(component); 2793 if (DEBUG_PACKAGE_INFO) Log.v( 2794 TAG, "getServiceInfo " + component + ": " + s); 2795 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2796 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2797 if (ps == null) return null; 2798 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2799 userId); 2800 } 2801 } 2802 return null; 2803 } 2804 2805 @Override 2806 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2807 if (!sUserManager.exists(userId)) return null; 2808 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2809 synchronized (mPackages) { 2810 PackageParser.Provider p = mProviders.mProviders.get(component); 2811 if (DEBUG_PACKAGE_INFO) Log.v( 2812 TAG, "getProviderInfo " + component + ": " + p); 2813 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2814 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2815 if (ps == null) return null; 2816 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2817 userId); 2818 } 2819 } 2820 return null; 2821 } 2822 2823 @Override 2824 public String[] getSystemSharedLibraryNames() { 2825 Set<String> libSet; 2826 synchronized (mPackages) { 2827 libSet = mSharedLibraries.keySet(); 2828 int size = libSet.size(); 2829 if (size > 0) { 2830 String[] libs = new String[size]; 2831 libSet.toArray(libs); 2832 return libs; 2833 } 2834 } 2835 return null; 2836 } 2837 2838 /** 2839 * @hide 2840 */ 2841 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2842 synchronized (mPackages) { 2843 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2844 if (lib != null && lib.apk != null) { 2845 return mPackages.get(lib.apk); 2846 } 2847 } 2848 return null; 2849 } 2850 2851 @Override 2852 public FeatureInfo[] getSystemAvailableFeatures() { 2853 Collection<FeatureInfo> featSet; 2854 synchronized (mPackages) { 2855 featSet = mAvailableFeatures.values(); 2856 int size = featSet.size(); 2857 if (size > 0) { 2858 FeatureInfo[] features = new FeatureInfo[size+1]; 2859 featSet.toArray(features); 2860 FeatureInfo fi = new FeatureInfo(); 2861 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2862 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2863 features[size] = fi; 2864 return features; 2865 } 2866 } 2867 return null; 2868 } 2869 2870 @Override 2871 public boolean hasSystemFeature(String name) { 2872 synchronized (mPackages) { 2873 return mAvailableFeatures.containsKey(name); 2874 } 2875 } 2876 2877 private void checkValidCaller(int uid, int userId) { 2878 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2879 return; 2880 2881 throw new SecurityException("Caller uid=" + uid 2882 + " is not privileged to communicate with user=" + userId); 2883 } 2884 2885 @Override 2886 public int checkPermission(String permName, String pkgName, int userId) { 2887 if (!sUserManager.exists(userId)) { 2888 return PackageManager.PERMISSION_DENIED; 2889 } 2890 2891 synchronized (mPackages) { 2892 final PackageParser.Package p = mPackages.get(pkgName); 2893 if (p != null && p.mExtras != null) { 2894 final PackageSetting ps = (PackageSetting) p.mExtras; 2895 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2896 return PackageManager.PERMISSION_GRANTED; 2897 } 2898 } 2899 } 2900 2901 return PackageManager.PERMISSION_DENIED; 2902 } 2903 2904 @Override 2905 public int checkUidPermission(String permName, int uid) { 2906 final int userId = UserHandle.getUserId(uid); 2907 2908 if (!sUserManager.exists(userId)) { 2909 return PackageManager.PERMISSION_DENIED; 2910 } 2911 2912 synchronized (mPackages) { 2913 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2914 if (obj != null) { 2915 final SettingBase ps = (SettingBase) obj; 2916 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2917 return PackageManager.PERMISSION_GRANTED; 2918 } 2919 } else { 2920 ArraySet<String> perms = mSystemPermissions.get(uid); 2921 if (perms != null && perms.contains(permName)) { 2922 return PackageManager.PERMISSION_GRANTED; 2923 } 2924 } 2925 } 2926 2927 return PackageManager.PERMISSION_DENIED; 2928 } 2929 2930 /** 2931 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2932 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2933 * @param checkShell TODO(yamasani): 2934 * @param message the message to log on security exception 2935 */ 2936 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2937 boolean checkShell, String message) { 2938 if (userId < 0) { 2939 throw new IllegalArgumentException("Invalid userId " + userId); 2940 } 2941 if (checkShell) { 2942 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2943 } 2944 if (userId == UserHandle.getUserId(callingUid)) return; 2945 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2946 if (requireFullPermission) { 2947 mContext.enforceCallingOrSelfPermission( 2948 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2949 } else { 2950 try { 2951 mContext.enforceCallingOrSelfPermission( 2952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2953 } catch (SecurityException se) { 2954 mContext.enforceCallingOrSelfPermission( 2955 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2956 } 2957 } 2958 } 2959 } 2960 2961 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2962 if (callingUid == Process.SHELL_UID) { 2963 if (userHandle >= 0 2964 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2965 throw new SecurityException("Shell does not have permission to access user " 2966 + userHandle); 2967 } else if (userHandle < 0) { 2968 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2969 + Debug.getCallers(3)); 2970 } 2971 } 2972 } 2973 2974 private BasePermission findPermissionTreeLP(String permName) { 2975 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2976 if (permName.startsWith(bp.name) && 2977 permName.length() > bp.name.length() && 2978 permName.charAt(bp.name.length()) == '.') { 2979 return bp; 2980 } 2981 } 2982 return null; 2983 } 2984 2985 private BasePermission checkPermissionTreeLP(String permName) { 2986 if (permName != null) { 2987 BasePermission bp = findPermissionTreeLP(permName); 2988 if (bp != null) { 2989 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2990 return bp; 2991 } 2992 throw new SecurityException("Calling uid " 2993 + Binder.getCallingUid() 2994 + " is not allowed to add to permission tree " 2995 + bp.name + " owned by uid " + bp.uid); 2996 } 2997 } 2998 throw new SecurityException("No permission tree found for " + permName); 2999 } 3000 3001 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3002 if (s1 == null) { 3003 return s2 == null; 3004 } 3005 if (s2 == null) { 3006 return false; 3007 } 3008 if (s1.getClass() != s2.getClass()) { 3009 return false; 3010 } 3011 return s1.equals(s2); 3012 } 3013 3014 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3015 if (pi1.icon != pi2.icon) return false; 3016 if (pi1.logo != pi2.logo) return false; 3017 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3018 if (!compareStrings(pi1.name, pi2.name)) return false; 3019 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3020 // We'll take care of setting this one. 3021 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3022 // These are not currently stored in settings. 3023 //if (!compareStrings(pi1.group, pi2.group)) return false; 3024 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3025 //if (pi1.labelRes != pi2.labelRes) return false; 3026 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3027 return true; 3028 } 3029 3030 int permissionInfoFootprint(PermissionInfo info) { 3031 int size = info.name.length(); 3032 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3033 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3034 return size; 3035 } 3036 3037 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3038 int size = 0; 3039 for (BasePermission perm : mSettings.mPermissions.values()) { 3040 if (perm.uid == tree.uid) { 3041 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3042 } 3043 } 3044 return size; 3045 } 3046 3047 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3048 // We calculate the max size of permissions defined by this uid and throw 3049 // if that plus the size of 'info' would exceed our stated maximum. 3050 if (tree.uid != Process.SYSTEM_UID) { 3051 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3052 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3053 throw new SecurityException("Permission tree size cap exceeded"); 3054 } 3055 } 3056 } 3057 3058 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3059 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3060 throw new SecurityException("Label must be specified in permission"); 3061 } 3062 BasePermission tree = checkPermissionTreeLP(info.name); 3063 BasePermission bp = mSettings.mPermissions.get(info.name); 3064 boolean added = bp == null; 3065 boolean changed = true; 3066 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3067 if (added) { 3068 enforcePermissionCapLocked(info, tree); 3069 bp = new BasePermission(info.name, tree.sourcePackage, 3070 BasePermission.TYPE_DYNAMIC); 3071 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3072 throw new SecurityException( 3073 "Not allowed to modify non-dynamic permission " 3074 + info.name); 3075 } else { 3076 if (bp.protectionLevel == fixedLevel 3077 && bp.perm.owner.equals(tree.perm.owner) 3078 && bp.uid == tree.uid 3079 && comparePermissionInfos(bp.perm.info, info)) { 3080 changed = false; 3081 } 3082 } 3083 bp.protectionLevel = fixedLevel; 3084 info = new PermissionInfo(info); 3085 info.protectionLevel = fixedLevel; 3086 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3087 bp.perm.info.packageName = tree.perm.info.packageName; 3088 bp.uid = tree.uid; 3089 if (added) { 3090 mSettings.mPermissions.put(info.name, bp); 3091 } 3092 if (changed) { 3093 if (!async) { 3094 mSettings.writeLPr(); 3095 } else { 3096 scheduleWriteSettingsLocked(); 3097 } 3098 } 3099 return added; 3100 } 3101 3102 @Override 3103 public boolean addPermission(PermissionInfo info) { 3104 synchronized (mPackages) { 3105 return addPermissionLocked(info, false); 3106 } 3107 } 3108 3109 @Override 3110 public boolean addPermissionAsync(PermissionInfo info) { 3111 synchronized (mPackages) { 3112 return addPermissionLocked(info, true); 3113 } 3114 } 3115 3116 @Override 3117 public void removePermission(String name) { 3118 synchronized (mPackages) { 3119 checkPermissionTreeLP(name); 3120 BasePermission bp = mSettings.mPermissions.get(name); 3121 if (bp != null) { 3122 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3123 throw new SecurityException( 3124 "Not allowed to modify non-dynamic permission " 3125 + name); 3126 } 3127 mSettings.mPermissions.remove(name); 3128 mSettings.writeLPr(); 3129 } 3130 } 3131 } 3132 3133 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3134 BasePermission bp) { 3135 int index = pkg.requestedPermissions.indexOf(bp.name); 3136 if (index == -1) { 3137 throw new SecurityException("Package " + pkg.packageName 3138 + " has not requested permission " + bp.name); 3139 } 3140 if (!bp.isRuntime()) { 3141 throw new SecurityException("Permission " + bp.name 3142 + " is not a changeable permission type"); 3143 } 3144 } 3145 3146 @Override 3147 public void grantRuntimePermission(String packageName, String name, int userId) { 3148 if (!sUserManager.exists(userId)) { 3149 Log.e(TAG, "No such user:" + userId); 3150 return; 3151 } 3152 3153 mContext.enforceCallingOrSelfPermission( 3154 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3155 "grantRuntimePermission"); 3156 3157 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3158 "grantRuntimePermission"); 3159 3160 boolean gidsChanged = false; 3161 final SettingBase sb; 3162 3163 synchronized (mPackages) { 3164 final PackageParser.Package pkg = mPackages.get(packageName); 3165 if (pkg == null) { 3166 throw new IllegalArgumentException("Unknown package: " + packageName); 3167 } 3168 3169 final BasePermission bp = mSettings.mPermissions.get(name); 3170 if (bp == null) { 3171 throw new IllegalArgumentException("Unknown permission: " + name); 3172 } 3173 3174 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3175 3176 sb = (SettingBase) pkg.mExtras; 3177 if (sb == null) { 3178 throw new IllegalArgumentException("Unknown package: " + packageName); 3179 } 3180 3181 final PermissionsState permissionsState = sb.getPermissionsState(); 3182 3183 final int flags = permissionsState.getPermissionFlags(name, userId); 3184 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3185 throw new SecurityException("Cannot grant system fixed permission: " 3186 + name + " for package: " + packageName); 3187 } 3188 3189 final int result = permissionsState.grantRuntimePermission(bp, userId); 3190 switch (result) { 3191 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3192 return; 3193 } 3194 3195 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3196 gidsChanged = true; 3197 } 3198 break; 3199 } 3200 3201 // Not critical if that is lost - app has to request again. 3202 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3203 } 3204 3205 if (gidsChanged) { 3206 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3207 } 3208 } 3209 3210 @Override 3211 public void revokeRuntimePermission(String packageName, String name, int userId) { 3212 if (!sUserManager.exists(userId)) { 3213 Log.e(TAG, "No such user:" + userId); 3214 return; 3215 } 3216 3217 mContext.enforceCallingOrSelfPermission( 3218 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3219 "revokeRuntimePermission"); 3220 3221 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3222 "revokeRuntimePermission"); 3223 3224 final SettingBase sb; 3225 3226 synchronized (mPackages) { 3227 final PackageParser.Package pkg = mPackages.get(packageName); 3228 if (pkg == null) { 3229 throw new IllegalArgumentException("Unknown package: " + packageName); 3230 } 3231 3232 final BasePermission bp = mSettings.mPermissions.get(name); 3233 if (bp == null) { 3234 throw new IllegalArgumentException("Unknown permission: " + name); 3235 } 3236 3237 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3238 3239 sb = (SettingBase) pkg.mExtras; 3240 if (sb == null) { 3241 throw new IllegalArgumentException("Unknown package: " + packageName); 3242 } 3243 3244 final PermissionsState permissionsState = sb.getPermissionsState(); 3245 3246 final int flags = permissionsState.getPermissionFlags(name, userId); 3247 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3248 throw new SecurityException("Cannot revoke system fixed permission: " 3249 + name + " for package: " + packageName); 3250 } 3251 3252 if (permissionsState.revokeRuntimePermission(bp, userId) == 3253 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3254 return; 3255 } 3256 3257 // Critical, after this call app should never have the permission. 3258 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3259 } 3260 3261 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3262 } 3263 3264 @Override 3265 public int getPermissionFlags(String name, String packageName, int userId) { 3266 if (!sUserManager.exists(userId)) { 3267 return 0; 3268 } 3269 3270 mContext.enforceCallingOrSelfPermission( 3271 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3272 "getPermissionFlags"); 3273 3274 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3275 "getPermissionFlags"); 3276 3277 synchronized (mPackages) { 3278 final PackageParser.Package pkg = mPackages.get(packageName); 3279 if (pkg == null) { 3280 throw new IllegalArgumentException("Unknown package: " + packageName); 3281 } 3282 3283 final BasePermission bp = mSettings.mPermissions.get(name); 3284 if (bp == null) { 3285 throw new IllegalArgumentException("Unknown permission: " + name); 3286 } 3287 3288 SettingBase sb = (SettingBase) pkg.mExtras; 3289 if (sb == null) { 3290 throw new IllegalArgumentException("Unknown package: " + packageName); 3291 } 3292 3293 PermissionsState permissionsState = sb.getPermissionsState(); 3294 return permissionsState.getPermissionFlags(name, userId); 3295 } 3296 } 3297 3298 @Override 3299 public void updatePermissionFlags(String name, String packageName, int flagMask, 3300 int flagValues, int userId) { 3301 if (!sUserManager.exists(userId)) { 3302 return; 3303 } 3304 3305 mContext.enforceCallingOrSelfPermission( 3306 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3307 "updatePermissionFlags"); 3308 3309 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3310 "updatePermissionFlags"); 3311 3312 // Only the system can change policy flags. 3313 if (getCallingUid() != Process.SYSTEM_UID) { 3314 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3315 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3316 } 3317 3318 // Only the package manager can change system flags. 3319 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3320 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3321 3322 synchronized (mPackages) { 3323 final PackageParser.Package pkg = mPackages.get(packageName); 3324 if (pkg == null) { 3325 throw new IllegalArgumentException("Unknown package: " + packageName); 3326 } 3327 3328 final BasePermission bp = mSettings.mPermissions.get(name); 3329 if (bp == null) { 3330 throw new IllegalArgumentException("Unknown permission: " + name); 3331 } 3332 3333 SettingBase sb = (SettingBase) pkg.mExtras; 3334 if (sb == null) { 3335 throw new IllegalArgumentException("Unknown package: " + packageName); 3336 } 3337 3338 PermissionsState permissionsState = sb.getPermissionsState(); 3339 3340 // Only the package manager can change flags for system component permissions. 3341 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3342 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3343 return; 3344 } 3345 3346 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3347 // Install and runtime permissions are stored in different places, 3348 // so figure out what permission changed and persist the change. 3349 if (permissionsState.getInstallPermissionState(name) != null) { 3350 scheduleWriteSettingsLocked(); 3351 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3352 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3353 } 3354 } 3355 } 3356 } 3357 3358 @Override 3359 public boolean shouldShowRequestPermissionRationale(String permissionName, 3360 String packageName, int userId) { 3361 if (UserHandle.getCallingUserId() != userId) { 3362 mContext.enforceCallingPermission( 3363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3364 "canShowRequestPermissionRationale for user " + userId); 3365 } 3366 3367 final int uid = getPackageUid(packageName, userId); 3368 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3369 return false; 3370 } 3371 3372 if (checkPermission(permissionName, packageName, userId) 3373 == PackageManager.PERMISSION_GRANTED) { 3374 return false; 3375 } 3376 3377 final int flags; 3378 3379 final long identity = Binder.clearCallingIdentity(); 3380 try { 3381 flags = getPermissionFlags(permissionName, 3382 packageName, userId); 3383 } finally { 3384 Binder.restoreCallingIdentity(identity); 3385 } 3386 3387 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3388 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3389 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3390 3391 if ((flags & fixedFlags) != 0) { 3392 return false; 3393 } 3394 3395 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3396 } 3397 3398 @Override 3399 public boolean isProtectedBroadcast(String actionName) { 3400 synchronized (mPackages) { 3401 return mProtectedBroadcasts.contains(actionName); 3402 } 3403 } 3404 3405 @Override 3406 public int checkSignatures(String pkg1, String pkg2) { 3407 synchronized (mPackages) { 3408 final PackageParser.Package p1 = mPackages.get(pkg1); 3409 final PackageParser.Package p2 = mPackages.get(pkg2); 3410 if (p1 == null || p1.mExtras == null 3411 || p2 == null || p2.mExtras == null) { 3412 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3413 } 3414 return compareSignatures(p1.mSignatures, p2.mSignatures); 3415 } 3416 } 3417 3418 @Override 3419 public int checkUidSignatures(int uid1, int uid2) { 3420 // Map to base uids. 3421 uid1 = UserHandle.getAppId(uid1); 3422 uid2 = UserHandle.getAppId(uid2); 3423 // reader 3424 synchronized (mPackages) { 3425 Signature[] s1; 3426 Signature[] s2; 3427 Object obj = mSettings.getUserIdLPr(uid1); 3428 if (obj != null) { 3429 if (obj instanceof SharedUserSetting) { 3430 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3431 } else if (obj instanceof PackageSetting) { 3432 s1 = ((PackageSetting)obj).signatures.mSignatures; 3433 } else { 3434 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3435 } 3436 } else { 3437 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3438 } 3439 obj = mSettings.getUserIdLPr(uid2); 3440 if (obj != null) { 3441 if (obj instanceof SharedUserSetting) { 3442 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3443 } else if (obj instanceof PackageSetting) { 3444 s2 = ((PackageSetting)obj).signatures.mSignatures; 3445 } else { 3446 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3447 } 3448 } else { 3449 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3450 } 3451 return compareSignatures(s1, s2); 3452 } 3453 } 3454 3455 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3456 final long identity = Binder.clearCallingIdentity(); 3457 try { 3458 if (sb instanceof SharedUserSetting) { 3459 SharedUserSetting sus = (SharedUserSetting) sb; 3460 final int packageCount = sus.packages.size(); 3461 for (int i = 0; i < packageCount; i++) { 3462 PackageSetting susPs = sus.packages.valueAt(i); 3463 if (userId == UserHandle.USER_ALL) { 3464 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3465 } else { 3466 final int uid = UserHandle.getUid(userId, susPs.appId); 3467 killUid(uid, reason); 3468 } 3469 } 3470 } else if (sb instanceof PackageSetting) { 3471 PackageSetting ps = (PackageSetting) sb; 3472 if (userId == UserHandle.USER_ALL) { 3473 killApplication(ps.pkg.packageName, ps.appId, reason); 3474 } else { 3475 final int uid = UserHandle.getUid(userId, ps.appId); 3476 killUid(uid, reason); 3477 } 3478 } 3479 } finally { 3480 Binder.restoreCallingIdentity(identity); 3481 } 3482 } 3483 3484 private static void killUid(int uid, String reason) { 3485 IActivityManager am = ActivityManagerNative.getDefault(); 3486 if (am != null) { 3487 try { 3488 am.killUid(uid, reason); 3489 } catch (RemoteException e) { 3490 /* ignore - same process */ 3491 } 3492 } 3493 } 3494 3495 /** 3496 * Compares two sets of signatures. Returns: 3497 * <br /> 3498 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3499 * <br /> 3500 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3501 * <br /> 3502 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3503 * <br /> 3504 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3505 * <br /> 3506 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3507 */ 3508 static int compareSignatures(Signature[] s1, Signature[] s2) { 3509 if (s1 == null) { 3510 return s2 == null 3511 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3512 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3513 } 3514 3515 if (s2 == null) { 3516 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3517 } 3518 3519 if (s1.length != s2.length) { 3520 return PackageManager.SIGNATURE_NO_MATCH; 3521 } 3522 3523 // Since both signature sets are of size 1, we can compare without HashSets. 3524 if (s1.length == 1) { 3525 return s1[0].equals(s2[0]) ? 3526 PackageManager.SIGNATURE_MATCH : 3527 PackageManager.SIGNATURE_NO_MATCH; 3528 } 3529 3530 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3531 for (Signature sig : s1) { 3532 set1.add(sig); 3533 } 3534 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3535 for (Signature sig : s2) { 3536 set2.add(sig); 3537 } 3538 // Make sure s2 contains all signatures in s1. 3539 if (set1.equals(set2)) { 3540 return PackageManager.SIGNATURE_MATCH; 3541 } 3542 return PackageManager.SIGNATURE_NO_MATCH; 3543 } 3544 3545 /** 3546 * If the database version for this type of package (internal storage or 3547 * external storage) is less than the version where package signatures 3548 * were updated, return true. 3549 */ 3550 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3551 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3552 DatabaseVersion.SIGNATURE_END_ENTITY)) 3553 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3554 DatabaseVersion.SIGNATURE_END_ENTITY)); 3555 } 3556 3557 /** 3558 * Used for backward compatibility to make sure any packages with 3559 * certificate chains get upgraded to the new style. {@code existingSigs} 3560 * will be in the old format (since they were stored on disk from before the 3561 * system upgrade) and {@code scannedSigs} will be in the newer format. 3562 */ 3563 private int compareSignaturesCompat(PackageSignatures existingSigs, 3564 PackageParser.Package scannedPkg) { 3565 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3566 return PackageManager.SIGNATURE_NO_MATCH; 3567 } 3568 3569 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3570 for (Signature sig : existingSigs.mSignatures) { 3571 existingSet.add(sig); 3572 } 3573 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3574 for (Signature sig : scannedPkg.mSignatures) { 3575 try { 3576 Signature[] chainSignatures = sig.getChainSignatures(); 3577 for (Signature chainSig : chainSignatures) { 3578 scannedCompatSet.add(chainSig); 3579 } 3580 } catch (CertificateEncodingException e) { 3581 scannedCompatSet.add(sig); 3582 } 3583 } 3584 /* 3585 * Make sure the expanded scanned set contains all signatures in the 3586 * existing one. 3587 */ 3588 if (scannedCompatSet.equals(existingSet)) { 3589 // Migrate the old signatures to the new scheme. 3590 existingSigs.assignSignatures(scannedPkg.mSignatures); 3591 // The new KeySets will be re-added later in the scanning process. 3592 synchronized (mPackages) { 3593 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3594 } 3595 return PackageManager.SIGNATURE_MATCH; 3596 } 3597 return PackageManager.SIGNATURE_NO_MATCH; 3598 } 3599 3600 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3601 if (isExternal(scannedPkg)) { 3602 return mSettings.isExternalDatabaseVersionOlderThan( 3603 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3604 } else { 3605 return mSettings.isInternalDatabaseVersionOlderThan( 3606 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3607 } 3608 } 3609 3610 private int compareSignaturesRecover(PackageSignatures existingSigs, 3611 PackageParser.Package scannedPkg) { 3612 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3613 return PackageManager.SIGNATURE_NO_MATCH; 3614 } 3615 3616 String msg = null; 3617 try { 3618 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3619 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3620 + scannedPkg.packageName); 3621 return PackageManager.SIGNATURE_MATCH; 3622 } 3623 } catch (CertificateException e) { 3624 msg = e.getMessage(); 3625 } 3626 3627 logCriticalInfo(Log.INFO, 3628 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3629 return PackageManager.SIGNATURE_NO_MATCH; 3630 } 3631 3632 @Override 3633 public String[] getPackagesForUid(int uid) { 3634 uid = UserHandle.getAppId(uid); 3635 // reader 3636 synchronized (mPackages) { 3637 Object obj = mSettings.getUserIdLPr(uid); 3638 if (obj instanceof SharedUserSetting) { 3639 final SharedUserSetting sus = (SharedUserSetting) obj; 3640 final int N = sus.packages.size(); 3641 final String[] res = new String[N]; 3642 final Iterator<PackageSetting> it = sus.packages.iterator(); 3643 int i = 0; 3644 while (it.hasNext()) { 3645 res[i++] = it.next().name; 3646 } 3647 return res; 3648 } else if (obj instanceof PackageSetting) { 3649 final PackageSetting ps = (PackageSetting) obj; 3650 return new String[] { ps.name }; 3651 } 3652 } 3653 return null; 3654 } 3655 3656 @Override 3657 public String getNameForUid(int uid) { 3658 // reader 3659 synchronized (mPackages) { 3660 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3661 if (obj instanceof SharedUserSetting) { 3662 final SharedUserSetting sus = (SharedUserSetting) obj; 3663 return sus.name + ":" + sus.userId; 3664 } else if (obj instanceof PackageSetting) { 3665 final PackageSetting ps = (PackageSetting) obj; 3666 return ps.name; 3667 } 3668 } 3669 return null; 3670 } 3671 3672 @Override 3673 public int getUidForSharedUser(String sharedUserName) { 3674 if(sharedUserName == null) { 3675 return -1; 3676 } 3677 // reader 3678 synchronized (mPackages) { 3679 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3680 if (suid == null) { 3681 return -1; 3682 } 3683 return suid.userId; 3684 } 3685 } 3686 3687 @Override 3688 public int getFlagsForUid(int uid) { 3689 synchronized (mPackages) { 3690 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3691 if (obj instanceof SharedUserSetting) { 3692 final SharedUserSetting sus = (SharedUserSetting) obj; 3693 return sus.pkgFlags; 3694 } else if (obj instanceof PackageSetting) { 3695 final PackageSetting ps = (PackageSetting) obj; 3696 return ps.pkgFlags; 3697 } 3698 } 3699 return 0; 3700 } 3701 3702 @Override 3703 public int getPrivateFlagsForUid(int uid) { 3704 synchronized (mPackages) { 3705 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3706 if (obj instanceof SharedUserSetting) { 3707 final SharedUserSetting sus = (SharedUserSetting) obj; 3708 return sus.pkgPrivateFlags; 3709 } else if (obj instanceof PackageSetting) { 3710 final PackageSetting ps = (PackageSetting) obj; 3711 return ps.pkgPrivateFlags; 3712 } 3713 } 3714 return 0; 3715 } 3716 3717 @Override 3718 public boolean isUidPrivileged(int uid) { 3719 uid = UserHandle.getAppId(uid); 3720 // reader 3721 synchronized (mPackages) { 3722 Object obj = mSettings.getUserIdLPr(uid); 3723 if (obj instanceof SharedUserSetting) { 3724 final SharedUserSetting sus = (SharedUserSetting) obj; 3725 final Iterator<PackageSetting> it = sus.packages.iterator(); 3726 while (it.hasNext()) { 3727 if (it.next().isPrivileged()) { 3728 return true; 3729 } 3730 } 3731 } else if (obj instanceof PackageSetting) { 3732 final PackageSetting ps = (PackageSetting) obj; 3733 return ps.isPrivileged(); 3734 } 3735 } 3736 return false; 3737 } 3738 3739 @Override 3740 public String[] getAppOpPermissionPackages(String permissionName) { 3741 synchronized (mPackages) { 3742 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3743 if (pkgs == null) { 3744 return null; 3745 } 3746 return pkgs.toArray(new String[pkgs.size()]); 3747 } 3748 } 3749 3750 @Override 3751 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3752 int flags, int userId) { 3753 if (!sUserManager.exists(userId)) return null; 3754 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3755 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3756 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3757 } 3758 3759 @Override 3760 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3761 IntentFilter filter, int match, ComponentName activity) { 3762 final int userId = UserHandle.getCallingUserId(); 3763 if (DEBUG_PREFERRED) { 3764 Log.v(TAG, "setLastChosenActivity intent=" + intent 3765 + " resolvedType=" + resolvedType 3766 + " flags=" + flags 3767 + " filter=" + filter 3768 + " match=" + match 3769 + " activity=" + activity); 3770 filter.dump(new PrintStreamPrinter(System.out), " "); 3771 } 3772 intent.setComponent(null); 3773 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3774 // Find any earlier preferred or last chosen entries and nuke them 3775 findPreferredActivity(intent, resolvedType, 3776 flags, query, 0, false, true, false, userId); 3777 // Add the new activity as the last chosen for this filter 3778 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3779 "Setting last chosen"); 3780 } 3781 3782 @Override 3783 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3784 final int userId = UserHandle.getCallingUserId(); 3785 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3786 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3787 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3788 false, false, false, userId); 3789 } 3790 3791 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3792 int flags, List<ResolveInfo> query, int userId) { 3793 if (query != null) { 3794 final int N = query.size(); 3795 if (N == 1) { 3796 return query.get(0); 3797 } else if (N > 1) { 3798 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3799 // If there is more than one activity with the same priority, 3800 // then let the user decide between them. 3801 ResolveInfo r0 = query.get(0); 3802 ResolveInfo r1 = query.get(1); 3803 if (DEBUG_INTENT_MATCHING || debug) { 3804 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3805 + r1.activityInfo.name + "=" + r1.priority); 3806 } 3807 // If the first activity has a higher priority, or a different 3808 // default, then it is always desireable to pick it. 3809 if (r0.priority != r1.priority 3810 || r0.preferredOrder != r1.preferredOrder 3811 || r0.isDefault != r1.isDefault) { 3812 return query.get(0); 3813 } 3814 // If we have saved a preference for a preferred activity for 3815 // this Intent, use that. 3816 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3817 flags, query, r0.priority, true, false, debug, userId); 3818 if (ri != null) { 3819 return ri; 3820 } 3821 if (userId != 0) { 3822 ri = new ResolveInfo(mResolveInfo); 3823 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3824 ri.activityInfo.applicationInfo = new ApplicationInfo( 3825 ri.activityInfo.applicationInfo); 3826 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3827 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3828 return ri; 3829 } 3830 return mResolveInfo; 3831 } 3832 } 3833 return null; 3834 } 3835 3836 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3837 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3838 final int N = query.size(); 3839 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3840 .get(userId); 3841 // Get the list of persistent preferred activities that handle the intent 3842 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3843 List<PersistentPreferredActivity> pprefs = ppir != null 3844 ? ppir.queryIntent(intent, resolvedType, 3845 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3846 : null; 3847 if (pprefs != null && pprefs.size() > 0) { 3848 final int M = pprefs.size(); 3849 for (int i=0; i<M; i++) { 3850 final PersistentPreferredActivity ppa = pprefs.get(i); 3851 if (DEBUG_PREFERRED || debug) { 3852 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3853 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3854 + "\n component=" + ppa.mComponent); 3855 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3856 } 3857 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3858 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3859 if (DEBUG_PREFERRED || debug) { 3860 Slog.v(TAG, "Found persistent preferred activity:"); 3861 if (ai != null) { 3862 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3863 } else { 3864 Slog.v(TAG, " null"); 3865 } 3866 } 3867 if (ai == null) { 3868 // This previously registered persistent preferred activity 3869 // component is no longer known. Ignore it and do NOT remove it. 3870 continue; 3871 } 3872 for (int j=0; j<N; j++) { 3873 final ResolveInfo ri = query.get(j); 3874 if (!ri.activityInfo.applicationInfo.packageName 3875 .equals(ai.applicationInfo.packageName)) { 3876 continue; 3877 } 3878 if (!ri.activityInfo.name.equals(ai.name)) { 3879 continue; 3880 } 3881 // Found a persistent preference that can handle the intent. 3882 if (DEBUG_PREFERRED || debug) { 3883 Slog.v(TAG, "Returning persistent preferred activity: " + 3884 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3885 } 3886 return ri; 3887 } 3888 } 3889 } 3890 return null; 3891 } 3892 3893 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3894 List<ResolveInfo> query, int priority, boolean always, 3895 boolean removeMatches, boolean debug, int userId) { 3896 if (!sUserManager.exists(userId)) return null; 3897 // writer 3898 synchronized (mPackages) { 3899 if (intent.getSelector() != null) { 3900 intent = intent.getSelector(); 3901 } 3902 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3903 3904 // Try to find a matching persistent preferred activity. 3905 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3906 debug, userId); 3907 3908 // If a persistent preferred activity matched, use it. 3909 if (pri != null) { 3910 return pri; 3911 } 3912 3913 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3914 // Get the list of preferred activities that handle the intent 3915 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3916 List<PreferredActivity> prefs = pir != null 3917 ? pir.queryIntent(intent, resolvedType, 3918 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3919 : null; 3920 if (prefs != null && prefs.size() > 0) { 3921 boolean changed = false; 3922 try { 3923 // First figure out how good the original match set is. 3924 // We will only allow preferred activities that came 3925 // from the same match quality. 3926 int match = 0; 3927 3928 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3929 3930 final int N = query.size(); 3931 for (int j=0; j<N; j++) { 3932 final ResolveInfo ri = query.get(j); 3933 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3934 + ": 0x" + Integer.toHexString(match)); 3935 if (ri.match > match) { 3936 match = ri.match; 3937 } 3938 } 3939 3940 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3941 + Integer.toHexString(match)); 3942 3943 match &= IntentFilter.MATCH_CATEGORY_MASK; 3944 final int M = prefs.size(); 3945 for (int i=0; i<M; i++) { 3946 final PreferredActivity pa = prefs.get(i); 3947 if (DEBUG_PREFERRED || debug) { 3948 Slog.v(TAG, "Checking PreferredActivity ds=" 3949 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3950 + "\n component=" + pa.mPref.mComponent); 3951 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3952 } 3953 if (pa.mPref.mMatch != match) { 3954 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3955 + Integer.toHexString(pa.mPref.mMatch)); 3956 continue; 3957 } 3958 // If it's not an "always" type preferred activity and that's what we're 3959 // looking for, skip it. 3960 if (always && !pa.mPref.mAlways) { 3961 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3962 continue; 3963 } 3964 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3965 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3966 if (DEBUG_PREFERRED || debug) { 3967 Slog.v(TAG, "Found preferred activity:"); 3968 if (ai != null) { 3969 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3970 } else { 3971 Slog.v(TAG, " null"); 3972 } 3973 } 3974 if (ai == null) { 3975 // This previously registered preferred activity 3976 // component is no longer known. Most likely an update 3977 // to the app was installed and in the new version this 3978 // component no longer exists. Clean it up by removing 3979 // it from the preferred activities list, and skip it. 3980 Slog.w(TAG, "Removing dangling preferred activity: " 3981 + pa.mPref.mComponent); 3982 pir.removeFilter(pa); 3983 changed = true; 3984 continue; 3985 } 3986 for (int j=0; j<N; j++) { 3987 final ResolveInfo ri = query.get(j); 3988 if (!ri.activityInfo.applicationInfo.packageName 3989 .equals(ai.applicationInfo.packageName)) { 3990 continue; 3991 } 3992 if (!ri.activityInfo.name.equals(ai.name)) { 3993 continue; 3994 } 3995 3996 if (removeMatches) { 3997 pir.removeFilter(pa); 3998 changed = true; 3999 if (DEBUG_PREFERRED) { 4000 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4001 } 4002 break; 4003 } 4004 4005 // Okay we found a previously set preferred or last chosen app. 4006 // If the result set is different from when this 4007 // was created, we need to clear it and re-ask the 4008 // user their preference, if we're looking for an "always" type entry. 4009 if (always && !pa.mPref.sameSet(query)) { 4010 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4011 + intent + " type " + resolvedType); 4012 if (DEBUG_PREFERRED) { 4013 Slog.v(TAG, "Removing preferred activity since set changed " 4014 + pa.mPref.mComponent); 4015 } 4016 pir.removeFilter(pa); 4017 // Re-add the filter as a "last chosen" entry (!always) 4018 PreferredActivity lastChosen = new PreferredActivity( 4019 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4020 pir.addFilter(lastChosen); 4021 changed = true; 4022 return null; 4023 } 4024 4025 // Yay! Either the set matched or we're looking for the last chosen 4026 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4027 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4028 return ri; 4029 } 4030 } 4031 } finally { 4032 if (changed) { 4033 if (DEBUG_PREFERRED) { 4034 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4035 } 4036 scheduleWritePackageRestrictionsLocked(userId); 4037 } 4038 } 4039 } 4040 } 4041 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4042 return null; 4043 } 4044 4045 /* 4046 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4047 */ 4048 @Override 4049 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4050 int targetUserId) { 4051 mContext.enforceCallingOrSelfPermission( 4052 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4053 List<CrossProfileIntentFilter> matches = 4054 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4055 if (matches != null) { 4056 int size = matches.size(); 4057 for (int i = 0; i < size; i++) { 4058 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4059 } 4060 } 4061 return false; 4062 } 4063 4064 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4065 String resolvedType, int userId) { 4066 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4067 if (resolver != null) { 4068 return resolver.queryIntent(intent, resolvedType, false, userId); 4069 } 4070 return null; 4071 } 4072 4073 @Override 4074 public List<ResolveInfo> queryIntentActivities(Intent intent, 4075 String resolvedType, int flags, int userId) { 4076 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4077 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4078 ComponentName comp = intent.getComponent(); 4079 if (comp == null) { 4080 if (intent.getSelector() != null) { 4081 intent = intent.getSelector(); 4082 comp = intent.getComponent(); 4083 } 4084 } 4085 4086 if (comp != null) { 4087 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4088 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4089 if (ai != null) { 4090 final ResolveInfo ri = new ResolveInfo(); 4091 ri.activityInfo = ai; 4092 list.add(ri); 4093 } 4094 return list; 4095 } 4096 4097 // reader 4098 synchronized (mPackages) { 4099 final String pkgName = intent.getPackage(); 4100 if (pkgName == null) { 4101 List<CrossProfileIntentFilter> matchingFilters = 4102 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4103 // Check for results that need to skip the current profile. 4104 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4105 resolvedType, flags, userId); 4106 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4107 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4108 result.add(resolveInfo); 4109 return filterIfNotPrimaryUser(result, userId); 4110 } 4111 4112 // Check for results in the current profile. 4113 List<ResolveInfo> result = mActivities.queryIntent( 4114 intent, resolvedType, flags, userId); 4115 4116 // Check for cross profile results. 4117 resolveInfo = queryCrossProfileIntents( 4118 matchingFilters, intent, resolvedType, flags, userId); 4119 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4120 result.add(resolveInfo); 4121 Collections.sort(result, mResolvePrioritySorter); 4122 } 4123 result = filterIfNotPrimaryUser(result, userId); 4124 if (result.size() > 1 && hasWebURI(intent)) { 4125 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4126 } 4127 return result; 4128 } 4129 final PackageParser.Package pkg = mPackages.get(pkgName); 4130 if (pkg != null) { 4131 return filterIfNotPrimaryUser( 4132 mActivities.queryIntentForPackage( 4133 intent, resolvedType, flags, pkg.activities, userId), 4134 userId); 4135 } 4136 return new ArrayList<ResolveInfo>(); 4137 } 4138 } 4139 4140 private boolean isUserEnabled(int userId) { 4141 long callingId = Binder.clearCallingIdentity(); 4142 try { 4143 UserInfo userInfo = sUserManager.getUserInfo(userId); 4144 return userInfo != null && userInfo.isEnabled(); 4145 } finally { 4146 Binder.restoreCallingIdentity(callingId); 4147 } 4148 } 4149 4150 /** 4151 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4152 * 4153 * @return filtered list 4154 */ 4155 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4156 if (userId == UserHandle.USER_OWNER) { 4157 return resolveInfos; 4158 } 4159 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4160 ResolveInfo info = resolveInfos.get(i); 4161 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4162 resolveInfos.remove(i); 4163 } 4164 } 4165 return resolveInfos; 4166 } 4167 4168 private static boolean hasWebURI(Intent intent) { 4169 if (intent.getData() == null) { 4170 return false; 4171 } 4172 final String scheme = intent.getScheme(); 4173 if (TextUtils.isEmpty(scheme)) { 4174 return false; 4175 } 4176 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4177 } 4178 4179 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4180 int flags, List<ResolveInfo> candidates) { 4181 if (DEBUG_PREFERRED) { 4182 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4183 candidates.size()); 4184 } 4185 4186 final int userId = UserHandle.getCallingUserId(); 4187 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4188 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4189 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4190 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4191 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4192 4193 synchronized (mPackages) { 4194 final int count = candidates.size(); 4195 // First, try to use the domain prefered App. Partition the candidates into four lists: 4196 // one for the final results, one for the "do not use ever", one for "undefined status" 4197 // and finally one for "Browser App type". 4198 for (int n=0; n<count; n++) { 4199 ResolveInfo info = candidates.get(n); 4200 String packageName = info.activityInfo.packageName; 4201 PackageSetting ps = mSettings.mPackages.get(packageName); 4202 if (ps != null) { 4203 // Add to the special match all list (Browser use case) 4204 if (info.handleAllWebDataURI) { 4205 matchAllList.add(info); 4206 continue; 4207 } 4208 // Try to get the status from User settings first 4209 int status = getDomainVerificationStatusLPr(ps, userId); 4210 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4211 alwaysList.add(info); 4212 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4213 neverList.add(info); 4214 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4215 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4216 undefinedList.add(info); 4217 } 4218 } 4219 } 4220 // First try to add the "always" if there is any 4221 if (alwaysList.size() > 0) { 4222 result.addAll(alwaysList); 4223 } else { 4224 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4225 result.addAll(undefinedList); 4226 // Also add Browsers (all of them or only the default one) 4227 if ((flags & MATCH_ALL) != 0) { 4228 result.addAll(matchAllList); 4229 } else { 4230 // Try to add the Default Browser if we can 4231 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4232 UserHandle.myUserId()); 4233 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4234 boolean defaultBrowserFound = false; 4235 final int browserCount = matchAllList.size(); 4236 for (int n=0; n<browserCount; n++) { 4237 ResolveInfo browser = matchAllList.get(n); 4238 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4239 result.add(browser); 4240 defaultBrowserFound = true; 4241 break; 4242 } 4243 } 4244 if (!defaultBrowserFound) { 4245 result.addAll(matchAllList); 4246 } 4247 } else { 4248 result.addAll(matchAllList); 4249 } 4250 } 4251 4252 // If there is nothing selected, add all candidates and remove the ones that the User 4253 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4254 if (result.size() == 0) { 4255 result.addAll(candidates); 4256 result.removeAll(neverList); 4257 } 4258 } 4259 } 4260 if (DEBUG_PREFERRED) { 4261 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4262 result.size()); 4263 } 4264 return result; 4265 } 4266 4267 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4268 int status = ps.getDomainVerificationStatusForUser(userId); 4269 // if none available, get the master status 4270 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4271 if (ps.getIntentFilterVerificationInfo() != null) { 4272 status = ps.getIntentFilterVerificationInfo().getStatus(); 4273 } 4274 } 4275 return status; 4276 } 4277 4278 private ResolveInfo querySkipCurrentProfileIntents( 4279 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4280 int flags, int sourceUserId) { 4281 if (matchingFilters != null) { 4282 int size = matchingFilters.size(); 4283 for (int i = 0; i < size; i ++) { 4284 CrossProfileIntentFilter filter = matchingFilters.get(i); 4285 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4286 // Checking if there are activities in the target user that can handle the 4287 // intent. 4288 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4289 flags, sourceUserId); 4290 if (resolveInfo != null) { 4291 return resolveInfo; 4292 } 4293 } 4294 } 4295 } 4296 return null; 4297 } 4298 4299 // Return matching ResolveInfo if any for skip current profile intent filters. 4300 private ResolveInfo queryCrossProfileIntents( 4301 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4302 int flags, int sourceUserId) { 4303 if (matchingFilters != null) { 4304 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4305 // match the same intent. For performance reasons, it is better not to 4306 // run queryIntent twice for the same userId 4307 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4308 int size = matchingFilters.size(); 4309 for (int i = 0; i < size; i++) { 4310 CrossProfileIntentFilter filter = matchingFilters.get(i); 4311 int targetUserId = filter.getTargetUserId(); 4312 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4313 && !alreadyTriedUserIds.get(targetUserId)) { 4314 // Checking if there are activities in the target user that can handle the 4315 // intent. 4316 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4317 flags, sourceUserId); 4318 if (resolveInfo != null) return resolveInfo; 4319 alreadyTriedUserIds.put(targetUserId, true); 4320 } 4321 } 4322 } 4323 return null; 4324 } 4325 4326 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4327 String resolvedType, int flags, int sourceUserId) { 4328 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4329 resolvedType, flags, filter.getTargetUserId()); 4330 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4331 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4332 } 4333 return null; 4334 } 4335 4336 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4337 int sourceUserId, int targetUserId) { 4338 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4339 String className; 4340 if (targetUserId == UserHandle.USER_OWNER) { 4341 className = FORWARD_INTENT_TO_USER_OWNER; 4342 } else { 4343 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4344 } 4345 ComponentName forwardingActivityComponentName = new ComponentName( 4346 mAndroidApplication.packageName, className); 4347 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4348 sourceUserId); 4349 if (targetUserId == UserHandle.USER_OWNER) { 4350 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4351 forwardingResolveInfo.noResourceId = true; 4352 } 4353 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4354 forwardingResolveInfo.priority = 0; 4355 forwardingResolveInfo.preferredOrder = 0; 4356 forwardingResolveInfo.match = 0; 4357 forwardingResolveInfo.isDefault = true; 4358 forwardingResolveInfo.filter = filter; 4359 forwardingResolveInfo.targetUserId = targetUserId; 4360 return forwardingResolveInfo; 4361 } 4362 4363 @Override 4364 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4365 Intent[] specifics, String[] specificTypes, Intent intent, 4366 String resolvedType, int flags, int userId) { 4367 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4368 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4369 false, "query intent activity options"); 4370 final String resultsAction = intent.getAction(); 4371 4372 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4373 | PackageManager.GET_RESOLVED_FILTER, userId); 4374 4375 if (DEBUG_INTENT_MATCHING) { 4376 Log.v(TAG, "Query " + intent + ": " + results); 4377 } 4378 4379 int specificsPos = 0; 4380 int N; 4381 4382 // todo: note that the algorithm used here is O(N^2). This 4383 // isn't a problem in our current environment, but if we start running 4384 // into situations where we have more than 5 or 10 matches then this 4385 // should probably be changed to something smarter... 4386 4387 // First we go through and resolve each of the specific items 4388 // that were supplied, taking care of removing any corresponding 4389 // duplicate items in the generic resolve list. 4390 if (specifics != null) { 4391 for (int i=0; i<specifics.length; i++) { 4392 final Intent sintent = specifics[i]; 4393 if (sintent == null) { 4394 continue; 4395 } 4396 4397 if (DEBUG_INTENT_MATCHING) { 4398 Log.v(TAG, "Specific #" + i + ": " + sintent); 4399 } 4400 4401 String action = sintent.getAction(); 4402 if (resultsAction != null && resultsAction.equals(action)) { 4403 // If this action was explicitly requested, then don't 4404 // remove things that have it. 4405 action = null; 4406 } 4407 4408 ResolveInfo ri = null; 4409 ActivityInfo ai = null; 4410 4411 ComponentName comp = sintent.getComponent(); 4412 if (comp == null) { 4413 ri = resolveIntent( 4414 sintent, 4415 specificTypes != null ? specificTypes[i] : null, 4416 flags, userId); 4417 if (ri == null) { 4418 continue; 4419 } 4420 if (ri == mResolveInfo) { 4421 // ACK! Must do something better with this. 4422 } 4423 ai = ri.activityInfo; 4424 comp = new ComponentName(ai.applicationInfo.packageName, 4425 ai.name); 4426 } else { 4427 ai = getActivityInfo(comp, flags, userId); 4428 if (ai == null) { 4429 continue; 4430 } 4431 } 4432 4433 // Look for any generic query activities that are duplicates 4434 // of this specific one, and remove them from the results. 4435 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4436 N = results.size(); 4437 int j; 4438 for (j=specificsPos; j<N; j++) { 4439 ResolveInfo sri = results.get(j); 4440 if ((sri.activityInfo.name.equals(comp.getClassName()) 4441 && sri.activityInfo.applicationInfo.packageName.equals( 4442 comp.getPackageName())) 4443 || (action != null && sri.filter.matchAction(action))) { 4444 results.remove(j); 4445 if (DEBUG_INTENT_MATCHING) Log.v( 4446 TAG, "Removing duplicate item from " + j 4447 + " due to specific " + specificsPos); 4448 if (ri == null) { 4449 ri = sri; 4450 } 4451 j--; 4452 N--; 4453 } 4454 } 4455 4456 // Add this specific item to its proper place. 4457 if (ri == null) { 4458 ri = new ResolveInfo(); 4459 ri.activityInfo = ai; 4460 } 4461 results.add(specificsPos, ri); 4462 ri.specificIndex = i; 4463 specificsPos++; 4464 } 4465 } 4466 4467 // Now we go through the remaining generic results and remove any 4468 // duplicate actions that are found here. 4469 N = results.size(); 4470 for (int i=specificsPos; i<N-1; i++) { 4471 final ResolveInfo rii = results.get(i); 4472 if (rii.filter == null) { 4473 continue; 4474 } 4475 4476 // Iterate over all of the actions of this result's intent 4477 // filter... typically this should be just one. 4478 final Iterator<String> it = rii.filter.actionsIterator(); 4479 if (it == null) { 4480 continue; 4481 } 4482 while (it.hasNext()) { 4483 final String action = it.next(); 4484 if (resultsAction != null && resultsAction.equals(action)) { 4485 // If this action was explicitly requested, then don't 4486 // remove things that have it. 4487 continue; 4488 } 4489 for (int j=i+1; j<N; j++) { 4490 final ResolveInfo rij = results.get(j); 4491 if (rij.filter != null && rij.filter.hasAction(action)) { 4492 results.remove(j); 4493 if (DEBUG_INTENT_MATCHING) Log.v( 4494 TAG, "Removing duplicate item from " + j 4495 + " due to action " + action + " at " + i); 4496 j--; 4497 N--; 4498 } 4499 } 4500 } 4501 4502 // If the caller didn't request filter information, drop it now 4503 // so we don't have to marshall/unmarshall it. 4504 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4505 rii.filter = null; 4506 } 4507 } 4508 4509 // Filter out the caller activity if so requested. 4510 if (caller != null) { 4511 N = results.size(); 4512 for (int i=0; i<N; i++) { 4513 ActivityInfo ainfo = results.get(i).activityInfo; 4514 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4515 && caller.getClassName().equals(ainfo.name)) { 4516 results.remove(i); 4517 break; 4518 } 4519 } 4520 } 4521 4522 // If the caller didn't request filter information, 4523 // drop them now so we don't have to 4524 // marshall/unmarshall it. 4525 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4526 N = results.size(); 4527 for (int i=0; i<N; i++) { 4528 results.get(i).filter = null; 4529 } 4530 } 4531 4532 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4533 return results; 4534 } 4535 4536 @Override 4537 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4538 int userId) { 4539 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4540 ComponentName comp = intent.getComponent(); 4541 if (comp == null) { 4542 if (intent.getSelector() != null) { 4543 intent = intent.getSelector(); 4544 comp = intent.getComponent(); 4545 } 4546 } 4547 if (comp != null) { 4548 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4549 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4550 if (ai != null) { 4551 ResolveInfo ri = new ResolveInfo(); 4552 ri.activityInfo = ai; 4553 list.add(ri); 4554 } 4555 return list; 4556 } 4557 4558 // reader 4559 synchronized (mPackages) { 4560 String pkgName = intent.getPackage(); 4561 if (pkgName == null) { 4562 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4563 } 4564 final PackageParser.Package pkg = mPackages.get(pkgName); 4565 if (pkg != null) { 4566 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4567 userId); 4568 } 4569 return null; 4570 } 4571 } 4572 4573 @Override 4574 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4575 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4576 if (!sUserManager.exists(userId)) return null; 4577 if (query != null) { 4578 if (query.size() >= 1) { 4579 // If there is more than one service with the same priority, 4580 // just arbitrarily pick the first one. 4581 return query.get(0); 4582 } 4583 } 4584 return null; 4585 } 4586 4587 @Override 4588 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4589 int userId) { 4590 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4591 ComponentName comp = intent.getComponent(); 4592 if (comp == null) { 4593 if (intent.getSelector() != null) { 4594 intent = intent.getSelector(); 4595 comp = intent.getComponent(); 4596 } 4597 } 4598 if (comp != null) { 4599 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4600 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4601 if (si != null) { 4602 final ResolveInfo ri = new ResolveInfo(); 4603 ri.serviceInfo = si; 4604 list.add(ri); 4605 } 4606 return list; 4607 } 4608 4609 // reader 4610 synchronized (mPackages) { 4611 String pkgName = intent.getPackage(); 4612 if (pkgName == null) { 4613 return mServices.queryIntent(intent, resolvedType, flags, userId); 4614 } 4615 final PackageParser.Package pkg = mPackages.get(pkgName); 4616 if (pkg != null) { 4617 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4618 userId); 4619 } 4620 return null; 4621 } 4622 } 4623 4624 @Override 4625 public List<ResolveInfo> queryIntentContentProviders( 4626 Intent intent, String resolvedType, int flags, int userId) { 4627 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4628 ComponentName comp = intent.getComponent(); 4629 if (comp == null) { 4630 if (intent.getSelector() != null) { 4631 intent = intent.getSelector(); 4632 comp = intent.getComponent(); 4633 } 4634 } 4635 if (comp != null) { 4636 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4637 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4638 if (pi != null) { 4639 final ResolveInfo ri = new ResolveInfo(); 4640 ri.providerInfo = pi; 4641 list.add(ri); 4642 } 4643 return list; 4644 } 4645 4646 // reader 4647 synchronized (mPackages) { 4648 String pkgName = intent.getPackage(); 4649 if (pkgName == null) { 4650 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4651 } 4652 final PackageParser.Package pkg = mPackages.get(pkgName); 4653 if (pkg != null) { 4654 return mProviders.queryIntentForPackage( 4655 intent, resolvedType, flags, pkg.providers, userId); 4656 } 4657 return null; 4658 } 4659 } 4660 4661 @Override 4662 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4663 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4664 4665 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4666 4667 // writer 4668 synchronized (mPackages) { 4669 ArrayList<PackageInfo> list; 4670 if (listUninstalled) { 4671 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4672 for (PackageSetting ps : mSettings.mPackages.values()) { 4673 PackageInfo pi; 4674 if (ps.pkg != null) { 4675 pi = generatePackageInfo(ps.pkg, flags, userId); 4676 } else { 4677 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4678 } 4679 if (pi != null) { 4680 list.add(pi); 4681 } 4682 } 4683 } else { 4684 list = new ArrayList<PackageInfo>(mPackages.size()); 4685 for (PackageParser.Package p : mPackages.values()) { 4686 PackageInfo pi = generatePackageInfo(p, flags, userId); 4687 if (pi != null) { 4688 list.add(pi); 4689 } 4690 } 4691 } 4692 4693 return new ParceledListSlice<PackageInfo>(list); 4694 } 4695 } 4696 4697 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4698 String[] permissions, boolean[] tmp, int flags, int userId) { 4699 int numMatch = 0; 4700 final PermissionsState permissionsState = ps.getPermissionsState(); 4701 for (int i=0; i<permissions.length; i++) { 4702 final String permission = permissions[i]; 4703 if (permissionsState.hasPermission(permission, userId)) { 4704 tmp[i] = true; 4705 numMatch++; 4706 } else { 4707 tmp[i] = false; 4708 } 4709 } 4710 if (numMatch == 0) { 4711 return; 4712 } 4713 PackageInfo pi; 4714 if (ps.pkg != null) { 4715 pi = generatePackageInfo(ps.pkg, flags, userId); 4716 } else { 4717 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4718 } 4719 // The above might return null in cases of uninstalled apps or install-state 4720 // skew across users/profiles. 4721 if (pi != null) { 4722 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4723 if (numMatch == permissions.length) { 4724 pi.requestedPermissions = permissions; 4725 } else { 4726 pi.requestedPermissions = new String[numMatch]; 4727 numMatch = 0; 4728 for (int i=0; i<permissions.length; i++) { 4729 if (tmp[i]) { 4730 pi.requestedPermissions[numMatch] = permissions[i]; 4731 numMatch++; 4732 } 4733 } 4734 } 4735 } 4736 list.add(pi); 4737 } 4738 } 4739 4740 @Override 4741 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4742 String[] permissions, int flags, int userId) { 4743 if (!sUserManager.exists(userId)) return null; 4744 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4745 4746 // writer 4747 synchronized (mPackages) { 4748 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4749 boolean[] tmpBools = new boolean[permissions.length]; 4750 if (listUninstalled) { 4751 for (PackageSetting ps : mSettings.mPackages.values()) { 4752 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4753 } 4754 } else { 4755 for (PackageParser.Package pkg : mPackages.values()) { 4756 PackageSetting ps = (PackageSetting)pkg.mExtras; 4757 if (ps != null) { 4758 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4759 userId); 4760 } 4761 } 4762 } 4763 4764 return new ParceledListSlice<PackageInfo>(list); 4765 } 4766 } 4767 4768 @Override 4769 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4770 if (!sUserManager.exists(userId)) return null; 4771 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4772 4773 // writer 4774 synchronized (mPackages) { 4775 ArrayList<ApplicationInfo> list; 4776 if (listUninstalled) { 4777 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4778 for (PackageSetting ps : mSettings.mPackages.values()) { 4779 ApplicationInfo ai; 4780 if (ps.pkg != null) { 4781 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4782 ps.readUserState(userId), userId); 4783 } else { 4784 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4785 } 4786 if (ai != null) { 4787 list.add(ai); 4788 } 4789 } 4790 } else { 4791 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4792 for (PackageParser.Package p : mPackages.values()) { 4793 if (p.mExtras != null) { 4794 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4795 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4796 if (ai != null) { 4797 list.add(ai); 4798 } 4799 } 4800 } 4801 } 4802 4803 return new ParceledListSlice<ApplicationInfo>(list); 4804 } 4805 } 4806 4807 public List<ApplicationInfo> getPersistentApplications(int flags) { 4808 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4809 4810 // reader 4811 synchronized (mPackages) { 4812 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4813 final int userId = UserHandle.getCallingUserId(); 4814 while (i.hasNext()) { 4815 final PackageParser.Package p = i.next(); 4816 if (p.applicationInfo != null 4817 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4818 && (!mSafeMode || isSystemApp(p))) { 4819 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4820 if (ps != null) { 4821 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4822 ps.readUserState(userId), userId); 4823 if (ai != null) { 4824 finalList.add(ai); 4825 } 4826 } 4827 } 4828 } 4829 } 4830 4831 return finalList; 4832 } 4833 4834 @Override 4835 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4836 if (!sUserManager.exists(userId)) return null; 4837 // reader 4838 synchronized (mPackages) { 4839 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4840 PackageSetting ps = provider != null 4841 ? mSettings.mPackages.get(provider.owner.packageName) 4842 : null; 4843 return ps != null 4844 && mSettings.isEnabledLPr(provider.info, flags, userId) 4845 && (!mSafeMode || (provider.info.applicationInfo.flags 4846 &ApplicationInfo.FLAG_SYSTEM) != 0) 4847 ? PackageParser.generateProviderInfo(provider, flags, 4848 ps.readUserState(userId), userId) 4849 : null; 4850 } 4851 } 4852 4853 /** 4854 * @deprecated 4855 */ 4856 @Deprecated 4857 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4858 // reader 4859 synchronized (mPackages) { 4860 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4861 .entrySet().iterator(); 4862 final int userId = UserHandle.getCallingUserId(); 4863 while (i.hasNext()) { 4864 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4865 PackageParser.Provider p = entry.getValue(); 4866 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4867 4868 if (ps != null && p.syncable 4869 && (!mSafeMode || (p.info.applicationInfo.flags 4870 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4871 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4872 ps.readUserState(userId), userId); 4873 if (info != null) { 4874 outNames.add(entry.getKey()); 4875 outInfo.add(info); 4876 } 4877 } 4878 } 4879 } 4880 } 4881 4882 @Override 4883 public List<ProviderInfo> queryContentProviders(String processName, 4884 int uid, int flags) { 4885 ArrayList<ProviderInfo> finalList = null; 4886 // reader 4887 synchronized (mPackages) { 4888 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4889 final int userId = processName != null ? 4890 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4891 while (i.hasNext()) { 4892 final PackageParser.Provider p = i.next(); 4893 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4894 if (ps != null && p.info.authority != null 4895 && (processName == null 4896 || (p.info.processName.equals(processName) 4897 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4898 && mSettings.isEnabledLPr(p.info, flags, userId) 4899 && (!mSafeMode 4900 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4901 if (finalList == null) { 4902 finalList = new ArrayList<ProviderInfo>(3); 4903 } 4904 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4905 ps.readUserState(userId), userId); 4906 if (info != null) { 4907 finalList.add(info); 4908 } 4909 } 4910 } 4911 } 4912 4913 if (finalList != null) { 4914 Collections.sort(finalList, mProviderInitOrderSorter); 4915 } 4916 4917 return finalList; 4918 } 4919 4920 @Override 4921 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4922 int flags) { 4923 // reader 4924 synchronized (mPackages) { 4925 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4926 return PackageParser.generateInstrumentationInfo(i, flags); 4927 } 4928 } 4929 4930 @Override 4931 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4932 int flags) { 4933 ArrayList<InstrumentationInfo> finalList = 4934 new ArrayList<InstrumentationInfo>(); 4935 4936 // reader 4937 synchronized (mPackages) { 4938 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4939 while (i.hasNext()) { 4940 final PackageParser.Instrumentation p = i.next(); 4941 if (targetPackage == null 4942 || targetPackage.equals(p.info.targetPackage)) { 4943 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4944 flags); 4945 if (ii != null) { 4946 finalList.add(ii); 4947 } 4948 } 4949 } 4950 } 4951 4952 return finalList; 4953 } 4954 4955 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4956 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4957 if (overlays == null) { 4958 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4959 return; 4960 } 4961 for (PackageParser.Package opkg : overlays.values()) { 4962 // Not much to do if idmap fails: we already logged the error 4963 // and we certainly don't want to abort installation of pkg simply 4964 // because an overlay didn't fit properly. For these reasons, 4965 // ignore the return value of createIdmapForPackagePairLI. 4966 createIdmapForPackagePairLI(pkg, opkg); 4967 } 4968 } 4969 4970 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4971 PackageParser.Package opkg) { 4972 if (!opkg.mTrustedOverlay) { 4973 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4974 opkg.baseCodePath + ": overlay not trusted"); 4975 return false; 4976 } 4977 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4978 if (overlaySet == null) { 4979 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4980 opkg.baseCodePath + " but target package has no known overlays"); 4981 return false; 4982 } 4983 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4984 // TODO: generate idmap for split APKs 4985 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4986 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4987 + opkg.baseCodePath); 4988 return false; 4989 } 4990 PackageParser.Package[] overlayArray = 4991 overlaySet.values().toArray(new PackageParser.Package[0]); 4992 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4993 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4994 return p1.mOverlayPriority - p2.mOverlayPriority; 4995 } 4996 }; 4997 Arrays.sort(overlayArray, cmp); 4998 4999 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5000 int i = 0; 5001 for (PackageParser.Package p : overlayArray) { 5002 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5003 } 5004 return true; 5005 } 5006 5007 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5008 final File[] files = dir.listFiles(); 5009 if (ArrayUtils.isEmpty(files)) { 5010 Log.d(TAG, "No files in app dir " + dir); 5011 return; 5012 } 5013 5014 if (DEBUG_PACKAGE_SCANNING) { 5015 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5016 + " flags=0x" + Integer.toHexString(parseFlags)); 5017 } 5018 5019 for (File file : files) { 5020 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5021 && !PackageInstallerService.isStageName(file.getName()); 5022 if (!isPackage) { 5023 // Ignore entries which are not packages 5024 continue; 5025 } 5026 try { 5027 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5028 scanFlags, currentTime, null); 5029 } catch (PackageManagerException e) { 5030 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5031 5032 // Delete invalid userdata apps 5033 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5034 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5035 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5036 if (file.isDirectory()) { 5037 mInstaller.rmPackageDir(file.getAbsolutePath()); 5038 } else { 5039 file.delete(); 5040 } 5041 } 5042 } 5043 } 5044 } 5045 5046 private static File getSettingsProblemFile() { 5047 File dataDir = Environment.getDataDirectory(); 5048 File systemDir = new File(dataDir, "system"); 5049 File fname = new File(systemDir, "uiderrors.txt"); 5050 return fname; 5051 } 5052 5053 static void reportSettingsProblem(int priority, String msg) { 5054 logCriticalInfo(priority, msg); 5055 } 5056 5057 static void logCriticalInfo(int priority, String msg) { 5058 Slog.println(priority, TAG, msg); 5059 EventLogTags.writePmCriticalInfo(msg); 5060 try { 5061 File fname = getSettingsProblemFile(); 5062 FileOutputStream out = new FileOutputStream(fname, true); 5063 PrintWriter pw = new FastPrintWriter(out); 5064 SimpleDateFormat formatter = new SimpleDateFormat(); 5065 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5066 pw.println(dateString + ": " + msg); 5067 pw.close(); 5068 FileUtils.setPermissions( 5069 fname.toString(), 5070 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5071 -1, -1); 5072 } catch (java.io.IOException e) { 5073 } 5074 } 5075 5076 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5077 PackageParser.Package pkg, File srcFile, int parseFlags) 5078 throws PackageManagerException { 5079 if (ps != null 5080 && ps.codePath.equals(srcFile) 5081 && ps.timeStamp == srcFile.lastModified() 5082 && !isCompatSignatureUpdateNeeded(pkg) 5083 && !isRecoverSignatureUpdateNeeded(pkg)) { 5084 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5085 if (ps.signatures.mSignatures != null 5086 && ps.signatures.mSignatures.length != 0 5087 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5088 // Optimization: reuse the existing cached certificates 5089 // if the package appears to be unchanged. 5090 pkg.mSignatures = ps.signatures.mSignatures; 5091 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5092 synchronized (mPackages) { 5093 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5094 } 5095 return; 5096 } 5097 5098 Slog.w(TAG, "PackageSetting for " + ps.name 5099 + " is missing signatures. Collecting certs again to recover them."); 5100 } else { 5101 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5102 } 5103 5104 try { 5105 pp.collectCertificates(pkg, parseFlags); 5106 pp.collectManifestDigest(pkg); 5107 } catch (PackageParserException e) { 5108 throw PackageManagerException.from(e); 5109 } 5110 } 5111 5112 /* 5113 * Scan a package and return the newly parsed package. 5114 * Returns null in case of errors and the error code is stored in mLastScanError 5115 */ 5116 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5117 long currentTime, UserHandle user) throws PackageManagerException { 5118 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5119 parseFlags |= mDefParseFlags; 5120 PackageParser pp = new PackageParser(); 5121 pp.setSeparateProcesses(mSeparateProcesses); 5122 pp.setOnlyCoreApps(mOnlyCore); 5123 pp.setDisplayMetrics(mMetrics); 5124 5125 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5126 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5127 } 5128 5129 final PackageParser.Package pkg; 5130 try { 5131 pkg = pp.parsePackage(scanFile, parseFlags); 5132 } catch (PackageParserException e) { 5133 throw PackageManagerException.from(e); 5134 } 5135 5136 PackageSetting ps = null; 5137 PackageSetting updatedPkg; 5138 // reader 5139 synchronized (mPackages) { 5140 // Look to see if we already know about this package. 5141 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5142 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5143 // This package has been renamed to its original name. Let's 5144 // use that. 5145 ps = mSettings.peekPackageLPr(oldName); 5146 } 5147 // If there was no original package, see one for the real package name. 5148 if (ps == null) { 5149 ps = mSettings.peekPackageLPr(pkg.packageName); 5150 } 5151 // Check to see if this package could be hiding/updating a system 5152 // package. Must look for it either under the original or real 5153 // package name depending on our state. 5154 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5155 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5156 } 5157 boolean updatedPkgBetter = false; 5158 // First check if this is a system package that may involve an update 5159 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5160 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5161 // it needs to drop FLAG_PRIVILEGED. 5162 if (locationIsPrivileged(scanFile)) { 5163 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5164 } else { 5165 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5166 } 5167 5168 if (ps != null && !ps.codePath.equals(scanFile)) { 5169 // The path has changed from what was last scanned... check the 5170 // version of the new path against what we have stored to determine 5171 // what to do. 5172 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5173 if (pkg.mVersionCode <= ps.versionCode) { 5174 // The system package has been updated and the code path does not match 5175 // Ignore entry. Skip it. 5176 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5177 + " ignored: updated version " + ps.versionCode 5178 + " better than this " + pkg.mVersionCode); 5179 if (!updatedPkg.codePath.equals(scanFile)) { 5180 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5181 + ps.name + " changing from " + updatedPkg.codePathString 5182 + " to " + scanFile); 5183 updatedPkg.codePath = scanFile; 5184 updatedPkg.codePathString = scanFile.toString(); 5185 updatedPkg.resourcePath = scanFile; 5186 updatedPkg.resourcePathString = scanFile.toString(); 5187 } 5188 updatedPkg.pkg = pkg; 5189 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5190 } else { 5191 // The current app on the system partition is better than 5192 // what we have updated to on the data partition; switch 5193 // back to the system partition version. 5194 // At this point, its safely assumed that package installation for 5195 // apps in system partition will go through. If not there won't be a working 5196 // version of the app 5197 // writer 5198 synchronized (mPackages) { 5199 // Just remove the loaded entries from package lists. 5200 mPackages.remove(ps.name); 5201 } 5202 5203 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5204 + " reverting from " + ps.codePathString 5205 + ": new version " + pkg.mVersionCode 5206 + " better than installed " + ps.versionCode); 5207 5208 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5209 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5210 synchronized (mInstallLock) { 5211 args.cleanUpResourcesLI(); 5212 } 5213 synchronized (mPackages) { 5214 mSettings.enableSystemPackageLPw(ps.name); 5215 } 5216 updatedPkgBetter = true; 5217 } 5218 } 5219 } 5220 5221 if (updatedPkg != null) { 5222 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5223 // initially 5224 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5225 5226 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5227 // flag set initially 5228 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5229 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5230 } 5231 } 5232 5233 // Verify certificates against what was last scanned 5234 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5235 5236 /* 5237 * A new system app appeared, but we already had a non-system one of the 5238 * same name installed earlier. 5239 */ 5240 boolean shouldHideSystemApp = false; 5241 if (updatedPkg == null && ps != null 5242 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5243 /* 5244 * Check to make sure the signatures match first. If they don't, 5245 * wipe the installed application and its data. 5246 */ 5247 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5248 != PackageManager.SIGNATURE_MATCH) { 5249 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5250 + " signatures don't match existing userdata copy; removing"); 5251 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5252 ps = null; 5253 } else { 5254 /* 5255 * If the newly-added system app is an older version than the 5256 * already installed version, hide it. It will be scanned later 5257 * and re-added like an update. 5258 */ 5259 if (pkg.mVersionCode <= ps.versionCode) { 5260 shouldHideSystemApp = true; 5261 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5262 + " but new version " + pkg.mVersionCode + " better than installed " 5263 + ps.versionCode + "; hiding system"); 5264 } else { 5265 /* 5266 * The newly found system app is a newer version that the 5267 * one previously installed. Simply remove the 5268 * already-installed application and replace it with our own 5269 * while keeping the application data. 5270 */ 5271 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5272 + " reverting from " + ps.codePathString + ": new version " 5273 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5274 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5275 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5276 synchronized (mInstallLock) { 5277 args.cleanUpResourcesLI(); 5278 } 5279 } 5280 } 5281 } 5282 5283 // The apk is forward locked (not public) if its code and resources 5284 // are kept in different files. (except for app in either system or 5285 // vendor path). 5286 // TODO grab this value from PackageSettings 5287 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5288 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5289 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5290 } 5291 } 5292 5293 // TODO: extend to support forward-locked splits 5294 String resourcePath = null; 5295 String baseResourcePath = null; 5296 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5297 if (ps != null && ps.resourcePathString != null) { 5298 resourcePath = ps.resourcePathString; 5299 baseResourcePath = ps.resourcePathString; 5300 } else { 5301 // Should not happen at all. Just log an error. 5302 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5303 } 5304 } else { 5305 resourcePath = pkg.codePath; 5306 baseResourcePath = pkg.baseCodePath; 5307 } 5308 5309 // Set application objects path explicitly. 5310 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5311 pkg.applicationInfo.setCodePath(pkg.codePath); 5312 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5313 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5314 pkg.applicationInfo.setResourcePath(resourcePath); 5315 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5316 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5317 5318 // Note that we invoke the following method only if we are about to unpack an application 5319 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5320 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5321 5322 /* 5323 * If the system app should be overridden by a previously installed 5324 * data, hide the system app now and let the /data/app scan pick it up 5325 * again. 5326 */ 5327 if (shouldHideSystemApp) { 5328 synchronized (mPackages) { 5329 /* 5330 * We have to grant systems permissions before we hide, because 5331 * grantPermissions will assume the package update is trying to 5332 * expand its permissions. 5333 */ 5334 grantPermissionsLPw(pkg, true, pkg.packageName); 5335 mSettings.disableSystemPackageLPw(pkg.packageName); 5336 } 5337 } 5338 5339 return scannedPkg; 5340 } 5341 5342 private static String fixProcessName(String defProcessName, 5343 String processName, int uid) { 5344 if (processName == null) { 5345 return defProcessName; 5346 } 5347 return processName; 5348 } 5349 5350 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5351 throws PackageManagerException { 5352 if (pkgSetting.signatures.mSignatures != null) { 5353 // Already existing package. Make sure signatures match 5354 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5355 == PackageManager.SIGNATURE_MATCH; 5356 if (!match) { 5357 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5358 == PackageManager.SIGNATURE_MATCH; 5359 } 5360 if (!match) { 5361 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5362 == PackageManager.SIGNATURE_MATCH; 5363 } 5364 if (!match) { 5365 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5366 + pkg.packageName + " signatures do not match the " 5367 + "previously installed version; ignoring!"); 5368 } 5369 } 5370 5371 // Check for shared user signatures 5372 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5373 // Already existing package. Make sure signatures match 5374 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5375 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5376 if (!match) { 5377 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5378 == PackageManager.SIGNATURE_MATCH; 5379 } 5380 if (!match) { 5381 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5382 == PackageManager.SIGNATURE_MATCH; 5383 } 5384 if (!match) { 5385 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5386 "Package " + pkg.packageName 5387 + " has no signatures that match those in shared user " 5388 + pkgSetting.sharedUser.name + "; ignoring!"); 5389 } 5390 } 5391 } 5392 5393 /** 5394 * Enforces that only the system UID or root's UID can call a method exposed 5395 * via Binder. 5396 * 5397 * @param message used as message if SecurityException is thrown 5398 * @throws SecurityException if the caller is not system or root 5399 */ 5400 private static final void enforceSystemOrRoot(String message) { 5401 final int uid = Binder.getCallingUid(); 5402 if (uid != Process.SYSTEM_UID && uid != 0) { 5403 throw new SecurityException(message); 5404 } 5405 } 5406 5407 @Override 5408 public void performBootDexOpt() { 5409 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5410 5411 // Before everything else, see whether we need to fstrim. 5412 try { 5413 IMountService ms = PackageHelper.getMountService(); 5414 if (ms != null) { 5415 final boolean isUpgrade = isUpgrade(); 5416 boolean doTrim = isUpgrade; 5417 if (doTrim) { 5418 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5419 } else { 5420 final long interval = android.provider.Settings.Global.getLong( 5421 mContext.getContentResolver(), 5422 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5423 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5424 if (interval > 0) { 5425 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5426 if (timeSinceLast > interval) { 5427 doTrim = true; 5428 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5429 + "; running immediately"); 5430 } 5431 } 5432 } 5433 if (doTrim) { 5434 if (!isFirstBoot()) { 5435 try { 5436 ActivityManagerNative.getDefault().showBootMessage( 5437 mContext.getResources().getString( 5438 R.string.android_upgrading_fstrim), true); 5439 } catch (RemoteException e) { 5440 } 5441 } 5442 ms.runMaintenance(); 5443 } 5444 } else { 5445 Slog.e(TAG, "Mount service unavailable!"); 5446 } 5447 } catch (RemoteException e) { 5448 // Can't happen; MountService is local 5449 } 5450 5451 final ArraySet<PackageParser.Package> pkgs; 5452 synchronized (mPackages) { 5453 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5454 } 5455 5456 if (pkgs != null) { 5457 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5458 // in case the device runs out of space. 5459 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5460 // Give priority to core apps. 5461 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5462 PackageParser.Package pkg = it.next(); 5463 if (pkg.coreApp) { 5464 if (DEBUG_DEXOPT) { 5465 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5466 } 5467 sortedPkgs.add(pkg); 5468 it.remove(); 5469 } 5470 } 5471 // Give priority to system apps that listen for pre boot complete. 5472 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5473 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5474 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5475 PackageParser.Package pkg = it.next(); 5476 if (pkgNames.contains(pkg.packageName)) { 5477 if (DEBUG_DEXOPT) { 5478 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5479 } 5480 sortedPkgs.add(pkg); 5481 it.remove(); 5482 } 5483 } 5484 // Give priority to system apps. 5485 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5486 PackageParser.Package pkg = it.next(); 5487 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5488 if (DEBUG_DEXOPT) { 5489 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5490 } 5491 sortedPkgs.add(pkg); 5492 it.remove(); 5493 } 5494 } 5495 // Give priority to updated system apps. 5496 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5497 PackageParser.Package pkg = it.next(); 5498 if (pkg.isUpdatedSystemApp()) { 5499 if (DEBUG_DEXOPT) { 5500 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5501 } 5502 sortedPkgs.add(pkg); 5503 it.remove(); 5504 } 5505 } 5506 // Give priority to apps that listen for boot complete. 5507 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5508 pkgNames = getPackageNamesForIntent(intent); 5509 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5510 PackageParser.Package pkg = it.next(); 5511 if (pkgNames.contains(pkg.packageName)) { 5512 if (DEBUG_DEXOPT) { 5513 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5514 } 5515 sortedPkgs.add(pkg); 5516 it.remove(); 5517 } 5518 } 5519 // Filter out packages that aren't recently used. 5520 filterRecentlyUsedApps(pkgs); 5521 // Add all remaining apps. 5522 for (PackageParser.Package pkg : pkgs) { 5523 if (DEBUG_DEXOPT) { 5524 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5525 } 5526 sortedPkgs.add(pkg); 5527 } 5528 5529 // If we want to be lazy, filter everything that wasn't recently used. 5530 if (mLazyDexOpt) { 5531 filterRecentlyUsedApps(sortedPkgs); 5532 } 5533 5534 int i = 0; 5535 int total = sortedPkgs.size(); 5536 File dataDir = Environment.getDataDirectory(); 5537 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5538 if (lowThreshold == 0) { 5539 throw new IllegalStateException("Invalid low memory threshold"); 5540 } 5541 for (PackageParser.Package pkg : sortedPkgs) { 5542 long usableSpace = dataDir.getUsableSpace(); 5543 if (usableSpace < lowThreshold) { 5544 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5545 break; 5546 } 5547 performBootDexOpt(pkg, ++i, total); 5548 } 5549 } 5550 } 5551 5552 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5553 // Filter out packages that aren't recently used. 5554 // 5555 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5556 // should do a full dexopt. 5557 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5558 int total = pkgs.size(); 5559 int skipped = 0; 5560 long now = System.currentTimeMillis(); 5561 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5562 PackageParser.Package pkg = i.next(); 5563 long then = pkg.mLastPackageUsageTimeInMills; 5564 if (then + mDexOptLRUThresholdInMills < now) { 5565 if (DEBUG_DEXOPT) { 5566 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5567 ((then == 0) ? "never" : new Date(then))); 5568 } 5569 i.remove(); 5570 skipped++; 5571 } 5572 } 5573 if (DEBUG_DEXOPT) { 5574 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5575 } 5576 } 5577 } 5578 5579 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5580 List<ResolveInfo> ris = null; 5581 try { 5582 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5583 intent, null, 0, UserHandle.USER_OWNER); 5584 } catch (RemoteException e) { 5585 } 5586 ArraySet<String> pkgNames = new ArraySet<String>(); 5587 if (ris != null) { 5588 for (ResolveInfo ri : ris) { 5589 pkgNames.add(ri.activityInfo.packageName); 5590 } 5591 } 5592 return pkgNames; 5593 } 5594 5595 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5596 if (DEBUG_DEXOPT) { 5597 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5598 } 5599 if (!isFirstBoot()) { 5600 try { 5601 ActivityManagerNative.getDefault().showBootMessage( 5602 mContext.getResources().getString(R.string.android_upgrading_apk, 5603 curr, total), true); 5604 } catch (RemoteException e) { 5605 } 5606 } 5607 PackageParser.Package p = pkg; 5608 synchronized (mInstallLock) { 5609 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5610 false /* force dex */, false /* defer */, true /* include dependencies */); 5611 } 5612 } 5613 5614 @Override 5615 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5616 return performDexOpt(packageName, instructionSet, false); 5617 } 5618 5619 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5620 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5621 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5622 if (!dexopt && !updateUsage) { 5623 // We aren't going to dexopt or update usage, so bail early. 5624 return false; 5625 } 5626 PackageParser.Package p; 5627 final String targetInstructionSet; 5628 synchronized (mPackages) { 5629 p = mPackages.get(packageName); 5630 if (p == null) { 5631 return false; 5632 } 5633 if (updateUsage) { 5634 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5635 } 5636 mPackageUsage.write(false); 5637 if (!dexopt) { 5638 // We aren't going to dexopt, so bail early. 5639 return false; 5640 } 5641 5642 targetInstructionSet = instructionSet != null ? instructionSet : 5643 getPrimaryInstructionSet(p.applicationInfo); 5644 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5645 return false; 5646 } 5647 } 5648 5649 synchronized (mInstallLock) { 5650 final String[] instructionSets = new String[] { targetInstructionSet }; 5651 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5652 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5653 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5654 } 5655 } 5656 5657 public ArraySet<String> getPackagesThatNeedDexOpt() { 5658 ArraySet<String> pkgs = null; 5659 synchronized (mPackages) { 5660 for (PackageParser.Package p : mPackages.values()) { 5661 if (DEBUG_DEXOPT) { 5662 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5663 } 5664 if (!p.mDexOptPerformed.isEmpty()) { 5665 continue; 5666 } 5667 if (pkgs == null) { 5668 pkgs = new ArraySet<String>(); 5669 } 5670 pkgs.add(p.packageName); 5671 } 5672 } 5673 return pkgs; 5674 } 5675 5676 public void shutdown() { 5677 mPackageUsage.write(true); 5678 } 5679 5680 @Override 5681 public void forceDexOpt(String packageName) { 5682 enforceSystemOrRoot("forceDexOpt"); 5683 5684 PackageParser.Package pkg; 5685 synchronized (mPackages) { 5686 pkg = mPackages.get(packageName); 5687 if (pkg == null) { 5688 throw new IllegalArgumentException("Missing package: " + packageName); 5689 } 5690 } 5691 5692 synchronized (mInstallLock) { 5693 final String[] instructionSets = new String[] { 5694 getPrimaryInstructionSet(pkg.applicationInfo) }; 5695 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5696 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5697 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5698 throw new IllegalStateException("Failed to dexopt: " + res); 5699 } 5700 } 5701 } 5702 5703 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5704 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5705 Slog.w(TAG, "Unable to update from " + oldPkg.name 5706 + " to " + newPkg.packageName 5707 + ": old package not in system partition"); 5708 return false; 5709 } else if (mPackages.get(oldPkg.name) != null) { 5710 Slog.w(TAG, "Unable to update from " + oldPkg.name 5711 + " to " + newPkg.packageName 5712 + ": old package still exists"); 5713 return false; 5714 } 5715 return true; 5716 } 5717 5718 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5719 int[] users = sUserManager.getUserIds(); 5720 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5721 if (res < 0) { 5722 return res; 5723 } 5724 for (int user : users) { 5725 if (user != 0) { 5726 res = mInstaller.createUserData(volumeUuid, packageName, 5727 UserHandle.getUid(user, uid), user, seinfo); 5728 if (res < 0) { 5729 return res; 5730 } 5731 } 5732 } 5733 return res; 5734 } 5735 5736 private int removeDataDirsLI(String volumeUuid, String packageName) { 5737 int[] users = sUserManager.getUserIds(); 5738 int res = 0; 5739 for (int user : users) { 5740 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5741 if (resInner < 0) { 5742 res = resInner; 5743 } 5744 } 5745 5746 return res; 5747 } 5748 5749 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5750 int[] users = sUserManager.getUserIds(); 5751 int res = 0; 5752 for (int user : users) { 5753 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5754 if (resInner < 0) { 5755 res = resInner; 5756 } 5757 } 5758 return res; 5759 } 5760 5761 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5762 PackageParser.Package changingLib) { 5763 if (file.path != null) { 5764 usesLibraryFiles.add(file.path); 5765 return; 5766 } 5767 PackageParser.Package p = mPackages.get(file.apk); 5768 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5769 // If we are doing this while in the middle of updating a library apk, 5770 // then we need to make sure to use that new apk for determining the 5771 // dependencies here. (We haven't yet finished committing the new apk 5772 // to the package manager state.) 5773 if (p == null || p.packageName.equals(changingLib.packageName)) { 5774 p = changingLib; 5775 } 5776 } 5777 if (p != null) { 5778 usesLibraryFiles.addAll(p.getAllCodePaths()); 5779 } 5780 } 5781 5782 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5783 PackageParser.Package changingLib) throws PackageManagerException { 5784 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5785 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5786 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5787 for (int i=0; i<N; i++) { 5788 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5789 if (file == null) { 5790 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5791 "Package " + pkg.packageName + " requires unavailable shared library " 5792 + pkg.usesLibraries.get(i) + "; failing!"); 5793 } 5794 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5795 } 5796 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5797 for (int i=0; i<N; i++) { 5798 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5799 if (file == null) { 5800 Slog.w(TAG, "Package " + pkg.packageName 5801 + " desires unavailable shared library " 5802 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5803 } else { 5804 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5805 } 5806 } 5807 N = usesLibraryFiles.size(); 5808 if (N > 0) { 5809 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5810 } else { 5811 pkg.usesLibraryFiles = null; 5812 } 5813 } 5814 } 5815 5816 private static boolean hasString(List<String> list, List<String> which) { 5817 if (list == null) { 5818 return false; 5819 } 5820 for (int i=list.size()-1; i>=0; i--) { 5821 for (int j=which.size()-1; j>=0; j--) { 5822 if (which.get(j).equals(list.get(i))) { 5823 return true; 5824 } 5825 } 5826 } 5827 return false; 5828 } 5829 5830 private void updateAllSharedLibrariesLPw() { 5831 for (PackageParser.Package pkg : mPackages.values()) { 5832 try { 5833 updateSharedLibrariesLPw(pkg, null); 5834 } catch (PackageManagerException e) { 5835 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5836 } 5837 } 5838 } 5839 5840 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5841 PackageParser.Package changingPkg) { 5842 ArrayList<PackageParser.Package> res = null; 5843 for (PackageParser.Package pkg : mPackages.values()) { 5844 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5845 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5846 if (res == null) { 5847 res = new ArrayList<PackageParser.Package>(); 5848 } 5849 res.add(pkg); 5850 try { 5851 updateSharedLibrariesLPw(pkg, changingPkg); 5852 } catch (PackageManagerException e) { 5853 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5854 } 5855 } 5856 } 5857 return res; 5858 } 5859 5860 /** 5861 * Derive the value of the {@code cpuAbiOverride} based on the provided 5862 * value and an optional stored value from the package settings. 5863 */ 5864 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5865 String cpuAbiOverride = null; 5866 5867 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5868 cpuAbiOverride = null; 5869 } else if (abiOverride != null) { 5870 cpuAbiOverride = abiOverride; 5871 } else if (settings != null) { 5872 cpuAbiOverride = settings.cpuAbiOverrideString; 5873 } 5874 5875 return cpuAbiOverride; 5876 } 5877 5878 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5879 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5880 boolean success = false; 5881 try { 5882 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5883 currentTime, user); 5884 success = true; 5885 return res; 5886 } finally { 5887 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5888 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5889 } 5890 } 5891 } 5892 5893 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5894 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5895 final File scanFile = new File(pkg.codePath); 5896 if (pkg.applicationInfo.getCodePath() == null || 5897 pkg.applicationInfo.getResourcePath() == null) { 5898 // Bail out. The resource and code paths haven't been set. 5899 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5900 "Code and resource paths haven't been set correctly"); 5901 } 5902 5903 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5904 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5905 } else { 5906 // Only allow system apps to be flagged as core apps. 5907 pkg.coreApp = false; 5908 } 5909 5910 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5911 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5912 } 5913 5914 if (mCustomResolverComponentName != null && 5915 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5916 setUpCustomResolverActivity(pkg); 5917 } 5918 5919 if (pkg.packageName.equals("android")) { 5920 synchronized (mPackages) { 5921 if (mAndroidApplication != null) { 5922 Slog.w(TAG, "*************************************************"); 5923 Slog.w(TAG, "Core android package being redefined. Skipping."); 5924 Slog.w(TAG, " file=" + scanFile); 5925 Slog.w(TAG, "*************************************************"); 5926 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5927 "Core android package being redefined. Skipping."); 5928 } 5929 5930 // Set up information for our fall-back user intent resolution activity. 5931 mPlatformPackage = pkg; 5932 pkg.mVersionCode = mSdkVersion; 5933 mAndroidApplication = pkg.applicationInfo; 5934 5935 if (!mResolverReplaced) { 5936 mResolveActivity.applicationInfo = mAndroidApplication; 5937 mResolveActivity.name = ResolverActivity.class.getName(); 5938 mResolveActivity.packageName = mAndroidApplication.packageName; 5939 mResolveActivity.processName = "system:ui"; 5940 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5941 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5942 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5943 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5944 mResolveActivity.exported = true; 5945 mResolveActivity.enabled = true; 5946 mResolveInfo.activityInfo = mResolveActivity; 5947 mResolveInfo.priority = 0; 5948 mResolveInfo.preferredOrder = 0; 5949 mResolveInfo.match = 0; 5950 mResolveComponentName = new ComponentName( 5951 mAndroidApplication.packageName, mResolveActivity.name); 5952 } 5953 } 5954 } 5955 5956 if (DEBUG_PACKAGE_SCANNING) { 5957 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5958 Log.d(TAG, "Scanning package " + pkg.packageName); 5959 } 5960 5961 if (mPackages.containsKey(pkg.packageName) 5962 || mSharedLibraries.containsKey(pkg.packageName)) { 5963 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5964 "Application package " + pkg.packageName 5965 + " already installed. Skipping duplicate."); 5966 } 5967 5968 // If we're only installing presumed-existing packages, require that the 5969 // scanned APK is both already known and at the path previously established 5970 // for it. Previously unknown packages we pick up normally, but if we have an 5971 // a priori expectation about this package's install presence, enforce it. 5972 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5973 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5974 if (known != null) { 5975 if (DEBUG_PACKAGE_SCANNING) { 5976 Log.d(TAG, "Examining " + pkg.codePath 5977 + " and requiring known paths " + known.codePathString 5978 + " & " + known.resourcePathString); 5979 } 5980 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5981 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5982 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5983 "Application package " + pkg.packageName 5984 + " found at " + pkg.applicationInfo.getCodePath() 5985 + " but expected at " + known.codePathString + "; ignoring."); 5986 } 5987 } 5988 } 5989 5990 // Initialize package source and resource directories 5991 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5992 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5993 5994 SharedUserSetting suid = null; 5995 PackageSetting pkgSetting = null; 5996 5997 if (!isSystemApp(pkg)) { 5998 // Only system apps can use these features. 5999 pkg.mOriginalPackages = null; 6000 pkg.mRealPackage = null; 6001 pkg.mAdoptPermissions = null; 6002 } 6003 6004 // writer 6005 synchronized (mPackages) { 6006 if (pkg.mSharedUserId != null) { 6007 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6008 if (suid == null) { 6009 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6010 "Creating application package " + pkg.packageName 6011 + " for shared user failed"); 6012 } 6013 if (DEBUG_PACKAGE_SCANNING) { 6014 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6015 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6016 + "): packages=" + suid.packages); 6017 } 6018 } 6019 6020 // Check if we are renaming from an original package name. 6021 PackageSetting origPackage = null; 6022 String realName = null; 6023 if (pkg.mOriginalPackages != null) { 6024 // This package may need to be renamed to a previously 6025 // installed name. Let's check on that... 6026 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6027 if (pkg.mOriginalPackages.contains(renamed)) { 6028 // This package had originally been installed as the 6029 // original name, and we have already taken care of 6030 // transitioning to the new one. Just update the new 6031 // one to continue using the old name. 6032 realName = pkg.mRealPackage; 6033 if (!pkg.packageName.equals(renamed)) { 6034 // Callers into this function may have already taken 6035 // care of renaming the package; only do it here if 6036 // it is not already done. 6037 pkg.setPackageName(renamed); 6038 } 6039 6040 } else { 6041 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6042 if ((origPackage = mSettings.peekPackageLPr( 6043 pkg.mOriginalPackages.get(i))) != null) { 6044 // We do have the package already installed under its 6045 // original name... should we use it? 6046 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6047 // New package is not compatible with original. 6048 origPackage = null; 6049 continue; 6050 } else if (origPackage.sharedUser != null) { 6051 // Make sure uid is compatible between packages. 6052 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6053 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6054 + " to " + pkg.packageName + ": old uid " 6055 + origPackage.sharedUser.name 6056 + " differs from " + pkg.mSharedUserId); 6057 origPackage = null; 6058 continue; 6059 } 6060 } else { 6061 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6062 + pkg.packageName + " to old name " + origPackage.name); 6063 } 6064 break; 6065 } 6066 } 6067 } 6068 } 6069 6070 if (mTransferedPackages.contains(pkg.packageName)) { 6071 Slog.w(TAG, "Package " + pkg.packageName 6072 + " was transferred to another, but its .apk remains"); 6073 } 6074 6075 // Just create the setting, don't add it yet. For already existing packages 6076 // the PkgSetting exists already and doesn't have to be created. 6077 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6078 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6079 pkg.applicationInfo.primaryCpuAbi, 6080 pkg.applicationInfo.secondaryCpuAbi, 6081 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6082 user, false); 6083 if (pkgSetting == null) { 6084 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6085 "Creating application package " + pkg.packageName + " failed"); 6086 } 6087 6088 if (pkgSetting.origPackage != null) { 6089 // If we are first transitioning from an original package, 6090 // fix up the new package's name now. We need to do this after 6091 // looking up the package under its new name, so getPackageLP 6092 // can take care of fiddling things correctly. 6093 pkg.setPackageName(origPackage.name); 6094 6095 // File a report about this. 6096 String msg = "New package " + pkgSetting.realName 6097 + " renamed to replace old package " + pkgSetting.name; 6098 reportSettingsProblem(Log.WARN, msg); 6099 6100 // Make a note of it. 6101 mTransferedPackages.add(origPackage.name); 6102 6103 // No longer need to retain this. 6104 pkgSetting.origPackage = null; 6105 } 6106 6107 if (realName != null) { 6108 // Make a note of it. 6109 mTransferedPackages.add(pkg.packageName); 6110 } 6111 6112 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6113 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6114 } 6115 6116 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6117 // Check all shared libraries and map to their actual file path. 6118 // We only do this here for apps not on a system dir, because those 6119 // are the only ones that can fail an install due to this. We 6120 // will take care of the system apps by updating all of their 6121 // library paths after the scan is done. 6122 updateSharedLibrariesLPw(pkg, null); 6123 } 6124 6125 if (mFoundPolicyFile) { 6126 SELinuxMMAC.assignSeinfoValue(pkg); 6127 } 6128 6129 pkg.applicationInfo.uid = pkgSetting.appId; 6130 pkg.mExtras = pkgSetting; 6131 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 6132 try { 6133 verifySignaturesLP(pkgSetting, pkg); 6134 // We just determined the app is signed correctly, so bring 6135 // over the latest parsed certs. 6136 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6137 } catch (PackageManagerException e) { 6138 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6139 throw e; 6140 } 6141 // The signature has changed, but this package is in the system 6142 // image... let's recover! 6143 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6144 // However... if this package is part of a shared user, but it 6145 // doesn't match the signature of the shared user, let's fail. 6146 // What this means is that you can't change the signatures 6147 // associated with an overall shared user, which doesn't seem all 6148 // that unreasonable. 6149 if (pkgSetting.sharedUser != null) { 6150 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6151 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6152 throw new PackageManagerException( 6153 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6154 "Signature mismatch for shared user : " 6155 + pkgSetting.sharedUser); 6156 } 6157 } 6158 // File a report about this. 6159 String msg = "System package " + pkg.packageName 6160 + " signature changed; retaining data."; 6161 reportSettingsProblem(Log.WARN, msg); 6162 } 6163 } else { 6164 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6165 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6166 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6167 "Package " + pkg.packageName + " upgrade keys do not match the " 6168 + "previously installed version"); 6169 } else { 6170 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6171 String msg = "System package " + pkg.packageName 6172 + " signature changed; retaining data."; 6173 reportSettingsProblem(Log.WARN, msg); 6174 } 6175 } else { 6176 // We just determined the app is signed correctly, so bring 6177 // over the latest parsed certs. 6178 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6179 } 6180 } 6181 // Verify that this new package doesn't have any content providers 6182 // that conflict with existing packages. Only do this if the 6183 // package isn't already installed, since we don't want to break 6184 // things that are installed. 6185 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6186 final int N = pkg.providers.size(); 6187 int i; 6188 for (i=0; i<N; i++) { 6189 PackageParser.Provider p = pkg.providers.get(i); 6190 if (p.info.authority != null) { 6191 String names[] = p.info.authority.split(";"); 6192 for (int j = 0; j < names.length; j++) { 6193 if (mProvidersByAuthority.containsKey(names[j])) { 6194 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6195 final String otherPackageName = 6196 ((other != null && other.getComponentName() != null) ? 6197 other.getComponentName().getPackageName() : "?"); 6198 throw new PackageManagerException( 6199 INSTALL_FAILED_CONFLICTING_PROVIDER, 6200 "Can't install because provider name " + names[j] 6201 + " (in package " + pkg.applicationInfo.packageName 6202 + ") is already used by " + otherPackageName); 6203 } 6204 } 6205 } 6206 } 6207 } 6208 6209 if (pkg.mAdoptPermissions != null) { 6210 // This package wants to adopt ownership of permissions from 6211 // another package. 6212 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6213 final String origName = pkg.mAdoptPermissions.get(i); 6214 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6215 if (orig != null) { 6216 if (verifyPackageUpdateLPr(orig, pkg)) { 6217 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6218 + pkg.packageName); 6219 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6220 } 6221 } 6222 } 6223 } 6224 } 6225 6226 final String pkgName = pkg.packageName; 6227 6228 final long scanFileTime = scanFile.lastModified(); 6229 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6230 pkg.applicationInfo.processName = fixProcessName( 6231 pkg.applicationInfo.packageName, 6232 pkg.applicationInfo.processName, 6233 pkg.applicationInfo.uid); 6234 6235 File dataPath; 6236 if (mPlatformPackage == pkg) { 6237 // The system package is special. 6238 dataPath = new File(Environment.getDataDirectory(), "system"); 6239 6240 pkg.applicationInfo.dataDir = dataPath.getPath(); 6241 6242 } else { 6243 // This is a normal package, need to make its data directory. 6244 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6245 UserHandle.USER_OWNER); 6246 6247 boolean uidError = false; 6248 if (dataPath.exists()) { 6249 int currentUid = 0; 6250 try { 6251 StructStat stat = Os.stat(dataPath.getPath()); 6252 currentUid = stat.st_uid; 6253 } catch (ErrnoException e) { 6254 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6255 } 6256 6257 // If we have mismatched owners for the data path, we have a problem. 6258 if (currentUid != pkg.applicationInfo.uid) { 6259 boolean recovered = false; 6260 if (currentUid == 0) { 6261 // The directory somehow became owned by root. Wow. 6262 // This is probably because the system was stopped while 6263 // installd was in the middle of messing with its libs 6264 // directory. Ask installd to fix that. 6265 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6266 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6267 if (ret >= 0) { 6268 recovered = true; 6269 String msg = "Package " + pkg.packageName 6270 + " unexpectedly changed to uid 0; recovered to " + 6271 + pkg.applicationInfo.uid; 6272 reportSettingsProblem(Log.WARN, msg); 6273 } 6274 } 6275 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6276 || (scanFlags&SCAN_BOOTING) != 0)) { 6277 // If this is a system app, we can at least delete its 6278 // current data so the application will still work. 6279 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6280 if (ret >= 0) { 6281 // TODO: Kill the processes first 6282 // Old data gone! 6283 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6284 ? "System package " : "Third party package "; 6285 String msg = prefix + pkg.packageName 6286 + " has changed from uid: " 6287 + currentUid + " to " 6288 + pkg.applicationInfo.uid + "; old data erased"; 6289 reportSettingsProblem(Log.WARN, msg); 6290 recovered = true; 6291 6292 // And now re-install the app. 6293 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6294 pkg.applicationInfo.seinfo); 6295 if (ret == -1) { 6296 // Ack should not happen! 6297 msg = prefix + pkg.packageName 6298 + " could not have data directory re-created after delete."; 6299 reportSettingsProblem(Log.WARN, msg); 6300 throw new PackageManagerException( 6301 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6302 } 6303 } 6304 if (!recovered) { 6305 mHasSystemUidErrors = true; 6306 } 6307 } else if (!recovered) { 6308 // If we allow this install to proceed, we will be broken. 6309 // Abort, abort! 6310 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6311 "scanPackageLI"); 6312 } 6313 if (!recovered) { 6314 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6315 + pkg.applicationInfo.uid + "/fs_" 6316 + currentUid; 6317 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6318 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6319 String msg = "Package " + pkg.packageName 6320 + " has mismatched uid: " 6321 + currentUid + " on disk, " 6322 + pkg.applicationInfo.uid + " in settings"; 6323 // writer 6324 synchronized (mPackages) { 6325 mSettings.mReadMessages.append(msg); 6326 mSettings.mReadMessages.append('\n'); 6327 uidError = true; 6328 if (!pkgSetting.uidError) { 6329 reportSettingsProblem(Log.ERROR, msg); 6330 } 6331 } 6332 } 6333 } 6334 pkg.applicationInfo.dataDir = dataPath.getPath(); 6335 if (mShouldRestoreconData) { 6336 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6337 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6338 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6339 } 6340 } else { 6341 if (DEBUG_PACKAGE_SCANNING) { 6342 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6343 Log.v(TAG, "Want this data dir: " + dataPath); 6344 } 6345 //invoke installer to do the actual installation 6346 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6347 pkg.applicationInfo.seinfo); 6348 if (ret < 0) { 6349 // Error from installer 6350 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6351 "Unable to create data dirs [errorCode=" + ret + "]"); 6352 } 6353 6354 if (dataPath.exists()) { 6355 pkg.applicationInfo.dataDir = dataPath.getPath(); 6356 } else { 6357 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6358 pkg.applicationInfo.dataDir = null; 6359 } 6360 } 6361 6362 pkgSetting.uidError = uidError; 6363 } 6364 6365 final String path = scanFile.getPath(); 6366 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6367 6368 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6369 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6370 6371 // Some system apps still use directory structure for native libraries 6372 // in which case we might end up not detecting abi solely based on apk 6373 // structure. Try to detect abi based on directory structure. 6374 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6375 pkg.applicationInfo.primaryCpuAbi == null) { 6376 setBundledAppAbisAndRoots(pkg, pkgSetting); 6377 setNativeLibraryPaths(pkg); 6378 } 6379 6380 } else { 6381 if ((scanFlags & SCAN_MOVE) != 0) { 6382 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6383 // but we already have this packages package info in the PackageSetting. We just 6384 // use that and derive the native library path based on the new codepath. 6385 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6386 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6387 } 6388 6389 // Set native library paths again. For moves, the path will be updated based on the 6390 // ABIs we've determined above. For non-moves, the path will be updated based on the 6391 // ABIs we determined during compilation, but the path will depend on the final 6392 // package path (after the rename away from the stage path). 6393 setNativeLibraryPaths(pkg); 6394 } 6395 6396 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6397 final int[] userIds = sUserManager.getUserIds(); 6398 synchronized (mInstallLock) { 6399 // Create a native library symlink only if we have native libraries 6400 // and if the native libraries are 32 bit libraries. We do not provide 6401 // this symlink for 64 bit libraries. 6402 if (pkg.applicationInfo.primaryCpuAbi != null && 6403 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6404 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6405 for (int userId : userIds) { 6406 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6407 nativeLibPath, userId) < 0) { 6408 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6409 "Failed linking native library dir (user=" + userId + ")"); 6410 } 6411 } 6412 } 6413 } 6414 6415 // This is a special case for the "system" package, where the ABI is 6416 // dictated by the zygote configuration (and init.rc). We should keep track 6417 // of this ABI so that we can deal with "normal" applications that run under 6418 // the same UID correctly. 6419 if (mPlatformPackage == pkg) { 6420 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6421 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6422 } 6423 6424 // If there's a mismatch between the abi-override in the package setting 6425 // and the abiOverride specified for the install. Warn about this because we 6426 // would've already compiled the app without taking the package setting into 6427 // account. 6428 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6429 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6430 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6431 " for package: " + pkg.packageName); 6432 } 6433 } 6434 6435 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6436 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6437 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6438 6439 // Copy the derived override back to the parsed package, so that we can 6440 // update the package settings accordingly. 6441 pkg.cpuAbiOverride = cpuAbiOverride; 6442 6443 if (DEBUG_ABI_SELECTION) { 6444 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6445 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6446 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6447 } 6448 6449 // Push the derived path down into PackageSettings so we know what to 6450 // clean up at uninstall time. 6451 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6452 6453 if (DEBUG_ABI_SELECTION) { 6454 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6455 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6456 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6457 } 6458 6459 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6460 // We don't do this here during boot because we can do it all 6461 // at once after scanning all existing packages. 6462 // 6463 // We also do this *before* we perform dexopt on this package, so that 6464 // we can avoid redundant dexopts, and also to make sure we've got the 6465 // code and package path correct. 6466 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6467 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6468 } 6469 6470 if ((scanFlags & SCAN_NO_DEX) == 0) { 6471 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6472 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6473 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6474 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6475 } 6476 } 6477 if (mFactoryTest && pkg.requestedPermissions.contains( 6478 android.Manifest.permission.FACTORY_TEST)) { 6479 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6480 } 6481 6482 ArrayList<PackageParser.Package> clientLibPkgs = null; 6483 6484 // writer 6485 synchronized (mPackages) { 6486 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6487 // Only system apps can add new shared libraries. 6488 if (pkg.libraryNames != null) { 6489 for (int i=0; i<pkg.libraryNames.size(); i++) { 6490 String name = pkg.libraryNames.get(i); 6491 boolean allowed = false; 6492 if (pkg.isUpdatedSystemApp()) { 6493 // New library entries can only be added through the 6494 // system image. This is important to get rid of a lot 6495 // of nasty edge cases: for example if we allowed a non- 6496 // system update of the app to add a library, then uninstalling 6497 // the update would make the library go away, and assumptions 6498 // we made such as through app install filtering would now 6499 // have allowed apps on the device which aren't compatible 6500 // with it. Better to just have the restriction here, be 6501 // conservative, and create many fewer cases that can negatively 6502 // impact the user experience. 6503 final PackageSetting sysPs = mSettings 6504 .getDisabledSystemPkgLPr(pkg.packageName); 6505 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6506 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6507 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6508 allowed = true; 6509 allowed = true; 6510 break; 6511 } 6512 } 6513 } 6514 } else { 6515 allowed = true; 6516 } 6517 if (allowed) { 6518 if (!mSharedLibraries.containsKey(name)) { 6519 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6520 } else if (!name.equals(pkg.packageName)) { 6521 Slog.w(TAG, "Package " + pkg.packageName + " library " 6522 + name + " already exists; skipping"); 6523 } 6524 } else { 6525 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6526 + name + " that is not declared on system image; skipping"); 6527 } 6528 } 6529 if ((scanFlags&SCAN_BOOTING) == 0) { 6530 // If we are not booting, we need to update any applications 6531 // that are clients of our shared library. If we are booting, 6532 // this will all be done once the scan is complete. 6533 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6534 } 6535 } 6536 } 6537 } 6538 6539 // We also need to dexopt any apps that are dependent on this library. Note that 6540 // if these fail, we should abort the install since installing the library will 6541 // result in some apps being broken. 6542 if (clientLibPkgs != null) { 6543 if ((scanFlags & SCAN_NO_DEX) == 0) { 6544 for (int i = 0; i < clientLibPkgs.size(); i++) { 6545 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6546 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6547 null /* instruction sets */, forceDex, 6548 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6549 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6550 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6551 "scanPackageLI failed to dexopt clientLibPkgs"); 6552 } 6553 } 6554 } 6555 } 6556 6557 // Also need to kill any apps that are dependent on the library. 6558 if (clientLibPkgs != null) { 6559 for (int i=0; i<clientLibPkgs.size(); i++) { 6560 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6561 killApplication(clientPkg.applicationInfo.packageName, 6562 clientPkg.applicationInfo.uid, "update lib"); 6563 } 6564 } 6565 6566 // writer 6567 synchronized (mPackages) { 6568 // We don't expect installation to fail beyond this point 6569 6570 // Add the new setting to mSettings 6571 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6572 // Add the new setting to mPackages 6573 mPackages.put(pkg.applicationInfo.packageName, pkg); 6574 // Make sure we don't accidentally delete its data. 6575 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6576 while (iter.hasNext()) { 6577 PackageCleanItem item = iter.next(); 6578 if (pkgName.equals(item.packageName)) { 6579 iter.remove(); 6580 } 6581 } 6582 6583 // Take care of first install / last update times. 6584 if (currentTime != 0) { 6585 if (pkgSetting.firstInstallTime == 0) { 6586 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6587 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6588 pkgSetting.lastUpdateTime = currentTime; 6589 } 6590 } else if (pkgSetting.firstInstallTime == 0) { 6591 // We need *something*. Take time time stamp of the file. 6592 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6593 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6594 if (scanFileTime != pkgSetting.timeStamp) { 6595 // A package on the system image has changed; consider this 6596 // to be an update. 6597 pkgSetting.lastUpdateTime = scanFileTime; 6598 } 6599 } 6600 6601 // Add the package's KeySets to the global KeySetManagerService 6602 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6603 try { 6604 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6605 if (pkg.mKeySetMapping != null) { 6606 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6607 if (pkg.mUpgradeKeySets != null) { 6608 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6609 } 6610 } 6611 } catch (NullPointerException e) { 6612 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6613 } catch (IllegalArgumentException e) { 6614 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6615 } 6616 6617 int N = pkg.providers.size(); 6618 StringBuilder r = null; 6619 int i; 6620 for (i=0; i<N; i++) { 6621 PackageParser.Provider p = pkg.providers.get(i); 6622 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6623 p.info.processName, pkg.applicationInfo.uid); 6624 mProviders.addProvider(p); 6625 p.syncable = p.info.isSyncable; 6626 if (p.info.authority != null) { 6627 String names[] = p.info.authority.split(";"); 6628 p.info.authority = null; 6629 for (int j = 0; j < names.length; j++) { 6630 if (j == 1 && p.syncable) { 6631 // We only want the first authority for a provider to possibly be 6632 // syncable, so if we already added this provider using a different 6633 // authority clear the syncable flag. We copy the provider before 6634 // changing it because the mProviders object contains a reference 6635 // to a provider that we don't want to change. 6636 // Only do this for the second authority since the resulting provider 6637 // object can be the same for all future authorities for this provider. 6638 p = new PackageParser.Provider(p); 6639 p.syncable = false; 6640 } 6641 if (!mProvidersByAuthority.containsKey(names[j])) { 6642 mProvidersByAuthority.put(names[j], p); 6643 if (p.info.authority == null) { 6644 p.info.authority = names[j]; 6645 } else { 6646 p.info.authority = p.info.authority + ";" + names[j]; 6647 } 6648 if (DEBUG_PACKAGE_SCANNING) { 6649 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6650 Log.d(TAG, "Registered content provider: " + names[j] 6651 + ", className = " + p.info.name + ", isSyncable = " 6652 + p.info.isSyncable); 6653 } 6654 } else { 6655 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6656 Slog.w(TAG, "Skipping provider name " + names[j] + 6657 " (in package " + pkg.applicationInfo.packageName + 6658 "): name already used by " 6659 + ((other != null && other.getComponentName() != null) 6660 ? other.getComponentName().getPackageName() : "?")); 6661 } 6662 } 6663 } 6664 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6665 if (r == null) { 6666 r = new StringBuilder(256); 6667 } else { 6668 r.append(' '); 6669 } 6670 r.append(p.info.name); 6671 } 6672 } 6673 if (r != null) { 6674 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6675 } 6676 6677 N = pkg.services.size(); 6678 r = null; 6679 for (i=0; i<N; i++) { 6680 PackageParser.Service s = pkg.services.get(i); 6681 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6682 s.info.processName, pkg.applicationInfo.uid); 6683 mServices.addService(s); 6684 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6685 if (r == null) { 6686 r = new StringBuilder(256); 6687 } else { 6688 r.append(' '); 6689 } 6690 r.append(s.info.name); 6691 } 6692 } 6693 if (r != null) { 6694 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6695 } 6696 6697 N = pkg.receivers.size(); 6698 r = null; 6699 for (i=0; i<N; i++) { 6700 PackageParser.Activity a = pkg.receivers.get(i); 6701 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6702 a.info.processName, pkg.applicationInfo.uid); 6703 mReceivers.addActivity(a, "receiver"); 6704 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6705 if (r == null) { 6706 r = new StringBuilder(256); 6707 } else { 6708 r.append(' '); 6709 } 6710 r.append(a.info.name); 6711 } 6712 } 6713 if (r != null) { 6714 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6715 } 6716 6717 N = pkg.activities.size(); 6718 r = null; 6719 for (i=0; i<N; i++) { 6720 PackageParser.Activity a = pkg.activities.get(i); 6721 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6722 a.info.processName, pkg.applicationInfo.uid); 6723 mActivities.addActivity(a, "activity"); 6724 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6725 if (r == null) { 6726 r = new StringBuilder(256); 6727 } else { 6728 r.append(' '); 6729 } 6730 r.append(a.info.name); 6731 } 6732 } 6733 if (r != null) { 6734 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6735 } 6736 6737 N = pkg.permissionGroups.size(); 6738 r = null; 6739 for (i=0; i<N; i++) { 6740 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6741 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6742 if (cur == null) { 6743 mPermissionGroups.put(pg.info.name, pg); 6744 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6745 if (r == null) { 6746 r = new StringBuilder(256); 6747 } else { 6748 r.append(' '); 6749 } 6750 r.append(pg.info.name); 6751 } 6752 } else { 6753 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6754 + pg.info.packageName + " ignored: original from " 6755 + cur.info.packageName); 6756 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6757 if (r == null) { 6758 r = new StringBuilder(256); 6759 } else { 6760 r.append(' '); 6761 } 6762 r.append("DUP:"); 6763 r.append(pg.info.name); 6764 } 6765 } 6766 } 6767 if (r != null) { 6768 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6769 } 6770 6771 N = pkg.permissions.size(); 6772 r = null; 6773 for (i=0; i<N; i++) { 6774 PackageParser.Permission p = pkg.permissions.get(i); 6775 6776 // Now that permission groups have a special meaning, we ignore permission 6777 // groups for legacy apps to prevent unexpected behavior. In particular, 6778 // permissions for one app being granted to someone just becuase they happen 6779 // to be in a group defined by another app (before this had no implications). 6780 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6781 p.group = mPermissionGroups.get(p.info.group); 6782 // Warn for a permission in an unknown group. 6783 if (p.info.group != null && p.group == null) { 6784 Slog.w(TAG, "Permission " + p.info.name + " from package " 6785 + p.info.packageName + " in an unknown group " + p.info.group); 6786 } 6787 } 6788 6789 ArrayMap<String, BasePermission> permissionMap = 6790 p.tree ? mSettings.mPermissionTrees 6791 : mSettings.mPermissions; 6792 BasePermission bp = permissionMap.get(p.info.name); 6793 6794 // Allow system apps to redefine non-system permissions 6795 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6796 final boolean currentOwnerIsSystem = (bp.perm != null 6797 && isSystemApp(bp.perm.owner)); 6798 if (isSystemApp(p.owner)) { 6799 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6800 // It's a built-in permission and no owner, take ownership now 6801 bp.packageSetting = pkgSetting; 6802 bp.perm = p; 6803 bp.uid = pkg.applicationInfo.uid; 6804 bp.sourcePackage = p.info.packageName; 6805 } else if (!currentOwnerIsSystem) { 6806 String msg = "New decl " + p.owner + " of permission " 6807 + p.info.name + " is system; overriding " + bp.sourcePackage; 6808 reportSettingsProblem(Log.WARN, msg); 6809 bp = null; 6810 } 6811 } 6812 } 6813 6814 if (bp == null) { 6815 bp = new BasePermission(p.info.name, p.info.packageName, 6816 BasePermission.TYPE_NORMAL); 6817 permissionMap.put(p.info.name, bp); 6818 } 6819 6820 if (bp.perm == null) { 6821 if (bp.sourcePackage == null 6822 || bp.sourcePackage.equals(p.info.packageName)) { 6823 BasePermission tree = findPermissionTreeLP(p.info.name); 6824 if (tree == null 6825 || tree.sourcePackage.equals(p.info.packageName)) { 6826 bp.packageSetting = pkgSetting; 6827 bp.perm = p; 6828 bp.uid = pkg.applicationInfo.uid; 6829 bp.sourcePackage = p.info.packageName; 6830 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6831 if (r == null) { 6832 r = new StringBuilder(256); 6833 } else { 6834 r.append(' '); 6835 } 6836 r.append(p.info.name); 6837 } 6838 } else { 6839 Slog.w(TAG, "Permission " + p.info.name + " from package " 6840 + p.info.packageName + " ignored: base tree " 6841 + tree.name + " is from package " 6842 + tree.sourcePackage); 6843 } 6844 } else { 6845 Slog.w(TAG, "Permission " + p.info.name + " from package " 6846 + p.info.packageName + " ignored: original from " 6847 + bp.sourcePackage); 6848 } 6849 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6850 if (r == null) { 6851 r = new StringBuilder(256); 6852 } else { 6853 r.append(' '); 6854 } 6855 r.append("DUP:"); 6856 r.append(p.info.name); 6857 } 6858 if (bp.perm == p) { 6859 bp.protectionLevel = p.info.protectionLevel; 6860 } 6861 } 6862 6863 if (r != null) { 6864 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6865 } 6866 6867 N = pkg.instrumentation.size(); 6868 r = null; 6869 for (i=0; i<N; i++) { 6870 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6871 a.info.packageName = pkg.applicationInfo.packageName; 6872 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6873 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6874 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6875 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6876 a.info.dataDir = pkg.applicationInfo.dataDir; 6877 6878 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6879 // need other information about the application, like the ABI and what not ? 6880 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6881 mInstrumentation.put(a.getComponentName(), a); 6882 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6883 if (r == null) { 6884 r = new StringBuilder(256); 6885 } else { 6886 r.append(' '); 6887 } 6888 r.append(a.info.name); 6889 } 6890 } 6891 if (r != null) { 6892 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6893 } 6894 6895 if (pkg.protectedBroadcasts != null) { 6896 N = pkg.protectedBroadcasts.size(); 6897 for (i=0; i<N; i++) { 6898 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6899 } 6900 } 6901 6902 pkgSetting.setTimeStamp(scanFileTime); 6903 6904 // Create idmap files for pairs of (packages, overlay packages). 6905 // Note: "android", ie framework-res.apk, is handled by native layers. 6906 if (pkg.mOverlayTarget != null) { 6907 // This is an overlay package. 6908 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6909 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6910 mOverlays.put(pkg.mOverlayTarget, 6911 new ArrayMap<String, PackageParser.Package>()); 6912 } 6913 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6914 map.put(pkg.packageName, pkg); 6915 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6916 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6917 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6918 "scanPackageLI failed to createIdmap"); 6919 } 6920 } 6921 } else if (mOverlays.containsKey(pkg.packageName) && 6922 !pkg.packageName.equals("android")) { 6923 // This is a regular package, with one or more known overlay packages. 6924 createIdmapsForPackageLI(pkg); 6925 } 6926 } 6927 6928 return pkg; 6929 } 6930 6931 /** 6932 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6933 * is derived purely on the basis of the contents of {@code scanFile} and 6934 * {@code cpuAbiOverride}. 6935 * 6936 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6937 */ 6938 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6939 String cpuAbiOverride, boolean extractLibs) 6940 throws PackageManagerException { 6941 // TODO: We can probably be smarter about this stuff. For installed apps, 6942 // we can calculate this information at install time once and for all. For 6943 // system apps, we can probably assume that this information doesn't change 6944 // after the first boot scan. As things stand, we do lots of unnecessary work. 6945 6946 // Give ourselves some initial paths; we'll come back for another 6947 // pass once we've determined ABI below. 6948 setNativeLibraryPaths(pkg); 6949 6950 // We would never need to extract libs for forward-locked and external packages, 6951 // since the container service will do it for us. We shouldn't attempt to 6952 // extract libs from system app when it was not updated. 6953 if (pkg.isForwardLocked() || isExternal(pkg) || 6954 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 6955 extractLibs = false; 6956 } 6957 6958 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6959 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6960 6961 NativeLibraryHelper.Handle handle = null; 6962 try { 6963 handle = NativeLibraryHelper.Handle.create(scanFile); 6964 // TODO(multiArch): This can be null for apps that didn't go through the 6965 // usual installation process. We can calculate it again, like we 6966 // do during install time. 6967 // 6968 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6969 // unnecessary. 6970 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6971 6972 // Null out the abis so that they can be recalculated. 6973 pkg.applicationInfo.primaryCpuAbi = null; 6974 pkg.applicationInfo.secondaryCpuAbi = null; 6975 if (isMultiArch(pkg.applicationInfo)) { 6976 // Warn if we've set an abiOverride for multi-lib packages.. 6977 // By definition, we need to copy both 32 and 64 bit libraries for 6978 // such packages. 6979 if (pkg.cpuAbiOverride != null 6980 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6981 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6982 } 6983 6984 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6985 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6986 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6987 if (extractLibs) { 6988 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6989 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6990 useIsaSpecificSubdirs); 6991 } else { 6992 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6993 } 6994 } 6995 6996 maybeThrowExceptionForMultiArchCopy( 6997 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6998 6999 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7000 if (extractLibs) { 7001 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7002 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7003 useIsaSpecificSubdirs); 7004 } else { 7005 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7006 } 7007 } 7008 7009 maybeThrowExceptionForMultiArchCopy( 7010 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7011 7012 if (abi64 >= 0) { 7013 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7014 } 7015 7016 if (abi32 >= 0) { 7017 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7018 if (abi64 >= 0) { 7019 pkg.applicationInfo.secondaryCpuAbi = abi; 7020 } else { 7021 pkg.applicationInfo.primaryCpuAbi = abi; 7022 } 7023 } 7024 } else { 7025 String[] abiList = (cpuAbiOverride != null) ? 7026 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7027 7028 // Enable gross and lame hacks for apps that are built with old 7029 // SDK tools. We must scan their APKs for renderscript bitcode and 7030 // not launch them if it's present. Don't bother checking on devices 7031 // that don't have 64 bit support. 7032 boolean needsRenderScriptOverride = false; 7033 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7034 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7035 abiList = Build.SUPPORTED_32_BIT_ABIS; 7036 needsRenderScriptOverride = true; 7037 } 7038 7039 final int copyRet; 7040 if (extractLibs) { 7041 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7042 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7043 } else { 7044 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7045 } 7046 7047 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7048 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7049 "Error unpackaging native libs for app, errorCode=" + copyRet); 7050 } 7051 7052 if (copyRet >= 0) { 7053 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7054 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7055 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7056 } else if (needsRenderScriptOverride) { 7057 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7058 } 7059 } 7060 } catch (IOException ioe) { 7061 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7062 } finally { 7063 IoUtils.closeQuietly(handle); 7064 } 7065 7066 // Now that we've calculated the ABIs and determined if it's an internal app, 7067 // we will go ahead and populate the nativeLibraryPath. 7068 setNativeLibraryPaths(pkg); 7069 } 7070 7071 /** 7072 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7073 * i.e, so that all packages can be run inside a single process if required. 7074 * 7075 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7076 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7077 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7078 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7079 * updating a package that belongs to a shared user. 7080 * 7081 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7082 * adds unnecessary complexity. 7083 */ 7084 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7085 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7086 String requiredInstructionSet = null; 7087 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7088 requiredInstructionSet = VMRuntime.getInstructionSet( 7089 scannedPackage.applicationInfo.primaryCpuAbi); 7090 } 7091 7092 PackageSetting requirer = null; 7093 for (PackageSetting ps : packagesForUser) { 7094 // If packagesForUser contains scannedPackage, we skip it. This will happen 7095 // when scannedPackage is an update of an existing package. Without this check, 7096 // we will never be able to change the ABI of any package belonging to a shared 7097 // user, even if it's compatible with other packages. 7098 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7099 if (ps.primaryCpuAbiString == null) { 7100 continue; 7101 } 7102 7103 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7104 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7105 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7106 // this but there's not much we can do. 7107 String errorMessage = "Instruction set mismatch, " 7108 + ((requirer == null) ? "[caller]" : requirer) 7109 + " requires " + requiredInstructionSet + " whereas " + ps 7110 + " requires " + instructionSet; 7111 Slog.w(TAG, errorMessage); 7112 } 7113 7114 if (requiredInstructionSet == null) { 7115 requiredInstructionSet = instructionSet; 7116 requirer = ps; 7117 } 7118 } 7119 } 7120 7121 if (requiredInstructionSet != null) { 7122 String adjustedAbi; 7123 if (requirer != null) { 7124 // requirer != null implies that either scannedPackage was null or that scannedPackage 7125 // did not require an ABI, in which case we have to adjust scannedPackage to match 7126 // the ABI of the set (which is the same as requirer's ABI) 7127 adjustedAbi = requirer.primaryCpuAbiString; 7128 if (scannedPackage != null) { 7129 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7130 } 7131 } else { 7132 // requirer == null implies that we're updating all ABIs in the set to 7133 // match scannedPackage. 7134 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7135 } 7136 7137 for (PackageSetting ps : packagesForUser) { 7138 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7139 if (ps.primaryCpuAbiString != null) { 7140 continue; 7141 } 7142 7143 ps.primaryCpuAbiString = adjustedAbi; 7144 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7145 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7146 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7147 7148 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7149 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7150 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7151 ps.primaryCpuAbiString = null; 7152 ps.pkg.applicationInfo.primaryCpuAbi = null; 7153 return; 7154 } else { 7155 mInstaller.rmdex(ps.codePathString, 7156 getDexCodeInstructionSet(getPreferredInstructionSet())); 7157 } 7158 } 7159 } 7160 } 7161 } 7162 } 7163 7164 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7165 synchronized (mPackages) { 7166 mResolverReplaced = true; 7167 // Set up information for custom user intent resolution activity. 7168 mResolveActivity.applicationInfo = pkg.applicationInfo; 7169 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7170 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7171 mResolveActivity.processName = pkg.applicationInfo.packageName; 7172 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7173 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7174 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7175 mResolveActivity.theme = 0; 7176 mResolveActivity.exported = true; 7177 mResolveActivity.enabled = true; 7178 mResolveInfo.activityInfo = mResolveActivity; 7179 mResolveInfo.priority = 0; 7180 mResolveInfo.preferredOrder = 0; 7181 mResolveInfo.match = 0; 7182 mResolveComponentName = mCustomResolverComponentName; 7183 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7184 mResolveComponentName); 7185 } 7186 } 7187 7188 private static String calculateBundledApkRoot(final String codePathString) { 7189 final File codePath = new File(codePathString); 7190 final File codeRoot; 7191 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7192 codeRoot = Environment.getRootDirectory(); 7193 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7194 codeRoot = Environment.getOemDirectory(); 7195 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7196 codeRoot = Environment.getVendorDirectory(); 7197 } else { 7198 // Unrecognized code path; take its top real segment as the apk root: 7199 // e.g. /something/app/blah.apk => /something 7200 try { 7201 File f = codePath.getCanonicalFile(); 7202 File parent = f.getParentFile(); // non-null because codePath is a file 7203 File tmp; 7204 while ((tmp = parent.getParentFile()) != null) { 7205 f = parent; 7206 parent = tmp; 7207 } 7208 codeRoot = f; 7209 Slog.w(TAG, "Unrecognized code path " 7210 + codePath + " - using " + codeRoot); 7211 } catch (IOException e) { 7212 // Can't canonicalize the code path -- shenanigans? 7213 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7214 return Environment.getRootDirectory().getPath(); 7215 } 7216 } 7217 return codeRoot.getPath(); 7218 } 7219 7220 /** 7221 * Derive and set the location of native libraries for the given package, 7222 * which varies depending on where and how the package was installed. 7223 */ 7224 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7225 final ApplicationInfo info = pkg.applicationInfo; 7226 final String codePath = pkg.codePath; 7227 final File codeFile = new File(codePath); 7228 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7229 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7230 7231 info.nativeLibraryRootDir = null; 7232 info.nativeLibraryRootRequiresIsa = false; 7233 info.nativeLibraryDir = null; 7234 info.secondaryNativeLibraryDir = null; 7235 7236 if (isApkFile(codeFile)) { 7237 // Monolithic install 7238 if (bundledApp) { 7239 // If "/system/lib64/apkname" exists, assume that is the per-package 7240 // native library directory to use; otherwise use "/system/lib/apkname". 7241 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7242 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7243 getPrimaryInstructionSet(info)); 7244 7245 // This is a bundled system app so choose the path based on the ABI. 7246 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7247 // is just the default path. 7248 final String apkName = deriveCodePathName(codePath); 7249 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7250 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7251 apkName).getAbsolutePath(); 7252 7253 if (info.secondaryCpuAbi != null) { 7254 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7255 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7256 secondaryLibDir, apkName).getAbsolutePath(); 7257 } 7258 } else if (asecApp) { 7259 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7260 .getAbsolutePath(); 7261 } else { 7262 final String apkName = deriveCodePathName(codePath); 7263 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7264 .getAbsolutePath(); 7265 } 7266 7267 info.nativeLibraryRootRequiresIsa = false; 7268 info.nativeLibraryDir = info.nativeLibraryRootDir; 7269 } else { 7270 // Cluster install 7271 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7272 info.nativeLibraryRootRequiresIsa = true; 7273 7274 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7275 getPrimaryInstructionSet(info)).getAbsolutePath(); 7276 7277 if (info.secondaryCpuAbi != null) { 7278 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7279 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7280 } 7281 } 7282 } 7283 7284 /** 7285 * Calculate the abis and roots for a bundled app. These can uniquely 7286 * be determined from the contents of the system partition, i.e whether 7287 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7288 * of this information, and instead assume that the system was built 7289 * sensibly. 7290 */ 7291 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7292 PackageSetting pkgSetting) { 7293 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7294 7295 // If "/system/lib64/apkname" exists, assume that is the per-package 7296 // native library directory to use; otherwise use "/system/lib/apkname". 7297 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7298 setBundledAppAbi(pkg, apkRoot, apkName); 7299 // pkgSetting might be null during rescan following uninstall of updates 7300 // to a bundled app, so accommodate that possibility. The settings in 7301 // that case will be established later from the parsed package. 7302 // 7303 // If the settings aren't null, sync them up with what we've just derived. 7304 // note that apkRoot isn't stored in the package settings. 7305 if (pkgSetting != null) { 7306 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7307 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7308 } 7309 } 7310 7311 /** 7312 * Deduces the ABI of a bundled app and sets the relevant fields on the 7313 * parsed pkg object. 7314 * 7315 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7316 * under which system libraries are installed. 7317 * @param apkName the name of the installed package. 7318 */ 7319 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7320 final File codeFile = new File(pkg.codePath); 7321 7322 final boolean has64BitLibs; 7323 final boolean has32BitLibs; 7324 if (isApkFile(codeFile)) { 7325 // Monolithic install 7326 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7327 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7328 } else { 7329 // Cluster install 7330 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7331 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7332 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7333 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7334 has64BitLibs = (new File(rootDir, isa)).exists(); 7335 } else { 7336 has64BitLibs = false; 7337 } 7338 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7339 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7340 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7341 has32BitLibs = (new File(rootDir, isa)).exists(); 7342 } else { 7343 has32BitLibs = false; 7344 } 7345 } 7346 7347 if (has64BitLibs && !has32BitLibs) { 7348 // The package has 64 bit libs, but not 32 bit libs. Its primary 7349 // ABI should be 64 bit. We can safely assume here that the bundled 7350 // native libraries correspond to the most preferred ABI in the list. 7351 7352 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7353 pkg.applicationInfo.secondaryCpuAbi = null; 7354 } else if (has32BitLibs && !has64BitLibs) { 7355 // The package has 32 bit libs but not 64 bit libs. Its primary 7356 // ABI should be 32 bit. 7357 7358 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7359 pkg.applicationInfo.secondaryCpuAbi = null; 7360 } else if (has32BitLibs && has64BitLibs) { 7361 // The application has both 64 and 32 bit bundled libraries. We check 7362 // here that the app declares multiArch support, and warn if it doesn't. 7363 // 7364 // We will be lenient here and record both ABIs. The primary will be the 7365 // ABI that's higher on the list, i.e, a device that's configured to prefer 7366 // 64 bit apps will see a 64 bit primary ABI, 7367 7368 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7369 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7370 } 7371 7372 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7373 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7374 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7375 } else { 7376 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7377 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7378 } 7379 } else { 7380 pkg.applicationInfo.primaryCpuAbi = null; 7381 pkg.applicationInfo.secondaryCpuAbi = null; 7382 } 7383 } 7384 7385 private void killApplication(String pkgName, int appId, String reason) { 7386 // Request the ActivityManager to kill the process(only for existing packages) 7387 // so that we do not end up in a confused state while the user is still using the older 7388 // version of the application while the new one gets installed. 7389 IActivityManager am = ActivityManagerNative.getDefault(); 7390 if (am != null) { 7391 try { 7392 am.killApplicationWithAppId(pkgName, appId, reason); 7393 } catch (RemoteException e) { 7394 } 7395 } 7396 } 7397 7398 void removePackageLI(PackageSetting ps, boolean chatty) { 7399 if (DEBUG_INSTALL) { 7400 if (chatty) 7401 Log.d(TAG, "Removing package " + ps.name); 7402 } 7403 7404 // writer 7405 synchronized (mPackages) { 7406 mPackages.remove(ps.name); 7407 final PackageParser.Package pkg = ps.pkg; 7408 if (pkg != null) { 7409 cleanPackageDataStructuresLILPw(pkg, chatty); 7410 } 7411 } 7412 } 7413 7414 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7415 if (DEBUG_INSTALL) { 7416 if (chatty) 7417 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7418 } 7419 7420 // writer 7421 synchronized (mPackages) { 7422 mPackages.remove(pkg.applicationInfo.packageName); 7423 cleanPackageDataStructuresLILPw(pkg, chatty); 7424 } 7425 } 7426 7427 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7428 int N = pkg.providers.size(); 7429 StringBuilder r = null; 7430 int i; 7431 for (i=0; i<N; i++) { 7432 PackageParser.Provider p = pkg.providers.get(i); 7433 mProviders.removeProvider(p); 7434 if (p.info.authority == null) { 7435 7436 /* There was another ContentProvider with this authority when 7437 * this app was installed so this authority is null, 7438 * Ignore it as we don't have to unregister the provider. 7439 */ 7440 continue; 7441 } 7442 String names[] = p.info.authority.split(";"); 7443 for (int j = 0; j < names.length; j++) { 7444 if (mProvidersByAuthority.get(names[j]) == p) { 7445 mProvidersByAuthority.remove(names[j]); 7446 if (DEBUG_REMOVE) { 7447 if (chatty) 7448 Log.d(TAG, "Unregistered content provider: " + names[j] 7449 + ", className = " + p.info.name + ", isSyncable = " 7450 + p.info.isSyncable); 7451 } 7452 } 7453 } 7454 if (DEBUG_REMOVE && chatty) { 7455 if (r == null) { 7456 r = new StringBuilder(256); 7457 } else { 7458 r.append(' '); 7459 } 7460 r.append(p.info.name); 7461 } 7462 } 7463 if (r != null) { 7464 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7465 } 7466 7467 N = pkg.services.size(); 7468 r = null; 7469 for (i=0; i<N; i++) { 7470 PackageParser.Service s = pkg.services.get(i); 7471 mServices.removeService(s); 7472 if (chatty) { 7473 if (r == null) { 7474 r = new StringBuilder(256); 7475 } else { 7476 r.append(' '); 7477 } 7478 r.append(s.info.name); 7479 } 7480 } 7481 if (r != null) { 7482 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7483 } 7484 7485 N = pkg.receivers.size(); 7486 r = null; 7487 for (i=0; i<N; i++) { 7488 PackageParser.Activity a = pkg.receivers.get(i); 7489 mReceivers.removeActivity(a, "receiver"); 7490 if (DEBUG_REMOVE && chatty) { 7491 if (r == null) { 7492 r = new StringBuilder(256); 7493 } else { 7494 r.append(' '); 7495 } 7496 r.append(a.info.name); 7497 } 7498 } 7499 if (r != null) { 7500 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7501 } 7502 7503 N = pkg.activities.size(); 7504 r = null; 7505 for (i=0; i<N; i++) { 7506 PackageParser.Activity a = pkg.activities.get(i); 7507 mActivities.removeActivity(a, "activity"); 7508 if (DEBUG_REMOVE && chatty) { 7509 if (r == null) { 7510 r = new StringBuilder(256); 7511 } else { 7512 r.append(' '); 7513 } 7514 r.append(a.info.name); 7515 } 7516 } 7517 if (r != null) { 7518 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7519 } 7520 7521 N = pkg.permissions.size(); 7522 r = null; 7523 for (i=0; i<N; i++) { 7524 PackageParser.Permission p = pkg.permissions.get(i); 7525 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7526 if (bp == null) { 7527 bp = mSettings.mPermissionTrees.get(p.info.name); 7528 } 7529 if (bp != null && bp.perm == p) { 7530 bp.perm = null; 7531 if (DEBUG_REMOVE && chatty) { 7532 if (r == null) { 7533 r = new StringBuilder(256); 7534 } else { 7535 r.append(' '); 7536 } 7537 r.append(p.info.name); 7538 } 7539 } 7540 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7541 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7542 if (appOpPerms != null) { 7543 appOpPerms.remove(pkg.packageName); 7544 } 7545 } 7546 } 7547 if (r != null) { 7548 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7549 } 7550 7551 N = pkg.requestedPermissions.size(); 7552 r = null; 7553 for (i=0; i<N; i++) { 7554 String perm = pkg.requestedPermissions.get(i); 7555 BasePermission bp = mSettings.mPermissions.get(perm); 7556 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7557 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7558 if (appOpPerms != null) { 7559 appOpPerms.remove(pkg.packageName); 7560 if (appOpPerms.isEmpty()) { 7561 mAppOpPermissionPackages.remove(perm); 7562 } 7563 } 7564 } 7565 } 7566 if (r != null) { 7567 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7568 } 7569 7570 N = pkg.instrumentation.size(); 7571 r = null; 7572 for (i=0; i<N; i++) { 7573 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7574 mInstrumentation.remove(a.getComponentName()); 7575 if (DEBUG_REMOVE && chatty) { 7576 if (r == null) { 7577 r = new StringBuilder(256); 7578 } else { 7579 r.append(' '); 7580 } 7581 r.append(a.info.name); 7582 } 7583 } 7584 if (r != null) { 7585 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7586 } 7587 7588 r = null; 7589 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7590 // Only system apps can hold shared libraries. 7591 if (pkg.libraryNames != null) { 7592 for (i=0; i<pkg.libraryNames.size(); i++) { 7593 String name = pkg.libraryNames.get(i); 7594 SharedLibraryEntry cur = mSharedLibraries.get(name); 7595 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7596 mSharedLibraries.remove(name); 7597 if (DEBUG_REMOVE && chatty) { 7598 if (r == null) { 7599 r = new StringBuilder(256); 7600 } else { 7601 r.append(' '); 7602 } 7603 r.append(name); 7604 } 7605 } 7606 } 7607 } 7608 } 7609 if (r != null) { 7610 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7611 } 7612 } 7613 7614 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7615 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7616 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7617 return true; 7618 } 7619 } 7620 return false; 7621 } 7622 7623 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7624 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7625 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7626 7627 private void updatePermissionsLPw(String changingPkg, 7628 PackageParser.Package pkgInfo, int flags) { 7629 // Make sure there are no dangling permission trees. 7630 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7631 while (it.hasNext()) { 7632 final BasePermission bp = it.next(); 7633 if (bp.packageSetting == null) { 7634 // We may not yet have parsed the package, so just see if 7635 // we still know about its settings. 7636 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7637 } 7638 if (bp.packageSetting == null) { 7639 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7640 + " from package " + bp.sourcePackage); 7641 it.remove(); 7642 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7643 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7644 Slog.i(TAG, "Removing old permission tree: " + bp.name 7645 + " from package " + bp.sourcePackage); 7646 flags |= UPDATE_PERMISSIONS_ALL; 7647 it.remove(); 7648 } 7649 } 7650 } 7651 7652 // Make sure all dynamic permissions have been assigned to a package, 7653 // and make sure there are no dangling permissions. 7654 it = mSettings.mPermissions.values().iterator(); 7655 while (it.hasNext()) { 7656 final BasePermission bp = it.next(); 7657 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7658 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7659 + bp.name + " pkg=" + bp.sourcePackage 7660 + " info=" + bp.pendingInfo); 7661 if (bp.packageSetting == null && bp.pendingInfo != null) { 7662 final BasePermission tree = findPermissionTreeLP(bp.name); 7663 if (tree != null && tree.perm != null) { 7664 bp.packageSetting = tree.packageSetting; 7665 bp.perm = new PackageParser.Permission(tree.perm.owner, 7666 new PermissionInfo(bp.pendingInfo)); 7667 bp.perm.info.packageName = tree.perm.info.packageName; 7668 bp.perm.info.name = bp.name; 7669 bp.uid = tree.uid; 7670 } 7671 } 7672 } 7673 if (bp.packageSetting == null) { 7674 // We may not yet have parsed the package, so just see if 7675 // we still know about its settings. 7676 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7677 } 7678 if (bp.packageSetting == null) { 7679 Slog.w(TAG, "Removing dangling permission: " + bp.name 7680 + " from package " + bp.sourcePackage); 7681 it.remove(); 7682 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7683 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7684 Slog.i(TAG, "Removing old permission: " + bp.name 7685 + " from package " + bp.sourcePackage); 7686 flags |= UPDATE_PERMISSIONS_ALL; 7687 it.remove(); 7688 } 7689 } 7690 } 7691 7692 // Now update the permissions for all packages, in particular 7693 // replace the granted permissions of the system packages. 7694 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7695 for (PackageParser.Package pkg : mPackages.values()) { 7696 if (pkg != pkgInfo) { 7697 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7698 changingPkg); 7699 } 7700 } 7701 } 7702 7703 if (pkgInfo != null) { 7704 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7705 } 7706 } 7707 7708 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7709 String packageOfInterest) { 7710 // IMPORTANT: There are two types of permissions: install and runtime. 7711 // Install time permissions are granted when the app is installed to 7712 // all device users and users added in the future. Runtime permissions 7713 // are granted at runtime explicitly to specific users. Normal and signature 7714 // protected permissions are install time permissions. Dangerous permissions 7715 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7716 // otherwise they are runtime permissions. This function does not manage 7717 // runtime permissions except for the case an app targeting Lollipop MR1 7718 // being upgraded to target a newer SDK, in which case dangerous permissions 7719 // are transformed from install time to runtime ones. 7720 7721 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7722 if (ps == null) { 7723 return; 7724 } 7725 7726 PermissionsState permissionsState = ps.getPermissionsState(); 7727 PermissionsState origPermissions = permissionsState; 7728 7729 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7730 7731 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7732 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7733 7734 boolean changedInstallPermission = false; 7735 7736 if (replace) { 7737 ps.installPermissionsFixed = false; 7738 if (!ps.isSharedUser()) { 7739 origPermissions = new PermissionsState(permissionsState); 7740 permissionsState.reset(); 7741 } 7742 } 7743 7744 permissionsState.setGlobalGids(mGlobalGids); 7745 7746 final int N = pkg.requestedPermissions.size(); 7747 for (int i=0; i<N; i++) { 7748 final String name = pkg.requestedPermissions.get(i); 7749 final BasePermission bp = mSettings.mPermissions.get(name); 7750 7751 if (DEBUG_INSTALL) { 7752 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7753 } 7754 7755 if (bp == null || bp.packageSetting == null) { 7756 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7757 Slog.w(TAG, "Unknown permission " + name 7758 + " in package " + pkg.packageName); 7759 } 7760 continue; 7761 } 7762 7763 final String perm = bp.name; 7764 boolean allowedSig = false; 7765 int grant = GRANT_DENIED; 7766 7767 // Keep track of app op permissions. 7768 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7769 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7770 if (pkgs == null) { 7771 pkgs = new ArraySet<>(); 7772 mAppOpPermissionPackages.put(bp.name, pkgs); 7773 } 7774 pkgs.add(pkg.packageName); 7775 } 7776 7777 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7778 switch (level) { 7779 case PermissionInfo.PROTECTION_NORMAL: { 7780 // For all apps normal permissions are install time ones. 7781 grant = GRANT_INSTALL; 7782 } break; 7783 7784 case PermissionInfo.PROTECTION_DANGEROUS: { 7785 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7786 // For legacy apps dangerous permissions are install time ones. 7787 grant = GRANT_INSTALL_LEGACY; 7788 } else if (ps.isSystem()) { 7789 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7790 if (origPermissions.hasInstallPermission(bp.name)) { 7791 // If a system app had an install permission, then the app was 7792 // upgraded and we grant the permissions as runtime to all users. 7793 grant = GRANT_UPGRADE; 7794 upgradeUserIds = currentUserIds; 7795 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7796 // If users changed since the last permissions update for a 7797 // system app, we grant the permission as runtime to the new users. 7798 grant = GRANT_UPGRADE; 7799 upgradeUserIds = currentUserIds; 7800 for (int userId : updatedUserIds) { 7801 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7802 } 7803 } else { 7804 // Otherwise, we grant the permission as runtime if the app 7805 // already had it, i.e. we preserve runtime permissions. 7806 grant = GRANT_RUNTIME; 7807 } 7808 } else if (origPermissions.hasInstallPermission(bp.name)) { 7809 // For legacy apps that became modern, install becomes runtime. 7810 grant = GRANT_UPGRADE; 7811 upgradeUserIds = currentUserIds; 7812 } else if (replace) { 7813 // For upgraded modern apps keep runtime permissions unchanged. 7814 grant = GRANT_RUNTIME; 7815 } 7816 } break; 7817 7818 case PermissionInfo.PROTECTION_SIGNATURE: { 7819 // For all apps signature permissions are install time ones. 7820 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7821 if (allowedSig) { 7822 grant = GRANT_INSTALL; 7823 } 7824 } break; 7825 } 7826 7827 if (DEBUG_INSTALL) { 7828 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7829 } 7830 7831 if (grant != GRANT_DENIED) { 7832 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7833 // If this is an existing, non-system package, then 7834 // we can't add any new permissions to it. 7835 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7836 // Except... if this is a permission that was added 7837 // to the platform (note: need to only do this when 7838 // updating the platform). 7839 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7840 grant = GRANT_DENIED; 7841 } 7842 } 7843 } 7844 7845 switch (grant) { 7846 case GRANT_INSTALL: { 7847 // Revoke this as runtime permission to handle the case of 7848 // a runtime permssion being downgraded to an install one. 7849 for (int userId : UserManagerService.getInstance().getUserIds()) { 7850 if (origPermissions.getRuntimePermissionState( 7851 bp.name, userId) != null) { 7852 // Revoke the runtime permission and clear the flags. 7853 origPermissions.revokeRuntimePermission(bp, userId); 7854 origPermissions.updatePermissionFlags(bp, userId, 7855 PackageManager.MASK_PERMISSION_FLAGS, 0); 7856 // If we revoked a permission permission, we have to write. 7857 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7858 changedRuntimePermissionUserIds, userId); 7859 } 7860 } 7861 // Grant an install permission. 7862 if (permissionsState.grantInstallPermission(bp) != 7863 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7864 changedInstallPermission = true; 7865 } 7866 } break; 7867 7868 case GRANT_INSTALL_LEGACY: { 7869 // Grant an install permission. 7870 if (permissionsState.grantInstallPermission(bp) != 7871 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7872 changedInstallPermission = true; 7873 } 7874 } break; 7875 7876 case GRANT_RUNTIME: { 7877 // Grant previously granted runtime permissions. 7878 for (int userId : UserManagerService.getInstance().getUserIds()) { 7879 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7880 PermissionState permissionState = origPermissions 7881 .getRuntimePermissionState(bp.name, userId); 7882 final int flags = permissionState.getFlags(); 7883 if (permissionsState.grantRuntimePermission(bp, userId) == 7884 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7885 // If we cannot put the permission as it was, we have to write. 7886 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7887 changedRuntimePermissionUserIds, userId); 7888 } else { 7889 // System components not only get the permissions but 7890 // they are also fixed, so nothing can change that. 7891 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7892 ? flags 7893 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7894 // Propagate the permission flags. 7895 permissionsState.updatePermissionFlags(bp, userId, 7896 newFlags, newFlags); 7897 } 7898 } 7899 } 7900 } break; 7901 7902 case GRANT_UPGRADE: { 7903 // Grant runtime permissions for a previously held install permission. 7904 PermissionState permissionState = origPermissions 7905 .getInstallPermissionState(bp.name); 7906 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7907 7908 origPermissions.revokeInstallPermission(bp); 7909 // We will be transferring the permission flags, so clear them. 7910 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7911 PackageManager.MASK_PERMISSION_FLAGS, 0); 7912 7913 // If the permission is not to be promoted to runtime we ignore it and 7914 // also its other flags as they are not applicable to install permissions. 7915 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7916 for (int userId : upgradeUserIds) { 7917 if (permissionsState.grantRuntimePermission(bp, userId) != 7918 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7919 // System components not only get the permissions but 7920 // they are also fixed so nothing can change that. 7921 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7922 ? flags 7923 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7924 // Transfer the permission flags. 7925 permissionsState.updatePermissionFlags(bp, userId, 7926 newFlags, newFlags); 7927 // If we granted the permission, we have to write. 7928 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7929 changedRuntimePermissionUserIds, userId); 7930 } 7931 } 7932 } 7933 } break; 7934 7935 default: { 7936 if (packageOfInterest == null 7937 || packageOfInterest.equals(pkg.packageName)) { 7938 Slog.w(TAG, "Not granting permission " + perm 7939 + " to package " + pkg.packageName 7940 + " because it was previously installed without"); 7941 } 7942 } break; 7943 } 7944 } else { 7945 if (permissionsState.revokeInstallPermission(bp) != 7946 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7947 // Also drop the permission flags. 7948 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7949 PackageManager.MASK_PERMISSION_FLAGS, 0); 7950 changedInstallPermission = true; 7951 Slog.i(TAG, "Un-granting permission " + perm 7952 + " from package " + pkg.packageName 7953 + " (protectionLevel=" + bp.protectionLevel 7954 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7955 + ")"); 7956 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7957 // Don't print warning for app op permissions, since it is fine for them 7958 // not to be granted, there is a UI for the user to decide. 7959 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7960 Slog.w(TAG, "Not granting permission " + perm 7961 + " to package " + pkg.packageName 7962 + " (protectionLevel=" + bp.protectionLevel 7963 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7964 + ")"); 7965 } 7966 } 7967 } 7968 } 7969 7970 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7971 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7972 // This is the first that we have heard about this package, so the 7973 // permissions we have now selected are fixed until explicitly 7974 // changed. 7975 ps.installPermissionsFixed = true; 7976 } 7977 7978 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7979 7980 // Persist the runtime permissions state for users with changes. 7981 for (int userId : changedRuntimePermissionUserIds) { 7982 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7983 } 7984 } 7985 7986 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7987 boolean allowed = false; 7988 final int NP = PackageParser.NEW_PERMISSIONS.length; 7989 for (int ip=0; ip<NP; ip++) { 7990 final PackageParser.NewPermissionInfo npi 7991 = PackageParser.NEW_PERMISSIONS[ip]; 7992 if (npi.name.equals(perm) 7993 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7994 allowed = true; 7995 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7996 + pkg.packageName); 7997 break; 7998 } 7999 } 8000 return allowed; 8001 } 8002 8003 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8004 BasePermission bp, PermissionsState origPermissions) { 8005 boolean allowed; 8006 allowed = (compareSignatures( 8007 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8008 == PackageManager.SIGNATURE_MATCH) 8009 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8010 == PackageManager.SIGNATURE_MATCH); 8011 if (!allowed && (bp.protectionLevel 8012 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8013 if (isSystemApp(pkg)) { 8014 // For updated system applications, a system permission 8015 // is granted only if it had been defined by the original application. 8016 if (pkg.isUpdatedSystemApp()) { 8017 final PackageSetting sysPs = mSettings 8018 .getDisabledSystemPkgLPr(pkg.packageName); 8019 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8020 // If the original was granted this permission, we take 8021 // that grant decision as read and propagate it to the 8022 // update. 8023 if (sysPs.isPrivileged()) { 8024 allowed = true; 8025 } 8026 } else { 8027 // The system apk may have been updated with an older 8028 // version of the one on the data partition, but which 8029 // granted a new system permission that it didn't have 8030 // before. In this case we do want to allow the app to 8031 // now get the new permission if the ancestral apk is 8032 // privileged to get it. 8033 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8034 for (int j=0; 8035 j<sysPs.pkg.requestedPermissions.size(); j++) { 8036 if (perm.equals( 8037 sysPs.pkg.requestedPermissions.get(j))) { 8038 allowed = true; 8039 break; 8040 } 8041 } 8042 } 8043 } 8044 } else { 8045 allowed = isPrivilegedApp(pkg); 8046 } 8047 } 8048 } 8049 if (!allowed && (bp.protectionLevel 8050 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8051 // For development permissions, a development permission 8052 // is granted only if it was already granted. 8053 allowed = origPermissions.hasInstallPermission(perm); 8054 } 8055 return allowed; 8056 } 8057 8058 final class ActivityIntentResolver 8059 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8060 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8061 boolean defaultOnly, int userId) { 8062 if (!sUserManager.exists(userId)) return null; 8063 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8064 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8065 } 8066 8067 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8068 int userId) { 8069 if (!sUserManager.exists(userId)) return null; 8070 mFlags = flags; 8071 return super.queryIntent(intent, resolvedType, 8072 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8073 } 8074 8075 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8076 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8077 if (!sUserManager.exists(userId)) return null; 8078 if (packageActivities == null) { 8079 return null; 8080 } 8081 mFlags = flags; 8082 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8083 final int N = packageActivities.size(); 8084 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8085 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8086 8087 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8088 for (int i = 0; i < N; ++i) { 8089 intentFilters = packageActivities.get(i).intents; 8090 if (intentFilters != null && intentFilters.size() > 0) { 8091 PackageParser.ActivityIntentInfo[] array = 8092 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8093 intentFilters.toArray(array); 8094 listCut.add(array); 8095 } 8096 } 8097 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8098 } 8099 8100 public final void addActivity(PackageParser.Activity a, String type) { 8101 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8102 mActivities.put(a.getComponentName(), a); 8103 if (DEBUG_SHOW_INFO) 8104 Log.v( 8105 TAG, " " + type + " " + 8106 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8107 if (DEBUG_SHOW_INFO) 8108 Log.v(TAG, " Class=" + a.info.name); 8109 final int NI = a.intents.size(); 8110 for (int j=0; j<NI; j++) { 8111 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8112 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8113 intent.setPriority(0); 8114 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8115 + a.className + " with priority > 0, forcing to 0"); 8116 } 8117 if (DEBUG_SHOW_INFO) { 8118 Log.v(TAG, " IntentFilter:"); 8119 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8120 } 8121 if (!intent.debugCheck()) { 8122 Log.w(TAG, "==> For Activity " + a.info.name); 8123 } 8124 addFilter(intent); 8125 } 8126 } 8127 8128 public final void removeActivity(PackageParser.Activity a, String type) { 8129 mActivities.remove(a.getComponentName()); 8130 if (DEBUG_SHOW_INFO) { 8131 Log.v(TAG, " " + type + " " 8132 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8133 : a.info.name) + ":"); 8134 Log.v(TAG, " Class=" + a.info.name); 8135 } 8136 final int NI = a.intents.size(); 8137 for (int j=0; j<NI; j++) { 8138 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8139 if (DEBUG_SHOW_INFO) { 8140 Log.v(TAG, " IntentFilter:"); 8141 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8142 } 8143 removeFilter(intent); 8144 } 8145 } 8146 8147 @Override 8148 protected boolean allowFilterResult( 8149 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8150 ActivityInfo filterAi = filter.activity.info; 8151 for (int i=dest.size()-1; i>=0; i--) { 8152 ActivityInfo destAi = dest.get(i).activityInfo; 8153 if (destAi.name == filterAi.name 8154 && destAi.packageName == filterAi.packageName) { 8155 return false; 8156 } 8157 } 8158 return true; 8159 } 8160 8161 @Override 8162 protected ActivityIntentInfo[] newArray(int size) { 8163 return new ActivityIntentInfo[size]; 8164 } 8165 8166 @Override 8167 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8168 if (!sUserManager.exists(userId)) return true; 8169 PackageParser.Package p = filter.activity.owner; 8170 if (p != null) { 8171 PackageSetting ps = (PackageSetting)p.mExtras; 8172 if (ps != null) { 8173 // System apps are never considered stopped for purposes of 8174 // filtering, because there may be no way for the user to 8175 // actually re-launch them. 8176 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8177 && ps.getStopped(userId); 8178 } 8179 } 8180 return false; 8181 } 8182 8183 @Override 8184 protected boolean isPackageForFilter(String packageName, 8185 PackageParser.ActivityIntentInfo info) { 8186 return packageName.equals(info.activity.owner.packageName); 8187 } 8188 8189 @Override 8190 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8191 int match, int userId) { 8192 if (!sUserManager.exists(userId)) return null; 8193 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8194 return null; 8195 } 8196 final PackageParser.Activity activity = info.activity; 8197 if (mSafeMode && (activity.info.applicationInfo.flags 8198 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8199 return null; 8200 } 8201 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8202 if (ps == null) { 8203 return null; 8204 } 8205 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8206 ps.readUserState(userId), userId); 8207 if (ai == null) { 8208 return null; 8209 } 8210 final ResolveInfo res = new ResolveInfo(); 8211 res.activityInfo = ai; 8212 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8213 res.filter = info; 8214 } 8215 if (info != null) { 8216 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8217 } 8218 res.priority = info.getPriority(); 8219 res.preferredOrder = activity.owner.mPreferredOrder; 8220 //System.out.println("Result: " + res.activityInfo.className + 8221 // " = " + res.priority); 8222 res.match = match; 8223 res.isDefault = info.hasDefault; 8224 res.labelRes = info.labelRes; 8225 res.nonLocalizedLabel = info.nonLocalizedLabel; 8226 if (userNeedsBadging(userId)) { 8227 res.noResourceId = true; 8228 } else { 8229 res.icon = info.icon; 8230 } 8231 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8232 return res; 8233 } 8234 8235 @Override 8236 protected void sortResults(List<ResolveInfo> results) { 8237 Collections.sort(results, mResolvePrioritySorter); 8238 } 8239 8240 @Override 8241 protected void dumpFilter(PrintWriter out, String prefix, 8242 PackageParser.ActivityIntentInfo filter) { 8243 out.print(prefix); out.print( 8244 Integer.toHexString(System.identityHashCode(filter.activity))); 8245 out.print(' '); 8246 filter.activity.printComponentShortName(out); 8247 out.print(" filter "); 8248 out.println(Integer.toHexString(System.identityHashCode(filter))); 8249 } 8250 8251 @Override 8252 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8253 return filter.activity; 8254 } 8255 8256 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8257 PackageParser.Activity activity = (PackageParser.Activity)label; 8258 out.print(prefix); out.print( 8259 Integer.toHexString(System.identityHashCode(activity))); 8260 out.print(' '); 8261 activity.printComponentShortName(out); 8262 if (count > 1) { 8263 out.print(" ("); out.print(count); out.print(" filters)"); 8264 } 8265 out.println(); 8266 } 8267 8268// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8269// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8270// final List<ResolveInfo> retList = Lists.newArrayList(); 8271// while (i.hasNext()) { 8272// final ResolveInfo resolveInfo = i.next(); 8273// if (isEnabledLP(resolveInfo.activityInfo)) { 8274// retList.add(resolveInfo); 8275// } 8276// } 8277// return retList; 8278// } 8279 8280 // Keys are String (activity class name), values are Activity. 8281 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8282 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8283 private int mFlags; 8284 } 8285 8286 private final class ServiceIntentResolver 8287 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8288 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8289 boolean defaultOnly, int userId) { 8290 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8291 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8292 } 8293 8294 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8295 int userId) { 8296 if (!sUserManager.exists(userId)) return null; 8297 mFlags = flags; 8298 return super.queryIntent(intent, resolvedType, 8299 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8300 } 8301 8302 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8303 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8304 if (!sUserManager.exists(userId)) return null; 8305 if (packageServices == null) { 8306 return null; 8307 } 8308 mFlags = flags; 8309 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8310 final int N = packageServices.size(); 8311 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8312 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8313 8314 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8315 for (int i = 0; i < N; ++i) { 8316 intentFilters = packageServices.get(i).intents; 8317 if (intentFilters != null && intentFilters.size() > 0) { 8318 PackageParser.ServiceIntentInfo[] array = 8319 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8320 intentFilters.toArray(array); 8321 listCut.add(array); 8322 } 8323 } 8324 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8325 } 8326 8327 public final void addService(PackageParser.Service s) { 8328 mServices.put(s.getComponentName(), s); 8329 if (DEBUG_SHOW_INFO) { 8330 Log.v(TAG, " " 8331 + (s.info.nonLocalizedLabel != null 8332 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8333 Log.v(TAG, " Class=" + s.info.name); 8334 } 8335 final int NI = s.intents.size(); 8336 int j; 8337 for (j=0; j<NI; j++) { 8338 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8339 if (DEBUG_SHOW_INFO) { 8340 Log.v(TAG, " IntentFilter:"); 8341 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8342 } 8343 if (!intent.debugCheck()) { 8344 Log.w(TAG, "==> For Service " + s.info.name); 8345 } 8346 addFilter(intent); 8347 } 8348 } 8349 8350 public final void removeService(PackageParser.Service s) { 8351 mServices.remove(s.getComponentName()); 8352 if (DEBUG_SHOW_INFO) { 8353 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8354 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8355 Log.v(TAG, " Class=" + s.info.name); 8356 } 8357 final int NI = s.intents.size(); 8358 int j; 8359 for (j=0; j<NI; j++) { 8360 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8361 if (DEBUG_SHOW_INFO) { 8362 Log.v(TAG, " IntentFilter:"); 8363 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8364 } 8365 removeFilter(intent); 8366 } 8367 } 8368 8369 @Override 8370 protected boolean allowFilterResult( 8371 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8372 ServiceInfo filterSi = filter.service.info; 8373 for (int i=dest.size()-1; i>=0; i--) { 8374 ServiceInfo destAi = dest.get(i).serviceInfo; 8375 if (destAi.name == filterSi.name 8376 && destAi.packageName == filterSi.packageName) { 8377 return false; 8378 } 8379 } 8380 return true; 8381 } 8382 8383 @Override 8384 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8385 return new PackageParser.ServiceIntentInfo[size]; 8386 } 8387 8388 @Override 8389 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8390 if (!sUserManager.exists(userId)) return true; 8391 PackageParser.Package p = filter.service.owner; 8392 if (p != null) { 8393 PackageSetting ps = (PackageSetting)p.mExtras; 8394 if (ps != null) { 8395 // System apps are never considered stopped for purposes of 8396 // filtering, because there may be no way for the user to 8397 // actually re-launch them. 8398 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8399 && ps.getStopped(userId); 8400 } 8401 } 8402 return false; 8403 } 8404 8405 @Override 8406 protected boolean isPackageForFilter(String packageName, 8407 PackageParser.ServiceIntentInfo info) { 8408 return packageName.equals(info.service.owner.packageName); 8409 } 8410 8411 @Override 8412 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8413 int match, int userId) { 8414 if (!sUserManager.exists(userId)) return null; 8415 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8416 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8417 return null; 8418 } 8419 final PackageParser.Service service = info.service; 8420 if (mSafeMode && (service.info.applicationInfo.flags 8421 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8422 return null; 8423 } 8424 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8425 if (ps == null) { 8426 return null; 8427 } 8428 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8429 ps.readUserState(userId), userId); 8430 if (si == null) { 8431 return null; 8432 } 8433 final ResolveInfo res = new ResolveInfo(); 8434 res.serviceInfo = si; 8435 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8436 res.filter = filter; 8437 } 8438 res.priority = info.getPriority(); 8439 res.preferredOrder = service.owner.mPreferredOrder; 8440 res.match = match; 8441 res.isDefault = info.hasDefault; 8442 res.labelRes = info.labelRes; 8443 res.nonLocalizedLabel = info.nonLocalizedLabel; 8444 res.icon = info.icon; 8445 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8446 return res; 8447 } 8448 8449 @Override 8450 protected void sortResults(List<ResolveInfo> results) { 8451 Collections.sort(results, mResolvePrioritySorter); 8452 } 8453 8454 @Override 8455 protected void dumpFilter(PrintWriter out, String prefix, 8456 PackageParser.ServiceIntentInfo filter) { 8457 out.print(prefix); out.print( 8458 Integer.toHexString(System.identityHashCode(filter.service))); 8459 out.print(' '); 8460 filter.service.printComponentShortName(out); 8461 out.print(" filter "); 8462 out.println(Integer.toHexString(System.identityHashCode(filter))); 8463 } 8464 8465 @Override 8466 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8467 return filter.service; 8468 } 8469 8470 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8471 PackageParser.Service service = (PackageParser.Service)label; 8472 out.print(prefix); out.print( 8473 Integer.toHexString(System.identityHashCode(service))); 8474 out.print(' '); 8475 service.printComponentShortName(out); 8476 if (count > 1) { 8477 out.print(" ("); out.print(count); out.print(" filters)"); 8478 } 8479 out.println(); 8480 } 8481 8482// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8483// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8484// final List<ResolveInfo> retList = Lists.newArrayList(); 8485// while (i.hasNext()) { 8486// final ResolveInfo resolveInfo = (ResolveInfo) i; 8487// if (isEnabledLP(resolveInfo.serviceInfo)) { 8488// retList.add(resolveInfo); 8489// } 8490// } 8491// return retList; 8492// } 8493 8494 // Keys are String (activity class name), values are Activity. 8495 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8496 = new ArrayMap<ComponentName, PackageParser.Service>(); 8497 private int mFlags; 8498 }; 8499 8500 private final class ProviderIntentResolver 8501 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8502 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8503 boolean defaultOnly, int userId) { 8504 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8505 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8506 } 8507 8508 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8509 int userId) { 8510 if (!sUserManager.exists(userId)) 8511 return null; 8512 mFlags = flags; 8513 return super.queryIntent(intent, resolvedType, 8514 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8515 } 8516 8517 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8518 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8519 if (!sUserManager.exists(userId)) 8520 return null; 8521 if (packageProviders == null) { 8522 return null; 8523 } 8524 mFlags = flags; 8525 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8526 final int N = packageProviders.size(); 8527 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8528 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8529 8530 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8531 for (int i = 0; i < N; ++i) { 8532 intentFilters = packageProviders.get(i).intents; 8533 if (intentFilters != null && intentFilters.size() > 0) { 8534 PackageParser.ProviderIntentInfo[] array = 8535 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8536 intentFilters.toArray(array); 8537 listCut.add(array); 8538 } 8539 } 8540 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8541 } 8542 8543 public final void addProvider(PackageParser.Provider p) { 8544 if (mProviders.containsKey(p.getComponentName())) { 8545 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8546 return; 8547 } 8548 8549 mProviders.put(p.getComponentName(), p); 8550 if (DEBUG_SHOW_INFO) { 8551 Log.v(TAG, " " 8552 + (p.info.nonLocalizedLabel != null 8553 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8554 Log.v(TAG, " Class=" + p.info.name); 8555 } 8556 final int NI = p.intents.size(); 8557 int j; 8558 for (j = 0; j < NI; j++) { 8559 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8560 if (DEBUG_SHOW_INFO) { 8561 Log.v(TAG, " IntentFilter:"); 8562 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8563 } 8564 if (!intent.debugCheck()) { 8565 Log.w(TAG, "==> For Provider " + p.info.name); 8566 } 8567 addFilter(intent); 8568 } 8569 } 8570 8571 public final void removeProvider(PackageParser.Provider p) { 8572 mProviders.remove(p.getComponentName()); 8573 if (DEBUG_SHOW_INFO) { 8574 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8575 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8576 Log.v(TAG, " Class=" + p.info.name); 8577 } 8578 final int NI = p.intents.size(); 8579 int j; 8580 for (j = 0; j < NI; j++) { 8581 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8582 if (DEBUG_SHOW_INFO) { 8583 Log.v(TAG, " IntentFilter:"); 8584 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8585 } 8586 removeFilter(intent); 8587 } 8588 } 8589 8590 @Override 8591 protected boolean allowFilterResult( 8592 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8593 ProviderInfo filterPi = filter.provider.info; 8594 for (int i = dest.size() - 1; i >= 0; i--) { 8595 ProviderInfo destPi = dest.get(i).providerInfo; 8596 if (destPi.name == filterPi.name 8597 && destPi.packageName == filterPi.packageName) { 8598 return false; 8599 } 8600 } 8601 return true; 8602 } 8603 8604 @Override 8605 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8606 return new PackageParser.ProviderIntentInfo[size]; 8607 } 8608 8609 @Override 8610 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8611 if (!sUserManager.exists(userId)) 8612 return true; 8613 PackageParser.Package p = filter.provider.owner; 8614 if (p != null) { 8615 PackageSetting ps = (PackageSetting) p.mExtras; 8616 if (ps != null) { 8617 // System apps are never considered stopped for purposes of 8618 // filtering, because there may be no way for the user to 8619 // actually re-launch them. 8620 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8621 && ps.getStopped(userId); 8622 } 8623 } 8624 return false; 8625 } 8626 8627 @Override 8628 protected boolean isPackageForFilter(String packageName, 8629 PackageParser.ProviderIntentInfo info) { 8630 return packageName.equals(info.provider.owner.packageName); 8631 } 8632 8633 @Override 8634 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8635 int match, int userId) { 8636 if (!sUserManager.exists(userId)) 8637 return null; 8638 final PackageParser.ProviderIntentInfo info = filter; 8639 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8640 return null; 8641 } 8642 final PackageParser.Provider provider = info.provider; 8643 if (mSafeMode && (provider.info.applicationInfo.flags 8644 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8645 return null; 8646 } 8647 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8648 if (ps == null) { 8649 return null; 8650 } 8651 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8652 ps.readUserState(userId), userId); 8653 if (pi == null) { 8654 return null; 8655 } 8656 final ResolveInfo res = new ResolveInfo(); 8657 res.providerInfo = pi; 8658 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8659 res.filter = filter; 8660 } 8661 res.priority = info.getPriority(); 8662 res.preferredOrder = provider.owner.mPreferredOrder; 8663 res.match = match; 8664 res.isDefault = info.hasDefault; 8665 res.labelRes = info.labelRes; 8666 res.nonLocalizedLabel = info.nonLocalizedLabel; 8667 res.icon = info.icon; 8668 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8669 return res; 8670 } 8671 8672 @Override 8673 protected void sortResults(List<ResolveInfo> results) { 8674 Collections.sort(results, mResolvePrioritySorter); 8675 } 8676 8677 @Override 8678 protected void dumpFilter(PrintWriter out, String prefix, 8679 PackageParser.ProviderIntentInfo filter) { 8680 out.print(prefix); 8681 out.print( 8682 Integer.toHexString(System.identityHashCode(filter.provider))); 8683 out.print(' '); 8684 filter.provider.printComponentShortName(out); 8685 out.print(" filter "); 8686 out.println(Integer.toHexString(System.identityHashCode(filter))); 8687 } 8688 8689 @Override 8690 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8691 return filter.provider; 8692 } 8693 8694 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8695 PackageParser.Provider provider = (PackageParser.Provider)label; 8696 out.print(prefix); out.print( 8697 Integer.toHexString(System.identityHashCode(provider))); 8698 out.print(' '); 8699 provider.printComponentShortName(out); 8700 if (count > 1) { 8701 out.print(" ("); out.print(count); out.print(" filters)"); 8702 } 8703 out.println(); 8704 } 8705 8706 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8707 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8708 private int mFlags; 8709 }; 8710 8711 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8712 new Comparator<ResolveInfo>() { 8713 public int compare(ResolveInfo r1, ResolveInfo r2) { 8714 int v1 = r1.priority; 8715 int v2 = r2.priority; 8716 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8717 if (v1 != v2) { 8718 return (v1 > v2) ? -1 : 1; 8719 } 8720 v1 = r1.preferredOrder; 8721 v2 = r2.preferredOrder; 8722 if (v1 != v2) { 8723 return (v1 > v2) ? -1 : 1; 8724 } 8725 if (r1.isDefault != r2.isDefault) { 8726 return r1.isDefault ? -1 : 1; 8727 } 8728 v1 = r1.match; 8729 v2 = r2.match; 8730 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8731 if (v1 != v2) { 8732 return (v1 > v2) ? -1 : 1; 8733 } 8734 if (r1.system != r2.system) { 8735 return r1.system ? -1 : 1; 8736 } 8737 return 0; 8738 } 8739 }; 8740 8741 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8742 new Comparator<ProviderInfo>() { 8743 public int compare(ProviderInfo p1, ProviderInfo p2) { 8744 final int v1 = p1.initOrder; 8745 final int v2 = p2.initOrder; 8746 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8747 } 8748 }; 8749 8750 final void sendPackageBroadcast(final String action, final String pkg, 8751 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8752 final int[] userIds) { 8753 mHandler.post(new Runnable() { 8754 @Override 8755 public void run() { 8756 try { 8757 final IActivityManager am = ActivityManagerNative.getDefault(); 8758 if (am == null) return; 8759 final int[] resolvedUserIds; 8760 if (userIds == null) { 8761 resolvedUserIds = am.getRunningUserIds(); 8762 } else { 8763 resolvedUserIds = userIds; 8764 } 8765 for (int id : resolvedUserIds) { 8766 final Intent intent = new Intent(action, 8767 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8768 if (extras != null) { 8769 intent.putExtras(extras); 8770 } 8771 if (targetPkg != null) { 8772 intent.setPackage(targetPkg); 8773 } 8774 // Modify the UID when posting to other users 8775 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8776 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8777 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8778 intent.putExtra(Intent.EXTRA_UID, uid); 8779 } 8780 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8781 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8782 if (DEBUG_BROADCASTS) { 8783 RuntimeException here = new RuntimeException("here"); 8784 here.fillInStackTrace(); 8785 Slog.d(TAG, "Sending to user " + id + ": " 8786 + intent.toShortString(false, true, false, false) 8787 + " " + intent.getExtras(), here); 8788 } 8789 am.broadcastIntent(null, intent, null, finishedReceiver, 8790 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8791 finishedReceiver != null, false, id); 8792 } 8793 } catch (RemoteException ex) { 8794 } 8795 } 8796 }); 8797 } 8798 8799 /** 8800 * Check if the external storage media is available. This is true if there 8801 * is a mounted external storage medium or if the external storage is 8802 * emulated. 8803 */ 8804 private boolean isExternalMediaAvailable() { 8805 return mMediaMounted || Environment.isExternalStorageEmulated(); 8806 } 8807 8808 @Override 8809 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8810 // writer 8811 synchronized (mPackages) { 8812 if (!isExternalMediaAvailable()) { 8813 // If the external storage is no longer mounted at this point, 8814 // the caller may not have been able to delete all of this 8815 // packages files and can not delete any more. Bail. 8816 return null; 8817 } 8818 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8819 if (lastPackage != null) { 8820 pkgs.remove(lastPackage); 8821 } 8822 if (pkgs.size() > 0) { 8823 return pkgs.get(0); 8824 } 8825 } 8826 return null; 8827 } 8828 8829 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8830 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8831 userId, andCode ? 1 : 0, packageName); 8832 if (mSystemReady) { 8833 msg.sendToTarget(); 8834 } else { 8835 if (mPostSystemReadyMessages == null) { 8836 mPostSystemReadyMessages = new ArrayList<>(); 8837 } 8838 mPostSystemReadyMessages.add(msg); 8839 } 8840 } 8841 8842 void startCleaningPackages() { 8843 // reader 8844 synchronized (mPackages) { 8845 if (!isExternalMediaAvailable()) { 8846 return; 8847 } 8848 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8849 return; 8850 } 8851 } 8852 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8853 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8854 IActivityManager am = ActivityManagerNative.getDefault(); 8855 if (am != null) { 8856 try { 8857 am.startService(null, intent, null, UserHandle.USER_OWNER); 8858 } catch (RemoteException e) { 8859 } 8860 } 8861 } 8862 8863 @Override 8864 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8865 int installFlags, String installerPackageName, VerificationParams verificationParams, 8866 String packageAbiOverride) { 8867 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8868 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8869 } 8870 8871 @Override 8872 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8873 int installFlags, String installerPackageName, VerificationParams verificationParams, 8874 String packageAbiOverride, int userId) { 8875 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8876 8877 final int callingUid = Binder.getCallingUid(); 8878 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8879 8880 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8881 try { 8882 if (observer != null) { 8883 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8884 } 8885 } catch (RemoteException re) { 8886 } 8887 return; 8888 } 8889 8890 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8891 installFlags |= PackageManager.INSTALL_FROM_ADB; 8892 8893 } else { 8894 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8895 // about installerPackageName. 8896 8897 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8898 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8899 } 8900 8901 UserHandle user; 8902 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8903 user = UserHandle.ALL; 8904 } else { 8905 user = new UserHandle(userId); 8906 } 8907 8908 // Only system components can circumvent runtime permissions when installing. 8909 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8910 && mContext.checkCallingOrSelfPermission(Manifest.permission 8911 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8912 throw new SecurityException("You need the " 8913 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8914 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8915 } 8916 8917 verificationParams.setInstallerUid(callingUid); 8918 8919 final File originFile = new File(originPath); 8920 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8921 8922 final Message msg = mHandler.obtainMessage(INIT_COPY); 8923 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8924 null, verificationParams, user, packageAbiOverride); 8925 mHandler.sendMessage(msg); 8926 } 8927 8928 void installStage(String packageName, File stagedDir, String stagedCid, 8929 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8930 String installerPackageName, int installerUid, UserHandle user) { 8931 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8932 params.referrerUri, installerUid, null); 8933 8934 final OriginInfo origin; 8935 if (stagedDir != null) { 8936 origin = OriginInfo.fromStagedFile(stagedDir); 8937 } else { 8938 origin = OriginInfo.fromStagedContainer(stagedCid); 8939 } 8940 8941 final Message msg = mHandler.obtainMessage(INIT_COPY); 8942 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8943 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8944 mHandler.sendMessage(msg); 8945 } 8946 8947 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8948 Bundle extras = new Bundle(1); 8949 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8950 8951 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8952 packageName, extras, null, null, new int[] {userId}); 8953 try { 8954 IActivityManager am = ActivityManagerNative.getDefault(); 8955 final boolean isSystem = 8956 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8957 if (isSystem && am.isUserRunning(userId, false)) { 8958 // The just-installed/enabled app is bundled on the system, so presumed 8959 // to be able to run automatically without needing an explicit launch. 8960 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8961 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8962 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8963 .setPackage(packageName); 8964 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8965 android.app.AppOpsManager.OP_NONE, false, false, userId); 8966 } 8967 } catch (RemoteException e) { 8968 // shouldn't happen 8969 Slog.w(TAG, "Unable to bootstrap installed package", e); 8970 } 8971 } 8972 8973 @Override 8974 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8975 int userId) { 8976 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8977 PackageSetting pkgSetting; 8978 final int uid = Binder.getCallingUid(); 8979 enforceCrossUserPermission(uid, userId, true, true, 8980 "setApplicationHiddenSetting for user " + userId); 8981 8982 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8983 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8984 return false; 8985 } 8986 8987 long callingId = Binder.clearCallingIdentity(); 8988 try { 8989 boolean sendAdded = false; 8990 boolean sendRemoved = false; 8991 // writer 8992 synchronized (mPackages) { 8993 pkgSetting = mSettings.mPackages.get(packageName); 8994 if (pkgSetting == null) { 8995 return false; 8996 } 8997 if (pkgSetting.getHidden(userId) != hidden) { 8998 pkgSetting.setHidden(hidden, userId); 8999 mSettings.writePackageRestrictionsLPr(userId); 9000 if (hidden) { 9001 sendRemoved = true; 9002 } else { 9003 sendAdded = true; 9004 } 9005 } 9006 } 9007 if (sendAdded) { 9008 sendPackageAddedForUser(packageName, pkgSetting, userId); 9009 return true; 9010 } 9011 if (sendRemoved) { 9012 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9013 "hiding pkg"); 9014 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9015 } 9016 } finally { 9017 Binder.restoreCallingIdentity(callingId); 9018 } 9019 return false; 9020 } 9021 9022 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9023 int userId) { 9024 final PackageRemovedInfo info = new PackageRemovedInfo(); 9025 info.removedPackage = packageName; 9026 info.removedUsers = new int[] {userId}; 9027 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9028 info.sendBroadcast(false, false, false); 9029 } 9030 9031 /** 9032 * Returns true if application is not found or there was an error. Otherwise it returns 9033 * the hidden state of the package for the given user. 9034 */ 9035 @Override 9036 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9037 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9038 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9039 false, "getApplicationHidden for user " + userId); 9040 PackageSetting pkgSetting; 9041 long callingId = Binder.clearCallingIdentity(); 9042 try { 9043 // writer 9044 synchronized (mPackages) { 9045 pkgSetting = mSettings.mPackages.get(packageName); 9046 if (pkgSetting == null) { 9047 return true; 9048 } 9049 return pkgSetting.getHidden(userId); 9050 } 9051 } finally { 9052 Binder.restoreCallingIdentity(callingId); 9053 } 9054 } 9055 9056 /** 9057 * @hide 9058 */ 9059 @Override 9060 public int installExistingPackageAsUser(String packageName, int userId) { 9061 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9062 null); 9063 PackageSetting pkgSetting; 9064 final int uid = Binder.getCallingUid(); 9065 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9066 + userId); 9067 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9068 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9069 } 9070 9071 long callingId = Binder.clearCallingIdentity(); 9072 try { 9073 boolean sendAdded = false; 9074 9075 // writer 9076 synchronized (mPackages) { 9077 pkgSetting = mSettings.mPackages.get(packageName); 9078 if (pkgSetting == null) { 9079 return PackageManager.INSTALL_FAILED_INVALID_URI; 9080 } 9081 if (!pkgSetting.getInstalled(userId)) { 9082 pkgSetting.setInstalled(true, userId); 9083 pkgSetting.setHidden(false, userId); 9084 mSettings.writePackageRestrictionsLPr(userId); 9085 sendAdded = true; 9086 } 9087 } 9088 9089 if (sendAdded) { 9090 sendPackageAddedForUser(packageName, pkgSetting, userId); 9091 } 9092 } finally { 9093 Binder.restoreCallingIdentity(callingId); 9094 } 9095 9096 return PackageManager.INSTALL_SUCCEEDED; 9097 } 9098 9099 boolean isUserRestricted(int userId, String restrictionKey) { 9100 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9101 if (restrictions.getBoolean(restrictionKey, false)) { 9102 Log.w(TAG, "User is restricted: " + restrictionKey); 9103 return true; 9104 } 9105 return false; 9106 } 9107 9108 @Override 9109 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9110 mContext.enforceCallingOrSelfPermission( 9111 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9112 "Only package verification agents can verify applications"); 9113 9114 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9115 final PackageVerificationResponse response = new PackageVerificationResponse( 9116 verificationCode, Binder.getCallingUid()); 9117 msg.arg1 = id; 9118 msg.obj = response; 9119 mHandler.sendMessage(msg); 9120 } 9121 9122 @Override 9123 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9124 long millisecondsToDelay) { 9125 mContext.enforceCallingOrSelfPermission( 9126 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9127 "Only package verification agents can extend verification timeouts"); 9128 9129 final PackageVerificationState state = mPendingVerification.get(id); 9130 final PackageVerificationResponse response = new PackageVerificationResponse( 9131 verificationCodeAtTimeout, Binder.getCallingUid()); 9132 9133 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9134 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9135 } 9136 if (millisecondsToDelay < 0) { 9137 millisecondsToDelay = 0; 9138 } 9139 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9140 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9141 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9142 } 9143 9144 if ((state != null) && !state.timeoutExtended()) { 9145 state.extendTimeout(); 9146 9147 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9148 msg.arg1 = id; 9149 msg.obj = response; 9150 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9151 } 9152 } 9153 9154 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9155 int verificationCode, UserHandle user) { 9156 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9157 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9158 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9159 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9160 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9161 9162 mContext.sendBroadcastAsUser(intent, user, 9163 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9164 } 9165 9166 private ComponentName matchComponentForVerifier(String packageName, 9167 List<ResolveInfo> receivers) { 9168 ActivityInfo targetReceiver = null; 9169 9170 final int NR = receivers.size(); 9171 for (int i = 0; i < NR; i++) { 9172 final ResolveInfo info = receivers.get(i); 9173 if (info.activityInfo == null) { 9174 continue; 9175 } 9176 9177 if (packageName.equals(info.activityInfo.packageName)) { 9178 targetReceiver = info.activityInfo; 9179 break; 9180 } 9181 } 9182 9183 if (targetReceiver == null) { 9184 return null; 9185 } 9186 9187 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9188 } 9189 9190 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9191 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9192 if (pkgInfo.verifiers.length == 0) { 9193 return null; 9194 } 9195 9196 final int N = pkgInfo.verifiers.length; 9197 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9198 for (int i = 0; i < N; i++) { 9199 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9200 9201 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9202 receivers); 9203 if (comp == null) { 9204 continue; 9205 } 9206 9207 final int verifierUid = getUidForVerifier(verifierInfo); 9208 if (verifierUid == -1) { 9209 continue; 9210 } 9211 9212 if (DEBUG_VERIFY) { 9213 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9214 + " with the correct signature"); 9215 } 9216 sufficientVerifiers.add(comp); 9217 verificationState.addSufficientVerifier(verifierUid); 9218 } 9219 9220 return sufficientVerifiers; 9221 } 9222 9223 private int getUidForVerifier(VerifierInfo verifierInfo) { 9224 synchronized (mPackages) { 9225 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9226 if (pkg == null) { 9227 return -1; 9228 } else if (pkg.mSignatures.length != 1) { 9229 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9230 + " has more than one signature; ignoring"); 9231 return -1; 9232 } 9233 9234 /* 9235 * If the public key of the package's signature does not match 9236 * our expected public key, then this is a different package and 9237 * we should skip. 9238 */ 9239 9240 final byte[] expectedPublicKey; 9241 try { 9242 final Signature verifierSig = pkg.mSignatures[0]; 9243 final PublicKey publicKey = verifierSig.getPublicKey(); 9244 expectedPublicKey = publicKey.getEncoded(); 9245 } catch (CertificateException e) { 9246 return -1; 9247 } 9248 9249 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9250 9251 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9252 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9253 + " does not have the expected public key; ignoring"); 9254 return -1; 9255 } 9256 9257 return pkg.applicationInfo.uid; 9258 } 9259 } 9260 9261 @Override 9262 public void finishPackageInstall(int token) { 9263 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9264 9265 if (DEBUG_INSTALL) { 9266 Slog.v(TAG, "BM finishing package install for " + token); 9267 } 9268 9269 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9270 mHandler.sendMessage(msg); 9271 } 9272 9273 /** 9274 * Get the verification agent timeout. 9275 * 9276 * @return verification timeout in milliseconds 9277 */ 9278 private long getVerificationTimeout() { 9279 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9280 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9281 DEFAULT_VERIFICATION_TIMEOUT); 9282 } 9283 9284 /** 9285 * Get the default verification agent response code. 9286 * 9287 * @return default verification response code 9288 */ 9289 private int getDefaultVerificationResponse() { 9290 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9291 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9292 DEFAULT_VERIFICATION_RESPONSE); 9293 } 9294 9295 /** 9296 * Check whether or not package verification has been enabled. 9297 * 9298 * @return true if verification should be performed 9299 */ 9300 private boolean isVerificationEnabled(int userId, int installFlags) { 9301 if (!DEFAULT_VERIFY_ENABLE) { 9302 return false; 9303 } 9304 9305 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9306 9307 // Check if installing from ADB 9308 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9309 // Do not run verification in a test harness environment 9310 if (ActivityManager.isRunningInTestHarness()) { 9311 return false; 9312 } 9313 if (ensureVerifyAppsEnabled) { 9314 return true; 9315 } 9316 // Check if the developer does not want package verification for ADB installs 9317 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9318 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9319 return false; 9320 } 9321 } 9322 9323 if (ensureVerifyAppsEnabled) { 9324 return true; 9325 } 9326 9327 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9328 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9329 } 9330 9331 @Override 9332 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9333 throws RemoteException { 9334 mContext.enforceCallingOrSelfPermission( 9335 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9336 "Only intentfilter verification agents can verify applications"); 9337 9338 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9339 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9340 Binder.getCallingUid(), verificationCode, failedDomains); 9341 msg.arg1 = id; 9342 msg.obj = response; 9343 mHandler.sendMessage(msg); 9344 } 9345 9346 @Override 9347 public int getIntentVerificationStatus(String packageName, int userId) { 9348 synchronized (mPackages) { 9349 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9350 } 9351 } 9352 9353 @Override 9354 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9355 boolean result = false; 9356 synchronized (mPackages) { 9357 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9358 } 9359 if (result) { 9360 scheduleWritePackageRestrictionsLocked(userId); 9361 } 9362 return result; 9363 } 9364 9365 @Override 9366 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9367 synchronized (mPackages) { 9368 return mSettings.getIntentFilterVerificationsLPr(packageName); 9369 } 9370 } 9371 9372 @Override 9373 public List<IntentFilter> getAllIntentFilters(String packageName) { 9374 if (TextUtils.isEmpty(packageName)) { 9375 return Collections.<IntentFilter>emptyList(); 9376 } 9377 synchronized (mPackages) { 9378 PackageParser.Package pkg = mPackages.get(packageName); 9379 if (pkg == null || pkg.activities == null) { 9380 return Collections.<IntentFilter>emptyList(); 9381 } 9382 final int count = pkg.activities.size(); 9383 ArrayList<IntentFilter> result = new ArrayList<>(); 9384 for (int n=0; n<count; n++) { 9385 PackageParser.Activity activity = pkg.activities.get(n); 9386 if (activity.intents != null || activity.intents.size() > 0) { 9387 result.addAll(activity.intents); 9388 } 9389 } 9390 return result; 9391 } 9392 } 9393 9394 @Override 9395 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9396 synchronized (mPackages) { 9397 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9398 if (packageName != null) { 9399 result |= updateIntentVerificationStatus(packageName, 9400 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9401 UserHandle.myUserId()); 9402 } 9403 return result; 9404 } 9405 } 9406 9407 @Override 9408 public String getDefaultBrowserPackageName(int userId) { 9409 synchronized (mPackages) { 9410 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9411 } 9412 } 9413 9414 /** 9415 * Get the "allow unknown sources" setting. 9416 * 9417 * @return the current "allow unknown sources" setting 9418 */ 9419 private int getUnknownSourcesSettings() { 9420 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9421 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9422 -1); 9423 } 9424 9425 @Override 9426 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9427 final int uid = Binder.getCallingUid(); 9428 // writer 9429 synchronized (mPackages) { 9430 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9431 if (targetPackageSetting == null) { 9432 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9433 } 9434 9435 PackageSetting installerPackageSetting; 9436 if (installerPackageName != null) { 9437 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9438 if (installerPackageSetting == null) { 9439 throw new IllegalArgumentException("Unknown installer package: " 9440 + installerPackageName); 9441 } 9442 } else { 9443 installerPackageSetting = null; 9444 } 9445 9446 Signature[] callerSignature; 9447 Object obj = mSettings.getUserIdLPr(uid); 9448 if (obj != null) { 9449 if (obj instanceof SharedUserSetting) { 9450 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9451 } else if (obj instanceof PackageSetting) { 9452 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9453 } else { 9454 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9455 } 9456 } else { 9457 throw new SecurityException("Unknown calling uid " + uid); 9458 } 9459 9460 // Verify: can't set installerPackageName to a package that is 9461 // not signed with the same cert as the caller. 9462 if (installerPackageSetting != null) { 9463 if (compareSignatures(callerSignature, 9464 installerPackageSetting.signatures.mSignatures) 9465 != PackageManager.SIGNATURE_MATCH) { 9466 throw new SecurityException( 9467 "Caller does not have same cert as new installer package " 9468 + installerPackageName); 9469 } 9470 } 9471 9472 // Verify: if target already has an installer package, it must 9473 // be signed with the same cert as the caller. 9474 if (targetPackageSetting.installerPackageName != null) { 9475 PackageSetting setting = mSettings.mPackages.get( 9476 targetPackageSetting.installerPackageName); 9477 // If the currently set package isn't valid, then it's always 9478 // okay to change it. 9479 if (setting != null) { 9480 if (compareSignatures(callerSignature, 9481 setting.signatures.mSignatures) 9482 != PackageManager.SIGNATURE_MATCH) { 9483 throw new SecurityException( 9484 "Caller does not have same cert as old installer package " 9485 + targetPackageSetting.installerPackageName); 9486 } 9487 } 9488 } 9489 9490 // Okay! 9491 targetPackageSetting.installerPackageName = installerPackageName; 9492 scheduleWriteSettingsLocked(); 9493 } 9494 } 9495 9496 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9497 // Queue up an async operation since the package installation may take a little while. 9498 mHandler.post(new Runnable() { 9499 public void run() { 9500 mHandler.removeCallbacks(this); 9501 // Result object to be returned 9502 PackageInstalledInfo res = new PackageInstalledInfo(); 9503 res.returnCode = currentStatus; 9504 res.uid = -1; 9505 res.pkg = null; 9506 res.removedInfo = new PackageRemovedInfo(); 9507 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9508 args.doPreInstall(res.returnCode); 9509 synchronized (mInstallLock) { 9510 installPackageLI(args, res); 9511 } 9512 args.doPostInstall(res.returnCode, res.uid); 9513 } 9514 9515 // A restore should be performed at this point if (a) the install 9516 // succeeded, (b) the operation is not an update, and (c) the new 9517 // package has not opted out of backup participation. 9518 final boolean update = res.removedInfo.removedPackage != null; 9519 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9520 boolean doRestore = !update 9521 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9522 9523 // Set up the post-install work request bookkeeping. This will be used 9524 // and cleaned up by the post-install event handling regardless of whether 9525 // there's a restore pass performed. Token values are >= 1. 9526 int token; 9527 if (mNextInstallToken < 0) mNextInstallToken = 1; 9528 token = mNextInstallToken++; 9529 9530 PostInstallData data = new PostInstallData(args, res); 9531 mRunningInstalls.put(token, data); 9532 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9533 9534 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9535 // Pass responsibility to the Backup Manager. It will perform a 9536 // restore if appropriate, then pass responsibility back to the 9537 // Package Manager to run the post-install observer callbacks 9538 // and broadcasts. 9539 IBackupManager bm = IBackupManager.Stub.asInterface( 9540 ServiceManager.getService(Context.BACKUP_SERVICE)); 9541 if (bm != null) { 9542 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9543 + " to BM for possible restore"); 9544 try { 9545 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9546 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9547 } else { 9548 doRestore = false; 9549 } 9550 } catch (RemoteException e) { 9551 // can't happen; the backup manager is local 9552 } catch (Exception e) { 9553 Slog.e(TAG, "Exception trying to enqueue restore", e); 9554 doRestore = false; 9555 } 9556 } else { 9557 Slog.e(TAG, "Backup Manager not found!"); 9558 doRestore = false; 9559 } 9560 } 9561 9562 if (!doRestore) { 9563 // No restore possible, or the Backup Manager was mysteriously not 9564 // available -- just fire the post-install work request directly. 9565 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9566 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9567 mHandler.sendMessage(msg); 9568 } 9569 } 9570 }); 9571 } 9572 9573 private abstract class HandlerParams { 9574 private static final int MAX_RETRIES = 4; 9575 9576 /** 9577 * Number of times startCopy() has been attempted and had a non-fatal 9578 * error. 9579 */ 9580 private int mRetries = 0; 9581 9582 /** User handle for the user requesting the information or installation. */ 9583 private final UserHandle mUser; 9584 9585 HandlerParams(UserHandle user) { 9586 mUser = user; 9587 } 9588 9589 UserHandle getUser() { 9590 return mUser; 9591 } 9592 9593 final boolean startCopy() { 9594 boolean res; 9595 try { 9596 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9597 9598 if (++mRetries > MAX_RETRIES) { 9599 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9600 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9601 handleServiceError(); 9602 return false; 9603 } else { 9604 handleStartCopy(); 9605 res = true; 9606 } 9607 } catch (RemoteException e) { 9608 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9609 mHandler.sendEmptyMessage(MCS_RECONNECT); 9610 res = false; 9611 } 9612 handleReturnCode(); 9613 return res; 9614 } 9615 9616 final void serviceError() { 9617 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9618 handleServiceError(); 9619 handleReturnCode(); 9620 } 9621 9622 abstract void handleStartCopy() throws RemoteException; 9623 abstract void handleServiceError(); 9624 abstract void handleReturnCode(); 9625 } 9626 9627 class MeasureParams extends HandlerParams { 9628 private final PackageStats mStats; 9629 private boolean mSuccess; 9630 9631 private final IPackageStatsObserver mObserver; 9632 9633 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9634 super(new UserHandle(stats.userHandle)); 9635 mObserver = observer; 9636 mStats = stats; 9637 } 9638 9639 @Override 9640 public String toString() { 9641 return "MeasureParams{" 9642 + Integer.toHexString(System.identityHashCode(this)) 9643 + " " + mStats.packageName + "}"; 9644 } 9645 9646 @Override 9647 void handleStartCopy() throws RemoteException { 9648 synchronized (mInstallLock) { 9649 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9650 } 9651 9652 if (mSuccess) { 9653 final boolean mounted; 9654 if (Environment.isExternalStorageEmulated()) { 9655 mounted = true; 9656 } else { 9657 final String status = Environment.getExternalStorageState(); 9658 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9659 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9660 } 9661 9662 if (mounted) { 9663 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9664 9665 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9666 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9667 9668 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9669 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9670 9671 // Always subtract cache size, since it's a subdirectory 9672 mStats.externalDataSize -= mStats.externalCacheSize; 9673 9674 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9675 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9676 9677 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9678 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9679 } 9680 } 9681 } 9682 9683 @Override 9684 void handleReturnCode() { 9685 if (mObserver != null) { 9686 try { 9687 mObserver.onGetStatsCompleted(mStats, mSuccess); 9688 } catch (RemoteException e) { 9689 Slog.i(TAG, "Observer no longer exists."); 9690 } 9691 } 9692 } 9693 9694 @Override 9695 void handleServiceError() { 9696 Slog.e(TAG, "Could not measure application " + mStats.packageName 9697 + " external storage"); 9698 } 9699 } 9700 9701 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9702 throws RemoteException { 9703 long result = 0; 9704 for (File path : paths) { 9705 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9706 } 9707 return result; 9708 } 9709 9710 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9711 for (File path : paths) { 9712 try { 9713 mcs.clearDirectory(path.getAbsolutePath()); 9714 } catch (RemoteException e) { 9715 } 9716 } 9717 } 9718 9719 static class OriginInfo { 9720 /** 9721 * Location where install is coming from, before it has been 9722 * copied/renamed into place. This could be a single monolithic APK 9723 * file, or a cluster directory. This location may be untrusted. 9724 */ 9725 final File file; 9726 final String cid; 9727 9728 /** 9729 * Flag indicating that {@link #file} or {@link #cid} has already been 9730 * staged, meaning downstream users don't need to defensively copy the 9731 * contents. 9732 */ 9733 final boolean staged; 9734 9735 /** 9736 * Flag indicating that {@link #file} or {@link #cid} is an already 9737 * installed app that is being moved. 9738 */ 9739 final boolean existing; 9740 9741 final String resolvedPath; 9742 final File resolvedFile; 9743 9744 static OriginInfo fromNothing() { 9745 return new OriginInfo(null, null, false, false); 9746 } 9747 9748 static OriginInfo fromUntrustedFile(File file) { 9749 return new OriginInfo(file, null, false, false); 9750 } 9751 9752 static OriginInfo fromExistingFile(File file) { 9753 return new OriginInfo(file, null, false, true); 9754 } 9755 9756 static OriginInfo fromStagedFile(File file) { 9757 return new OriginInfo(file, null, true, false); 9758 } 9759 9760 static OriginInfo fromStagedContainer(String cid) { 9761 return new OriginInfo(null, cid, true, false); 9762 } 9763 9764 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9765 this.file = file; 9766 this.cid = cid; 9767 this.staged = staged; 9768 this.existing = existing; 9769 9770 if (cid != null) { 9771 resolvedPath = PackageHelper.getSdDir(cid); 9772 resolvedFile = new File(resolvedPath); 9773 } else if (file != null) { 9774 resolvedPath = file.getAbsolutePath(); 9775 resolvedFile = file; 9776 } else { 9777 resolvedPath = null; 9778 resolvedFile = null; 9779 } 9780 } 9781 } 9782 9783 class MoveInfo { 9784 final int moveId; 9785 final String fromUuid; 9786 final String toUuid; 9787 final String packageName; 9788 final String dataAppName; 9789 final int appId; 9790 final String seinfo; 9791 9792 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9793 String dataAppName, int appId, String seinfo) { 9794 this.moveId = moveId; 9795 this.fromUuid = fromUuid; 9796 this.toUuid = toUuid; 9797 this.packageName = packageName; 9798 this.dataAppName = dataAppName; 9799 this.appId = appId; 9800 this.seinfo = seinfo; 9801 } 9802 } 9803 9804 class InstallParams extends HandlerParams { 9805 final OriginInfo origin; 9806 final MoveInfo move; 9807 final IPackageInstallObserver2 observer; 9808 int installFlags; 9809 final String installerPackageName; 9810 final String volumeUuid; 9811 final VerificationParams verificationParams; 9812 private InstallArgs mArgs; 9813 private int mRet; 9814 final String packageAbiOverride; 9815 9816 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9817 int installFlags, String installerPackageName, String volumeUuid, 9818 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9819 super(user); 9820 this.origin = origin; 9821 this.move = move; 9822 this.observer = observer; 9823 this.installFlags = installFlags; 9824 this.installerPackageName = installerPackageName; 9825 this.volumeUuid = volumeUuid; 9826 this.verificationParams = verificationParams; 9827 this.packageAbiOverride = packageAbiOverride; 9828 } 9829 9830 @Override 9831 public String toString() { 9832 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9833 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9834 } 9835 9836 public ManifestDigest getManifestDigest() { 9837 if (verificationParams == null) { 9838 return null; 9839 } 9840 return verificationParams.getManifestDigest(); 9841 } 9842 9843 private int installLocationPolicy(PackageInfoLite pkgLite) { 9844 String packageName = pkgLite.packageName; 9845 int installLocation = pkgLite.installLocation; 9846 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9847 // reader 9848 synchronized (mPackages) { 9849 PackageParser.Package pkg = mPackages.get(packageName); 9850 if (pkg != null) { 9851 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9852 // Check for downgrading. 9853 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9854 try { 9855 checkDowngrade(pkg, pkgLite); 9856 } catch (PackageManagerException e) { 9857 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9858 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9859 } 9860 } 9861 // Check for updated system application. 9862 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9863 if (onSd) { 9864 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9865 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9866 } 9867 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9868 } else { 9869 if (onSd) { 9870 // Install flag overrides everything. 9871 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9872 } 9873 // If current upgrade specifies particular preference 9874 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9875 // Application explicitly specified internal. 9876 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9877 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9878 // App explictly prefers external. Let policy decide 9879 } else { 9880 // Prefer previous location 9881 if (isExternal(pkg)) { 9882 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9883 } 9884 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9885 } 9886 } 9887 } else { 9888 // Invalid install. Return error code 9889 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9890 } 9891 } 9892 } 9893 // All the special cases have been taken care of. 9894 // Return result based on recommended install location. 9895 if (onSd) { 9896 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9897 } 9898 return pkgLite.recommendedInstallLocation; 9899 } 9900 9901 /* 9902 * Invoke remote method to get package information and install 9903 * location values. Override install location based on default 9904 * policy if needed and then create install arguments based 9905 * on the install location. 9906 */ 9907 public void handleStartCopy() throws RemoteException { 9908 int ret = PackageManager.INSTALL_SUCCEEDED; 9909 9910 // If we're already staged, we've firmly committed to an install location 9911 if (origin.staged) { 9912 if (origin.file != null) { 9913 installFlags |= PackageManager.INSTALL_INTERNAL; 9914 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9915 } else if (origin.cid != null) { 9916 installFlags |= PackageManager.INSTALL_EXTERNAL; 9917 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9918 } else { 9919 throw new IllegalStateException("Invalid stage location"); 9920 } 9921 } 9922 9923 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9924 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9925 9926 PackageInfoLite pkgLite = null; 9927 9928 if (onInt && onSd) { 9929 // Check if both bits are set. 9930 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9931 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9932 } else { 9933 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9934 packageAbiOverride); 9935 9936 /* 9937 * If we have too little free space, try to free cache 9938 * before giving up. 9939 */ 9940 if (!origin.staged && pkgLite.recommendedInstallLocation 9941 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9942 // TODO: focus freeing disk space on the target device 9943 final StorageManager storage = StorageManager.from(mContext); 9944 final long lowThreshold = storage.getStorageLowBytes( 9945 Environment.getDataDirectory()); 9946 9947 final long sizeBytes = mContainerService.calculateInstalledSize( 9948 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9949 9950 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9951 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9952 installFlags, packageAbiOverride); 9953 } 9954 9955 /* 9956 * The cache free must have deleted the file we 9957 * downloaded to install. 9958 * 9959 * TODO: fix the "freeCache" call to not delete 9960 * the file we care about. 9961 */ 9962 if (pkgLite.recommendedInstallLocation 9963 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9964 pkgLite.recommendedInstallLocation 9965 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9966 } 9967 } 9968 } 9969 9970 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9971 int loc = pkgLite.recommendedInstallLocation; 9972 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9973 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9974 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9975 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9976 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9977 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9978 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9979 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9980 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9981 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9982 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9983 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9984 } else { 9985 // Override with defaults if needed. 9986 loc = installLocationPolicy(pkgLite); 9987 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9988 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9989 } else if (!onSd && !onInt) { 9990 // Override install location with flags 9991 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9992 // Set the flag to install on external media. 9993 installFlags |= PackageManager.INSTALL_EXTERNAL; 9994 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9995 } else { 9996 // Make sure the flag for installing on external 9997 // media is unset 9998 installFlags |= PackageManager.INSTALL_INTERNAL; 9999 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10000 } 10001 } 10002 } 10003 } 10004 10005 final InstallArgs args = createInstallArgs(this); 10006 mArgs = args; 10007 10008 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10009 /* 10010 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10011 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10012 */ 10013 int userIdentifier = getUser().getIdentifier(); 10014 if (userIdentifier == UserHandle.USER_ALL 10015 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10016 userIdentifier = UserHandle.USER_OWNER; 10017 } 10018 10019 /* 10020 * Determine if we have any installed package verifiers. If we 10021 * do, then we'll defer to them to verify the packages. 10022 */ 10023 final int requiredUid = mRequiredVerifierPackage == null ? -1 10024 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10025 if (!origin.existing && requiredUid != -1 10026 && isVerificationEnabled(userIdentifier, installFlags)) { 10027 final Intent verification = new Intent( 10028 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10029 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10030 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10031 PACKAGE_MIME_TYPE); 10032 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10033 10034 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10035 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10036 0 /* TODO: Which userId? */); 10037 10038 if (DEBUG_VERIFY) { 10039 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10040 + verification.toString() + " with " + pkgLite.verifiers.length 10041 + " optional verifiers"); 10042 } 10043 10044 final int verificationId = mPendingVerificationToken++; 10045 10046 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10047 10048 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10049 installerPackageName); 10050 10051 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10052 installFlags); 10053 10054 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10055 pkgLite.packageName); 10056 10057 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10058 pkgLite.versionCode); 10059 10060 if (verificationParams != null) { 10061 if (verificationParams.getVerificationURI() != null) { 10062 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10063 verificationParams.getVerificationURI()); 10064 } 10065 if (verificationParams.getOriginatingURI() != null) { 10066 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10067 verificationParams.getOriginatingURI()); 10068 } 10069 if (verificationParams.getReferrer() != null) { 10070 verification.putExtra(Intent.EXTRA_REFERRER, 10071 verificationParams.getReferrer()); 10072 } 10073 if (verificationParams.getOriginatingUid() >= 0) { 10074 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10075 verificationParams.getOriginatingUid()); 10076 } 10077 if (verificationParams.getInstallerUid() >= 0) { 10078 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10079 verificationParams.getInstallerUid()); 10080 } 10081 } 10082 10083 final PackageVerificationState verificationState = new PackageVerificationState( 10084 requiredUid, args); 10085 10086 mPendingVerification.append(verificationId, verificationState); 10087 10088 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10089 receivers, verificationState); 10090 10091 /* 10092 * If any sufficient verifiers were listed in the package 10093 * manifest, attempt to ask them. 10094 */ 10095 if (sufficientVerifiers != null) { 10096 final int N = sufficientVerifiers.size(); 10097 if (N == 0) { 10098 Slog.i(TAG, "Additional verifiers required, but none installed."); 10099 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10100 } else { 10101 for (int i = 0; i < N; i++) { 10102 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10103 10104 final Intent sufficientIntent = new Intent(verification); 10105 sufficientIntent.setComponent(verifierComponent); 10106 10107 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10108 } 10109 } 10110 } 10111 10112 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10113 mRequiredVerifierPackage, receivers); 10114 if (ret == PackageManager.INSTALL_SUCCEEDED 10115 && mRequiredVerifierPackage != null) { 10116 /* 10117 * Send the intent to the required verification agent, 10118 * but only start the verification timeout after the 10119 * target BroadcastReceivers have run. 10120 */ 10121 verification.setComponent(requiredVerifierComponent); 10122 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10123 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10124 new BroadcastReceiver() { 10125 @Override 10126 public void onReceive(Context context, Intent intent) { 10127 final Message msg = mHandler 10128 .obtainMessage(CHECK_PENDING_VERIFICATION); 10129 msg.arg1 = verificationId; 10130 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10131 } 10132 }, null, 0, null, null); 10133 10134 /* 10135 * We don't want the copy to proceed until verification 10136 * succeeds, so null out this field. 10137 */ 10138 mArgs = null; 10139 } 10140 } else { 10141 /* 10142 * No package verification is enabled, so immediately start 10143 * the remote call to initiate copy using temporary file. 10144 */ 10145 ret = args.copyApk(mContainerService, true); 10146 } 10147 } 10148 10149 mRet = ret; 10150 } 10151 10152 @Override 10153 void handleReturnCode() { 10154 // If mArgs is null, then MCS couldn't be reached. When it 10155 // reconnects, it will try again to install. At that point, this 10156 // will succeed. 10157 if (mArgs != null) { 10158 processPendingInstall(mArgs, mRet); 10159 } 10160 } 10161 10162 @Override 10163 void handleServiceError() { 10164 mArgs = createInstallArgs(this); 10165 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10166 } 10167 10168 public boolean isForwardLocked() { 10169 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10170 } 10171 } 10172 10173 /** 10174 * Used during creation of InstallArgs 10175 * 10176 * @param installFlags package installation flags 10177 * @return true if should be installed on external storage 10178 */ 10179 private static boolean installOnExternalAsec(int installFlags) { 10180 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10181 return false; 10182 } 10183 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10184 return true; 10185 } 10186 return false; 10187 } 10188 10189 /** 10190 * Used during creation of InstallArgs 10191 * 10192 * @param installFlags package installation flags 10193 * @return true if should be installed as forward locked 10194 */ 10195 private static boolean installForwardLocked(int installFlags) { 10196 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10197 } 10198 10199 private InstallArgs createInstallArgs(InstallParams params) { 10200 if (params.move != null) { 10201 return new MoveInstallArgs(params); 10202 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10203 return new AsecInstallArgs(params); 10204 } else { 10205 return new FileInstallArgs(params); 10206 } 10207 } 10208 10209 /** 10210 * Create args that describe an existing installed package. Typically used 10211 * when cleaning up old installs, or used as a move source. 10212 */ 10213 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10214 String resourcePath, String[] instructionSets) { 10215 final boolean isInAsec; 10216 if (installOnExternalAsec(installFlags)) { 10217 /* Apps on SD card are always in ASEC containers. */ 10218 isInAsec = true; 10219 } else if (installForwardLocked(installFlags) 10220 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10221 /* 10222 * Forward-locked apps are only in ASEC containers if they're the 10223 * new style 10224 */ 10225 isInAsec = true; 10226 } else { 10227 isInAsec = false; 10228 } 10229 10230 if (isInAsec) { 10231 return new AsecInstallArgs(codePath, instructionSets, 10232 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10233 } else { 10234 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10235 } 10236 } 10237 10238 static abstract class InstallArgs { 10239 /** @see InstallParams#origin */ 10240 final OriginInfo origin; 10241 /** @see InstallParams#move */ 10242 final MoveInfo move; 10243 10244 final IPackageInstallObserver2 observer; 10245 // Always refers to PackageManager flags only 10246 final int installFlags; 10247 final String installerPackageName; 10248 final String volumeUuid; 10249 final ManifestDigest manifestDigest; 10250 final UserHandle user; 10251 final String abiOverride; 10252 10253 // The list of instruction sets supported by this app. This is currently 10254 // only used during the rmdex() phase to clean up resources. We can get rid of this 10255 // if we move dex files under the common app path. 10256 /* nullable */ String[] instructionSets; 10257 10258 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10259 int installFlags, String installerPackageName, String volumeUuid, 10260 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10261 String abiOverride) { 10262 this.origin = origin; 10263 this.move = move; 10264 this.installFlags = installFlags; 10265 this.observer = observer; 10266 this.installerPackageName = installerPackageName; 10267 this.volumeUuid = volumeUuid; 10268 this.manifestDigest = manifestDigest; 10269 this.user = user; 10270 this.instructionSets = instructionSets; 10271 this.abiOverride = abiOverride; 10272 } 10273 10274 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10275 abstract int doPreInstall(int status); 10276 10277 /** 10278 * Rename package into final resting place. All paths on the given 10279 * scanned package should be updated to reflect the rename. 10280 */ 10281 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10282 abstract int doPostInstall(int status, int uid); 10283 10284 /** @see PackageSettingBase#codePathString */ 10285 abstract String getCodePath(); 10286 /** @see PackageSettingBase#resourcePathString */ 10287 abstract String getResourcePath(); 10288 10289 // Need installer lock especially for dex file removal. 10290 abstract void cleanUpResourcesLI(); 10291 abstract boolean doPostDeleteLI(boolean delete); 10292 10293 /** 10294 * Called before the source arguments are copied. This is used mostly 10295 * for MoveParams when it needs to read the source file to put it in the 10296 * destination. 10297 */ 10298 int doPreCopy() { 10299 return PackageManager.INSTALL_SUCCEEDED; 10300 } 10301 10302 /** 10303 * Called after the source arguments are copied. This is used mostly for 10304 * MoveParams when it needs to read the source file to put it in the 10305 * destination. 10306 * 10307 * @return 10308 */ 10309 int doPostCopy(int uid) { 10310 return PackageManager.INSTALL_SUCCEEDED; 10311 } 10312 10313 protected boolean isFwdLocked() { 10314 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10315 } 10316 10317 protected boolean isExternalAsec() { 10318 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10319 } 10320 10321 UserHandle getUser() { 10322 return user; 10323 } 10324 } 10325 10326 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10327 if (!allCodePaths.isEmpty()) { 10328 if (instructionSets == null) { 10329 throw new IllegalStateException("instructionSet == null"); 10330 } 10331 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10332 for (String codePath : allCodePaths) { 10333 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10334 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10335 if (retCode < 0) { 10336 Slog.w(TAG, "Couldn't remove dex file for package: " 10337 + " at location " + codePath + ", retcode=" + retCode); 10338 // we don't consider this to be a failure of the core package deletion 10339 } 10340 } 10341 } 10342 } 10343 } 10344 10345 /** 10346 * Logic to handle installation of non-ASEC applications, including copying 10347 * and renaming logic. 10348 */ 10349 class FileInstallArgs extends InstallArgs { 10350 private File codeFile; 10351 private File resourceFile; 10352 10353 // Example topology: 10354 // /data/app/com.example/base.apk 10355 // /data/app/com.example/split_foo.apk 10356 // /data/app/com.example/lib/arm/libfoo.so 10357 // /data/app/com.example/lib/arm64/libfoo.so 10358 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10359 10360 /** New install */ 10361 FileInstallArgs(InstallParams params) { 10362 super(params.origin, params.move, params.observer, params.installFlags, 10363 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10364 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10365 if (isFwdLocked()) { 10366 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10367 } 10368 } 10369 10370 /** Existing install */ 10371 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10372 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10373 null); 10374 this.codeFile = (codePath != null) ? new File(codePath) : null; 10375 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10376 } 10377 10378 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10379 if (origin.staged) { 10380 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10381 codeFile = origin.file; 10382 resourceFile = origin.file; 10383 return PackageManager.INSTALL_SUCCEEDED; 10384 } 10385 10386 try { 10387 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10388 codeFile = tempDir; 10389 resourceFile = tempDir; 10390 } catch (IOException e) { 10391 Slog.w(TAG, "Failed to create copy file: " + e); 10392 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10393 } 10394 10395 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10396 @Override 10397 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10398 if (!FileUtils.isValidExtFilename(name)) { 10399 throw new IllegalArgumentException("Invalid filename: " + name); 10400 } 10401 try { 10402 final File file = new File(codeFile, name); 10403 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10404 O_RDWR | O_CREAT, 0644); 10405 Os.chmod(file.getAbsolutePath(), 0644); 10406 return new ParcelFileDescriptor(fd); 10407 } catch (ErrnoException e) { 10408 throw new RemoteException("Failed to open: " + e.getMessage()); 10409 } 10410 } 10411 }; 10412 10413 int ret = PackageManager.INSTALL_SUCCEEDED; 10414 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10415 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10416 Slog.e(TAG, "Failed to copy package"); 10417 return ret; 10418 } 10419 10420 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10421 NativeLibraryHelper.Handle handle = null; 10422 try { 10423 handle = NativeLibraryHelper.Handle.create(codeFile); 10424 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10425 abiOverride); 10426 } catch (IOException e) { 10427 Slog.e(TAG, "Copying native libraries failed", e); 10428 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10429 } finally { 10430 IoUtils.closeQuietly(handle); 10431 } 10432 10433 return ret; 10434 } 10435 10436 int doPreInstall(int status) { 10437 if (status != PackageManager.INSTALL_SUCCEEDED) { 10438 cleanUp(); 10439 } 10440 return status; 10441 } 10442 10443 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10444 if (status != PackageManager.INSTALL_SUCCEEDED) { 10445 cleanUp(); 10446 return false; 10447 } 10448 10449 final File targetDir = codeFile.getParentFile(); 10450 final File beforeCodeFile = codeFile; 10451 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10452 10453 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10454 try { 10455 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10456 } catch (ErrnoException e) { 10457 Slog.w(TAG, "Failed to rename", e); 10458 return false; 10459 } 10460 10461 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10462 Slog.w(TAG, "Failed to restorecon"); 10463 return false; 10464 } 10465 10466 // Reflect the rename internally 10467 codeFile = afterCodeFile; 10468 resourceFile = afterCodeFile; 10469 10470 // Reflect the rename in scanned details 10471 pkg.codePath = afterCodeFile.getAbsolutePath(); 10472 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10473 pkg.baseCodePath); 10474 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10475 pkg.splitCodePaths); 10476 10477 // Reflect the rename in app info 10478 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10479 pkg.applicationInfo.setCodePath(pkg.codePath); 10480 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10481 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10482 pkg.applicationInfo.setResourcePath(pkg.codePath); 10483 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10484 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10485 10486 return true; 10487 } 10488 10489 int doPostInstall(int status, int uid) { 10490 if (status != PackageManager.INSTALL_SUCCEEDED) { 10491 cleanUp(); 10492 } 10493 return status; 10494 } 10495 10496 @Override 10497 String getCodePath() { 10498 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10499 } 10500 10501 @Override 10502 String getResourcePath() { 10503 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10504 } 10505 10506 private boolean cleanUp() { 10507 if (codeFile == null || !codeFile.exists()) { 10508 return false; 10509 } 10510 10511 if (codeFile.isDirectory()) { 10512 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10513 } else { 10514 codeFile.delete(); 10515 } 10516 10517 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10518 resourceFile.delete(); 10519 } 10520 10521 return true; 10522 } 10523 10524 void cleanUpResourcesLI() { 10525 // Try enumerating all code paths before deleting 10526 List<String> allCodePaths = Collections.EMPTY_LIST; 10527 if (codeFile != null && codeFile.exists()) { 10528 try { 10529 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10530 allCodePaths = pkg.getAllCodePaths(); 10531 } catch (PackageParserException e) { 10532 // Ignored; we tried our best 10533 } 10534 } 10535 10536 cleanUp(); 10537 removeDexFiles(allCodePaths, instructionSets); 10538 } 10539 10540 boolean doPostDeleteLI(boolean delete) { 10541 // XXX err, shouldn't we respect the delete flag? 10542 cleanUpResourcesLI(); 10543 return true; 10544 } 10545 } 10546 10547 private boolean isAsecExternal(String cid) { 10548 final String asecPath = PackageHelper.getSdFilesystem(cid); 10549 return !asecPath.startsWith(mAsecInternalPath); 10550 } 10551 10552 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10553 PackageManagerException { 10554 if (copyRet < 0) { 10555 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10556 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10557 throw new PackageManagerException(copyRet, message); 10558 } 10559 } 10560 } 10561 10562 /** 10563 * Extract the MountService "container ID" from the full code path of an 10564 * .apk. 10565 */ 10566 static String cidFromCodePath(String fullCodePath) { 10567 int eidx = fullCodePath.lastIndexOf("/"); 10568 String subStr1 = fullCodePath.substring(0, eidx); 10569 int sidx = subStr1.lastIndexOf("/"); 10570 return subStr1.substring(sidx+1, eidx); 10571 } 10572 10573 /** 10574 * Logic to handle installation of ASEC applications, including copying and 10575 * renaming logic. 10576 */ 10577 class AsecInstallArgs extends InstallArgs { 10578 static final String RES_FILE_NAME = "pkg.apk"; 10579 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10580 10581 String cid; 10582 String packagePath; 10583 String resourcePath; 10584 10585 /** New install */ 10586 AsecInstallArgs(InstallParams params) { 10587 super(params.origin, params.move, params.observer, params.installFlags, 10588 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10589 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10590 } 10591 10592 /** Existing install */ 10593 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10594 boolean isExternal, boolean isForwardLocked) { 10595 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10596 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10597 instructionSets, null); 10598 // Hackily pretend we're still looking at a full code path 10599 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10600 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10601 } 10602 10603 // Extract cid from fullCodePath 10604 int eidx = fullCodePath.lastIndexOf("/"); 10605 String subStr1 = fullCodePath.substring(0, eidx); 10606 int sidx = subStr1.lastIndexOf("/"); 10607 cid = subStr1.substring(sidx+1, eidx); 10608 setMountPath(subStr1); 10609 } 10610 10611 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10612 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10613 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10614 instructionSets, null); 10615 this.cid = cid; 10616 setMountPath(PackageHelper.getSdDir(cid)); 10617 } 10618 10619 void createCopyFile() { 10620 cid = mInstallerService.allocateExternalStageCidLegacy(); 10621 } 10622 10623 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10624 if (origin.staged) { 10625 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10626 cid = origin.cid; 10627 setMountPath(PackageHelper.getSdDir(cid)); 10628 return PackageManager.INSTALL_SUCCEEDED; 10629 } 10630 10631 if (temp) { 10632 createCopyFile(); 10633 } else { 10634 /* 10635 * Pre-emptively destroy the container since it's destroyed if 10636 * copying fails due to it existing anyway. 10637 */ 10638 PackageHelper.destroySdDir(cid); 10639 } 10640 10641 final String newMountPath = imcs.copyPackageToContainer( 10642 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10643 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10644 10645 if (newMountPath != null) { 10646 setMountPath(newMountPath); 10647 return PackageManager.INSTALL_SUCCEEDED; 10648 } else { 10649 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10650 } 10651 } 10652 10653 @Override 10654 String getCodePath() { 10655 return packagePath; 10656 } 10657 10658 @Override 10659 String getResourcePath() { 10660 return resourcePath; 10661 } 10662 10663 int doPreInstall(int status) { 10664 if (status != PackageManager.INSTALL_SUCCEEDED) { 10665 // Destroy container 10666 PackageHelper.destroySdDir(cid); 10667 } else { 10668 boolean mounted = PackageHelper.isContainerMounted(cid); 10669 if (!mounted) { 10670 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10671 Process.SYSTEM_UID); 10672 if (newMountPath != null) { 10673 setMountPath(newMountPath); 10674 } else { 10675 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10676 } 10677 } 10678 } 10679 return status; 10680 } 10681 10682 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10683 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10684 String newMountPath = null; 10685 if (PackageHelper.isContainerMounted(cid)) { 10686 // Unmount the container 10687 if (!PackageHelper.unMountSdDir(cid)) { 10688 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10689 return false; 10690 } 10691 } 10692 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10693 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10694 " which might be stale. Will try to clean up."); 10695 // Clean up the stale container and proceed to recreate. 10696 if (!PackageHelper.destroySdDir(newCacheId)) { 10697 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10698 return false; 10699 } 10700 // Successfully cleaned up stale container. Try to rename again. 10701 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10702 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10703 + " inspite of cleaning it up."); 10704 return false; 10705 } 10706 } 10707 if (!PackageHelper.isContainerMounted(newCacheId)) { 10708 Slog.w(TAG, "Mounting container " + newCacheId); 10709 newMountPath = PackageHelper.mountSdDir(newCacheId, 10710 getEncryptKey(), Process.SYSTEM_UID); 10711 } else { 10712 newMountPath = PackageHelper.getSdDir(newCacheId); 10713 } 10714 if (newMountPath == null) { 10715 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10716 return false; 10717 } 10718 Log.i(TAG, "Succesfully renamed " + cid + 10719 " to " + newCacheId + 10720 " at new path: " + newMountPath); 10721 cid = newCacheId; 10722 10723 final File beforeCodeFile = new File(packagePath); 10724 setMountPath(newMountPath); 10725 final File afterCodeFile = new File(packagePath); 10726 10727 // Reflect the rename in scanned details 10728 pkg.codePath = afterCodeFile.getAbsolutePath(); 10729 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10730 pkg.baseCodePath); 10731 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10732 pkg.splitCodePaths); 10733 10734 // Reflect the rename in app info 10735 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10736 pkg.applicationInfo.setCodePath(pkg.codePath); 10737 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10738 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10739 pkg.applicationInfo.setResourcePath(pkg.codePath); 10740 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10741 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10742 10743 return true; 10744 } 10745 10746 private void setMountPath(String mountPath) { 10747 final File mountFile = new File(mountPath); 10748 10749 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10750 if (monolithicFile.exists()) { 10751 packagePath = monolithicFile.getAbsolutePath(); 10752 if (isFwdLocked()) { 10753 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10754 } else { 10755 resourcePath = packagePath; 10756 } 10757 } else { 10758 packagePath = mountFile.getAbsolutePath(); 10759 resourcePath = packagePath; 10760 } 10761 } 10762 10763 int doPostInstall(int status, int uid) { 10764 if (status != PackageManager.INSTALL_SUCCEEDED) { 10765 cleanUp(); 10766 } else { 10767 final int groupOwner; 10768 final String protectedFile; 10769 if (isFwdLocked()) { 10770 groupOwner = UserHandle.getSharedAppGid(uid); 10771 protectedFile = RES_FILE_NAME; 10772 } else { 10773 groupOwner = -1; 10774 protectedFile = null; 10775 } 10776 10777 if (uid < Process.FIRST_APPLICATION_UID 10778 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10779 Slog.e(TAG, "Failed to finalize " + cid); 10780 PackageHelper.destroySdDir(cid); 10781 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10782 } 10783 10784 boolean mounted = PackageHelper.isContainerMounted(cid); 10785 if (!mounted) { 10786 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10787 } 10788 } 10789 return status; 10790 } 10791 10792 private void cleanUp() { 10793 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10794 10795 // Destroy secure container 10796 PackageHelper.destroySdDir(cid); 10797 } 10798 10799 private List<String> getAllCodePaths() { 10800 final File codeFile = new File(getCodePath()); 10801 if (codeFile != null && codeFile.exists()) { 10802 try { 10803 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10804 return pkg.getAllCodePaths(); 10805 } catch (PackageParserException e) { 10806 // Ignored; we tried our best 10807 } 10808 } 10809 return Collections.EMPTY_LIST; 10810 } 10811 10812 void cleanUpResourcesLI() { 10813 // Enumerate all code paths before deleting 10814 cleanUpResourcesLI(getAllCodePaths()); 10815 } 10816 10817 private void cleanUpResourcesLI(List<String> allCodePaths) { 10818 cleanUp(); 10819 removeDexFiles(allCodePaths, instructionSets); 10820 } 10821 10822 String getPackageName() { 10823 return getAsecPackageName(cid); 10824 } 10825 10826 boolean doPostDeleteLI(boolean delete) { 10827 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10828 final List<String> allCodePaths = getAllCodePaths(); 10829 boolean mounted = PackageHelper.isContainerMounted(cid); 10830 if (mounted) { 10831 // Unmount first 10832 if (PackageHelper.unMountSdDir(cid)) { 10833 mounted = false; 10834 } 10835 } 10836 if (!mounted && delete) { 10837 cleanUpResourcesLI(allCodePaths); 10838 } 10839 return !mounted; 10840 } 10841 10842 @Override 10843 int doPreCopy() { 10844 if (isFwdLocked()) { 10845 if (!PackageHelper.fixSdPermissions(cid, 10846 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10847 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10848 } 10849 } 10850 10851 return PackageManager.INSTALL_SUCCEEDED; 10852 } 10853 10854 @Override 10855 int doPostCopy(int uid) { 10856 if (isFwdLocked()) { 10857 if (uid < Process.FIRST_APPLICATION_UID 10858 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10859 RES_FILE_NAME)) { 10860 Slog.e(TAG, "Failed to finalize " + cid); 10861 PackageHelper.destroySdDir(cid); 10862 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10863 } 10864 } 10865 10866 return PackageManager.INSTALL_SUCCEEDED; 10867 } 10868 } 10869 10870 /** 10871 * Logic to handle movement of existing installed applications. 10872 */ 10873 class MoveInstallArgs extends InstallArgs { 10874 private File codeFile; 10875 private File resourceFile; 10876 10877 /** New install */ 10878 MoveInstallArgs(InstallParams params) { 10879 super(params.origin, params.move, params.observer, params.installFlags, 10880 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10881 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10882 } 10883 10884 int copyApk(IMediaContainerService imcs, boolean temp) { 10885 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10886 + move.fromUuid + " to " + move.toUuid); 10887 synchronized (mInstaller) { 10888 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10889 move.dataAppName, move.appId, move.seinfo) != 0) { 10890 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10891 } 10892 } 10893 10894 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10895 resourceFile = codeFile; 10896 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10897 10898 return PackageManager.INSTALL_SUCCEEDED; 10899 } 10900 10901 int doPreInstall(int status) { 10902 if (status != PackageManager.INSTALL_SUCCEEDED) { 10903 cleanUp(); 10904 } 10905 return status; 10906 } 10907 10908 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10909 if (status != PackageManager.INSTALL_SUCCEEDED) { 10910 cleanUp(); 10911 return false; 10912 } 10913 10914 // Reflect the move in app info 10915 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10916 pkg.applicationInfo.setCodePath(pkg.codePath); 10917 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10918 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10919 pkg.applicationInfo.setResourcePath(pkg.codePath); 10920 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10921 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10922 10923 return true; 10924 } 10925 10926 int doPostInstall(int status, int uid) { 10927 if (status != PackageManager.INSTALL_SUCCEEDED) { 10928 cleanUp(); 10929 } 10930 return status; 10931 } 10932 10933 @Override 10934 String getCodePath() { 10935 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10936 } 10937 10938 @Override 10939 String getResourcePath() { 10940 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10941 } 10942 10943 private boolean cleanUp() { 10944 if (codeFile == null || !codeFile.exists()) { 10945 return false; 10946 } 10947 10948 if (codeFile.isDirectory()) { 10949 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10950 } else { 10951 codeFile.delete(); 10952 } 10953 10954 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10955 resourceFile.delete(); 10956 } 10957 10958 return true; 10959 } 10960 10961 void cleanUpResourcesLI() { 10962 cleanUp(); 10963 } 10964 10965 boolean doPostDeleteLI(boolean delete) { 10966 // XXX err, shouldn't we respect the delete flag? 10967 cleanUpResourcesLI(); 10968 return true; 10969 } 10970 } 10971 10972 static String getAsecPackageName(String packageCid) { 10973 int idx = packageCid.lastIndexOf("-"); 10974 if (idx == -1) { 10975 return packageCid; 10976 } 10977 return packageCid.substring(0, idx); 10978 } 10979 10980 // Utility method used to create code paths based on package name and available index. 10981 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10982 String idxStr = ""; 10983 int idx = 1; 10984 // Fall back to default value of idx=1 if prefix is not 10985 // part of oldCodePath 10986 if (oldCodePath != null) { 10987 String subStr = oldCodePath; 10988 // Drop the suffix right away 10989 if (suffix != null && subStr.endsWith(suffix)) { 10990 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10991 } 10992 // If oldCodePath already contains prefix find out the 10993 // ending index to either increment or decrement. 10994 int sidx = subStr.lastIndexOf(prefix); 10995 if (sidx != -1) { 10996 subStr = subStr.substring(sidx + prefix.length()); 10997 if (subStr != null) { 10998 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10999 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11000 } 11001 try { 11002 idx = Integer.parseInt(subStr); 11003 if (idx <= 1) { 11004 idx++; 11005 } else { 11006 idx--; 11007 } 11008 } catch(NumberFormatException e) { 11009 } 11010 } 11011 } 11012 } 11013 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11014 return prefix + idxStr; 11015 } 11016 11017 private File getNextCodePath(File targetDir, String packageName) { 11018 int suffix = 1; 11019 File result; 11020 do { 11021 result = new File(targetDir, packageName + "-" + suffix); 11022 suffix++; 11023 } while (result.exists()); 11024 return result; 11025 } 11026 11027 // Utility method that returns the relative package path with respect 11028 // to the installation directory. Like say for /data/data/com.test-1.apk 11029 // string com.test-1 is returned. 11030 static String deriveCodePathName(String codePath) { 11031 if (codePath == null) { 11032 return null; 11033 } 11034 final File codeFile = new File(codePath); 11035 final String name = codeFile.getName(); 11036 if (codeFile.isDirectory()) { 11037 return name; 11038 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11039 final int lastDot = name.lastIndexOf('.'); 11040 return name.substring(0, lastDot); 11041 } else { 11042 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11043 return null; 11044 } 11045 } 11046 11047 class PackageInstalledInfo { 11048 String name; 11049 int uid; 11050 // The set of users that originally had this package installed. 11051 int[] origUsers; 11052 // The set of users that now have this package installed. 11053 int[] newUsers; 11054 PackageParser.Package pkg; 11055 int returnCode; 11056 String returnMsg; 11057 PackageRemovedInfo removedInfo; 11058 11059 public void setError(int code, String msg) { 11060 returnCode = code; 11061 returnMsg = msg; 11062 Slog.w(TAG, msg); 11063 } 11064 11065 public void setError(String msg, PackageParserException e) { 11066 returnCode = e.error; 11067 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11068 Slog.w(TAG, msg, e); 11069 } 11070 11071 public void setError(String msg, PackageManagerException e) { 11072 returnCode = e.error; 11073 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11074 Slog.w(TAG, msg, e); 11075 } 11076 11077 // In some error cases we want to convey more info back to the observer 11078 String origPackage; 11079 String origPermission; 11080 } 11081 11082 /* 11083 * Install a non-existing package. 11084 */ 11085 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11086 UserHandle user, String installerPackageName, String volumeUuid, 11087 PackageInstalledInfo res) { 11088 // Remember this for later, in case we need to rollback this install 11089 String pkgName = pkg.packageName; 11090 11091 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11092 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11093 UserHandle.USER_OWNER).exists(); 11094 synchronized(mPackages) { 11095 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11096 // A package with the same name is already installed, though 11097 // it has been renamed to an older name. The package we 11098 // are trying to install should be installed as an update to 11099 // the existing one, but that has not been requested, so bail. 11100 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11101 + " without first uninstalling package running as " 11102 + mSettings.mRenamedPackages.get(pkgName)); 11103 return; 11104 } 11105 if (mPackages.containsKey(pkgName)) { 11106 // Don't allow installation over an existing package with the same name. 11107 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11108 + " without first uninstalling."); 11109 return; 11110 } 11111 } 11112 11113 try { 11114 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11115 System.currentTimeMillis(), user); 11116 11117 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11118 // delete the partially installed application. the data directory will have to be 11119 // restored if it was already existing 11120 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11121 // remove package from internal structures. Note that we want deletePackageX to 11122 // delete the package data and cache directories that it created in 11123 // scanPackageLocked, unless those directories existed before we even tried to 11124 // install. 11125 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11126 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11127 res.removedInfo, true); 11128 } 11129 11130 } catch (PackageManagerException e) { 11131 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11132 } 11133 } 11134 11135 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11136 // Upgrade keysets are being used. Determine if new package has a superset of the 11137 // required keys. 11138 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11139 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11140 for (int i = 0; i < upgradeKeySets.length; i++) { 11141 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11142 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11143 return true; 11144 } 11145 } 11146 return false; 11147 } 11148 11149 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11150 UserHandle user, String installerPackageName, String volumeUuid, 11151 PackageInstalledInfo res) { 11152 final PackageParser.Package oldPackage; 11153 final String pkgName = pkg.packageName; 11154 final int[] allUsers; 11155 final boolean[] perUserInstalled; 11156 final boolean weFroze; 11157 11158 // First find the old package info and check signatures 11159 synchronized(mPackages) { 11160 oldPackage = mPackages.get(pkgName); 11161 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11162 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11163 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11164 // default to original signature matching 11165 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11166 != PackageManager.SIGNATURE_MATCH) { 11167 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11168 "New package has a different signature: " + pkgName); 11169 return; 11170 } 11171 } else { 11172 if(!checkUpgradeKeySetLP(ps, pkg)) { 11173 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11174 "New package not signed by keys specified by upgrade-keysets: " 11175 + pkgName); 11176 return; 11177 } 11178 } 11179 11180 // In case of rollback, remember per-user/profile install state 11181 allUsers = sUserManager.getUserIds(); 11182 perUserInstalled = new boolean[allUsers.length]; 11183 for (int i = 0; i < allUsers.length; i++) { 11184 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11185 } 11186 11187 // Mark the app as frozen to prevent launching during the upgrade 11188 // process, and then kill all running instances 11189 if (!ps.frozen) { 11190 ps.frozen = true; 11191 weFroze = true; 11192 } else { 11193 weFroze = false; 11194 } 11195 } 11196 11197 // Now that we're guarded by frozen state, kill app during upgrade 11198 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11199 11200 try { 11201 boolean sysPkg = (isSystemApp(oldPackage)); 11202 if (sysPkg) { 11203 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11204 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11205 } else { 11206 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11207 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11208 } 11209 } finally { 11210 // Regardless of success or failure of upgrade steps above, always 11211 // unfreeze the package if we froze it 11212 if (weFroze) { 11213 unfreezePackage(pkgName); 11214 } 11215 } 11216 } 11217 11218 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11219 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11220 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11221 String volumeUuid, PackageInstalledInfo res) { 11222 String pkgName = deletedPackage.packageName; 11223 boolean deletedPkg = true; 11224 boolean updatedSettings = false; 11225 11226 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11227 + deletedPackage); 11228 long origUpdateTime; 11229 if (pkg.mExtras != null) { 11230 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11231 } else { 11232 origUpdateTime = 0; 11233 } 11234 11235 // First delete the existing package while retaining the data directory 11236 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11237 res.removedInfo, true)) { 11238 // If the existing package wasn't successfully deleted 11239 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11240 deletedPkg = false; 11241 } else { 11242 // Successfully deleted the old package; proceed with replace. 11243 11244 // If deleted package lived in a container, give users a chance to 11245 // relinquish resources before killing. 11246 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11247 if (DEBUG_INSTALL) { 11248 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11249 } 11250 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11251 final ArrayList<String> pkgList = new ArrayList<String>(1); 11252 pkgList.add(deletedPackage.applicationInfo.packageName); 11253 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11254 } 11255 11256 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11257 try { 11258 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11259 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11260 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11261 perUserInstalled, res, user); 11262 updatedSettings = true; 11263 } catch (PackageManagerException e) { 11264 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11265 } 11266 } 11267 11268 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11269 // remove package from internal structures. Note that we want deletePackageX to 11270 // delete the package data and cache directories that it created in 11271 // scanPackageLocked, unless those directories existed before we even tried to 11272 // install. 11273 if(updatedSettings) { 11274 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11275 deletePackageLI( 11276 pkgName, null, true, allUsers, perUserInstalled, 11277 PackageManager.DELETE_KEEP_DATA, 11278 res.removedInfo, true); 11279 } 11280 // Since we failed to install the new package we need to restore the old 11281 // package that we deleted. 11282 if (deletedPkg) { 11283 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11284 File restoreFile = new File(deletedPackage.codePath); 11285 // Parse old package 11286 boolean oldExternal = isExternal(deletedPackage); 11287 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11288 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11289 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11290 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11291 try { 11292 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11293 } catch (PackageManagerException e) { 11294 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11295 + e.getMessage()); 11296 return; 11297 } 11298 // Restore of old package succeeded. Update permissions. 11299 // writer 11300 synchronized (mPackages) { 11301 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11302 UPDATE_PERMISSIONS_ALL); 11303 // can downgrade to reader 11304 mSettings.writeLPr(); 11305 } 11306 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11307 } 11308 } 11309 } 11310 11311 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11312 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11313 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11314 String volumeUuid, PackageInstalledInfo res) { 11315 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11316 + ", old=" + deletedPackage); 11317 boolean disabledSystem = false; 11318 boolean updatedSettings = false; 11319 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11320 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11321 != 0) { 11322 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11323 } 11324 String packageName = deletedPackage.packageName; 11325 if (packageName == null) { 11326 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11327 "Attempt to delete null packageName."); 11328 return; 11329 } 11330 PackageParser.Package oldPkg; 11331 PackageSetting oldPkgSetting; 11332 // reader 11333 synchronized (mPackages) { 11334 oldPkg = mPackages.get(packageName); 11335 oldPkgSetting = mSettings.mPackages.get(packageName); 11336 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11337 (oldPkgSetting == null)) { 11338 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11339 "Couldn't find package:" + packageName + " information"); 11340 return; 11341 } 11342 } 11343 11344 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11345 res.removedInfo.removedPackage = packageName; 11346 // Remove existing system package 11347 removePackageLI(oldPkgSetting, true); 11348 // writer 11349 synchronized (mPackages) { 11350 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11351 if (!disabledSystem && deletedPackage != null) { 11352 // We didn't need to disable the .apk as a current system package, 11353 // which means we are replacing another update that is already 11354 // installed. We need to make sure to delete the older one's .apk. 11355 res.removedInfo.args = createInstallArgsForExisting(0, 11356 deletedPackage.applicationInfo.getCodePath(), 11357 deletedPackage.applicationInfo.getResourcePath(), 11358 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11359 } else { 11360 res.removedInfo.args = null; 11361 } 11362 } 11363 11364 // Successfully disabled the old package. Now proceed with re-installation 11365 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11366 11367 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11368 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11369 11370 PackageParser.Package newPackage = null; 11371 try { 11372 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11373 if (newPackage.mExtras != null) { 11374 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11375 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11376 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11377 11378 // is the update attempting to change shared user? that isn't going to work... 11379 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11380 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11381 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11382 + " to " + newPkgSetting.sharedUser); 11383 updatedSettings = true; 11384 } 11385 } 11386 11387 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11388 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11389 perUserInstalled, res, user); 11390 updatedSettings = true; 11391 } 11392 11393 } catch (PackageManagerException e) { 11394 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11395 } 11396 11397 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11398 // Re installation failed. Restore old information 11399 // Remove new pkg information 11400 if (newPackage != null) { 11401 removeInstalledPackageLI(newPackage, true); 11402 } 11403 // Add back the old system package 11404 try { 11405 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11406 } catch (PackageManagerException e) { 11407 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11408 } 11409 // Restore the old system information in Settings 11410 synchronized (mPackages) { 11411 if (disabledSystem) { 11412 mSettings.enableSystemPackageLPw(packageName); 11413 } 11414 if (updatedSettings) { 11415 mSettings.setInstallerPackageName(packageName, 11416 oldPkgSetting.installerPackageName); 11417 } 11418 mSettings.writeLPr(); 11419 } 11420 } 11421 } 11422 11423 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11424 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11425 UserHandle user) { 11426 String pkgName = newPackage.packageName; 11427 synchronized (mPackages) { 11428 //write settings. the installStatus will be incomplete at this stage. 11429 //note that the new package setting would have already been 11430 //added to mPackages. It hasn't been persisted yet. 11431 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11432 mSettings.writeLPr(); 11433 } 11434 11435 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11436 11437 synchronized (mPackages) { 11438 updatePermissionsLPw(newPackage.packageName, newPackage, 11439 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11440 ? UPDATE_PERMISSIONS_ALL : 0)); 11441 // For system-bundled packages, we assume that installing an upgraded version 11442 // of the package implies that the user actually wants to run that new code, 11443 // so we enable the package. 11444 PackageSetting ps = mSettings.mPackages.get(pkgName); 11445 if (ps != null) { 11446 if (isSystemApp(newPackage)) { 11447 // NB: implicit assumption that system package upgrades apply to all users 11448 if (DEBUG_INSTALL) { 11449 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11450 } 11451 if (res.origUsers != null) { 11452 for (int userHandle : res.origUsers) { 11453 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11454 userHandle, installerPackageName); 11455 } 11456 } 11457 // Also convey the prior install/uninstall state 11458 if (allUsers != null && perUserInstalled != null) { 11459 for (int i = 0; i < allUsers.length; i++) { 11460 if (DEBUG_INSTALL) { 11461 Slog.d(TAG, " user " + allUsers[i] 11462 + " => " + perUserInstalled[i]); 11463 } 11464 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11465 } 11466 // these install state changes will be persisted in the 11467 // upcoming call to mSettings.writeLPr(). 11468 } 11469 } 11470 // It's implied that when a user requests installation, they want the app to be 11471 // installed and enabled. 11472 int userId = user.getIdentifier(); 11473 if (userId != UserHandle.USER_ALL) { 11474 ps.setInstalled(true, userId); 11475 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11476 } 11477 } 11478 res.name = pkgName; 11479 res.uid = newPackage.applicationInfo.uid; 11480 res.pkg = newPackage; 11481 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11482 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11483 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11484 //to update install status 11485 mSettings.writeLPr(); 11486 } 11487 } 11488 11489 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11490 final int installFlags = args.installFlags; 11491 final String installerPackageName = args.installerPackageName; 11492 final String volumeUuid = args.volumeUuid; 11493 final File tmpPackageFile = new File(args.getCodePath()); 11494 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11495 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11496 || (args.volumeUuid != null)); 11497 boolean replace = false; 11498 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11499 // Result object to be returned 11500 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11501 11502 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11503 // Retrieve PackageSettings and parse package 11504 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11505 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11506 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11507 PackageParser pp = new PackageParser(); 11508 pp.setSeparateProcesses(mSeparateProcesses); 11509 pp.setDisplayMetrics(mMetrics); 11510 11511 final PackageParser.Package pkg; 11512 try { 11513 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11514 } catch (PackageParserException e) { 11515 res.setError("Failed parse during installPackageLI", e); 11516 return; 11517 } 11518 11519 // Mark that we have an install time CPU ABI override. 11520 pkg.cpuAbiOverride = args.abiOverride; 11521 11522 String pkgName = res.name = pkg.packageName; 11523 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11524 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11525 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11526 return; 11527 } 11528 } 11529 11530 try { 11531 pp.collectCertificates(pkg, parseFlags); 11532 pp.collectManifestDigest(pkg); 11533 } catch (PackageParserException e) { 11534 res.setError("Failed collect during installPackageLI", e); 11535 return; 11536 } 11537 11538 /* If the installer passed in a manifest digest, compare it now. */ 11539 if (args.manifestDigest != null) { 11540 if (DEBUG_INSTALL) { 11541 final String parsedManifest = pkg.manifestDigest == null ? "null" 11542 : pkg.manifestDigest.toString(); 11543 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11544 + parsedManifest); 11545 } 11546 11547 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11548 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11549 return; 11550 } 11551 } else if (DEBUG_INSTALL) { 11552 final String parsedManifest = pkg.manifestDigest == null 11553 ? "null" : pkg.manifestDigest.toString(); 11554 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11555 } 11556 11557 // Get rid of all references to package scan path via parser. 11558 pp = null; 11559 String oldCodePath = null; 11560 boolean systemApp = false; 11561 synchronized (mPackages) { 11562 // Check if installing already existing package 11563 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11564 String oldName = mSettings.mRenamedPackages.get(pkgName); 11565 if (pkg.mOriginalPackages != null 11566 && pkg.mOriginalPackages.contains(oldName) 11567 && mPackages.containsKey(oldName)) { 11568 // This package is derived from an original package, 11569 // and this device has been updating from that original 11570 // name. We must continue using the original name, so 11571 // rename the new package here. 11572 pkg.setPackageName(oldName); 11573 pkgName = pkg.packageName; 11574 replace = true; 11575 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11576 + oldName + " pkgName=" + pkgName); 11577 } else if (mPackages.containsKey(pkgName)) { 11578 // This package, under its official name, already exists 11579 // on the device; we should replace it. 11580 replace = true; 11581 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11582 } 11583 11584 // Prevent apps opting out from runtime permissions 11585 if (replace) { 11586 PackageParser.Package oldPackage = mPackages.get(pkgName); 11587 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11588 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11589 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11590 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11591 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11592 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11593 + " doesn't support runtime permissions but the old" 11594 + " target SDK " + oldTargetSdk + " does."); 11595 return; 11596 } 11597 } 11598 } 11599 11600 PackageSetting ps = mSettings.mPackages.get(pkgName); 11601 if (ps != null) { 11602 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11603 11604 // Quick sanity check that we're signed correctly if updating; 11605 // we'll check this again later when scanning, but we want to 11606 // bail early here before tripping over redefined permissions. 11607 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11608 try { 11609 verifySignaturesLP(ps, pkg); 11610 } catch (PackageManagerException e) { 11611 res.setError(e.error, e.getMessage()); 11612 return; 11613 } 11614 } else { 11615 if (!checkUpgradeKeySetLP(ps, pkg)) { 11616 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11617 + pkg.packageName + " upgrade keys do not match the " 11618 + "previously installed version"); 11619 return; 11620 } 11621 } 11622 11623 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11624 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11625 systemApp = (ps.pkg.applicationInfo.flags & 11626 ApplicationInfo.FLAG_SYSTEM) != 0; 11627 } 11628 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11629 } 11630 11631 // Check whether the newly-scanned package wants to define an already-defined perm 11632 int N = pkg.permissions.size(); 11633 for (int i = N-1; i >= 0; i--) { 11634 PackageParser.Permission perm = pkg.permissions.get(i); 11635 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11636 if (bp != null) { 11637 // If the defining package is signed with our cert, it's okay. This 11638 // also includes the "updating the same package" case, of course. 11639 // "updating same package" could also involve key-rotation. 11640 final boolean sigsOk; 11641 if (!bp.sourcePackage.equals(pkg.packageName) 11642 || !(bp.packageSetting instanceof PackageSetting) 11643 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11644 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11645 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11646 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11647 } else { 11648 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11649 } 11650 if (!sigsOk) { 11651 // If the owning package is the system itself, we log but allow 11652 // install to proceed; we fail the install on all other permission 11653 // redefinitions. 11654 if (!bp.sourcePackage.equals("android")) { 11655 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11656 + pkg.packageName + " attempting to redeclare permission " 11657 + perm.info.name + " already owned by " + bp.sourcePackage); 11658 res.origPermission = perm.info.name; 11659 res.origPackage = bp.sourcePackage; 11660 return; 11661 } else { 11662 Slog.w(TAG, "Package " + pkg.packageName 11663 + " attempting to redeclare system permission " 11664 + perm.info.name + "; ignoring new declaration"); 11665 pkg.permissions.remove(i); 11666 } 11667 } 11668 } 11669 } 11670 11671 } 11672 11673 if (systemApp && onExternal) { 11674 // Disable updates to system apps on sdcard 11675 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11676 "Cannot install updates to system apps on sdcard"); 11677 return; 11678 } 11679 11680 if (args.move != null) { 11681 // We did an in-place move, so dex is ready to roll 11682 scanFlags |= SCAN_NO_DEX; 11683 scanFlags |= SCAN_MOVE; 11684 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11685 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11686 scanFlags |= SCAN_NO_DEX; 11687 11688 try { 11689 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11690 true /* extract libs */); 11691 } catch (PackageManagerException pme) { 11692 Slog.e(TAG, "Error deriving application ABI", pme); 11693 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11694 return; 11695 } 11696 11697 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11698 int result = mPackageDexOptimizer 11699 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11700 false /* defer */, false /* inclDependencies */); 11701 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11702 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11703 return; 11704 } 11705 } 11706 11707 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11708 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11709 return; 11710 } 11711 11712 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11713 11714 if (replace) { 11715 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11716 installerPackageName, volumeUuid, res); 11717 } else { 11718 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11719 args.user, installerPackageName, volumeUuid, res); 11720 } 11721 synchronized (mPackages) { 11722 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11723 if (ps != null) { 11724 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11725 } 11726 } 11727 } 11728 11729 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11730 if (mIntentFilterVerifierComponent == null) { 11731 Slog.w(TAG, "No IntentFilter verification will not be done as " 11732 + "there is no IntentFilterVerifier available!"); 11733 return; 11734 } 11735 11736 final int verifierUid = getPackageUid( 11737 mIntentFilterVerifierComponent.getPackageName(), 11738 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11739 11740 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11741 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11742 msg.obj = pkg; 11743 msg.arg1 = userId; 11744 msg.arg2 = verifierUid; 11745 11746 mHandler.sendMessage(msg); 11747 } 11748 11749 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11750 PackageParser.Package pkg) { 11751 int size = pkg.activities.size(); 11752 if (size == 0) { 11753 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11754 "No activity, so no need to verify any IntentFilter!"); 11755 return; 11756 } 11757 11758 final boolean hasDomainURLs = hasDomainURLs(pkg); 11759 if (!hasDomainURLs) { 11760 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11761 "No domain URLs, so no need to verify any IntentFilter!"); 11762 return; 11763 } 11764 11765 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11766 + " if any IntentFilter from the " + size 11767 + " Activities needs verification ..."); 11768 11769 final int verificationId = mIntentFilterVerificationToken++; 11770 int count = 0; 11771 final String packageName = pkg.packageName; 11772 ArrayList<String> allHosts = new ArrayList<>(); 11773 11774 synchronized (mPackages) { 11775 for (PackageParser.Activity a : pkg.activities) { 11776 for (ActivityIntentInfo filter : a.intents) { 11777 boolean needsFilterVerification = filter.needsVerification(); 11778 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11779 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11780 "Verification needed for IntentFilter:" + filter.toString()); 11781 mIntentFilterVerifier.addOneIntentFilterVerification( 11782 verifierUid, userId, verificationId, filter, packageName); 11783 count++; 11784 } else if (!needsFilterVerification) { 11785 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11786 "No verification needed for IntentFilter:" + filter.toString()); 11787 if (hasValidDomains(filter)) { 11788 ArrayList<String> hosts = filter.getHostsList(); 11789 if (hosts.size() > 0) { 11790 allHosts.addAll(hosts); 11791 } else { 11792 if (allHosts.isEmpty()) { 11793 allHosts.add("*"); 11794 } 11795 } 11796 } 11797 } else { 11798 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11799 "Verification already done for IntentFilter:" + filter.toString()); 11800 } 11801 } 11802 } 11803 } 11804 11805 if (count > 0) { 11806 mIntentFilterVerifier.startVerifications(userId); 11807 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Started " + count 11808 + " IntentFilter verification" + (count > 1 ? "s" : "") 11809 + " for userId:" + userId + "!"); 11810 } else { 11811 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11812 "No need to start any IntentFilter verification!"); 11813 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11814 packageName, allHosts) != null) { 11815 scheduleWriteSettingsLocked(); 11816 } 11817 } 11818 } 11819 11820 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11821 final ComponentName cn = filter.activity.getComponentName(); 11822 final String packageName = cn.getPackageName(); 11823 11824 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11825 packageName); 11826 if (ivi == null) { 11827 return true; 11828 } 11829 int status = ivi.getStatus(); 11830 switch (status) { 11831 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11832 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11833 return true; 11834 11835 default: 11836 // Nothing to do 11837 return false; 11838 } 11839 } 11840 11841 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11842 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11843 || ((pkg.applicationInfo.privateFlags 11844 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11845 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11846 } 11847 11848 private static boolean isMultiArch(PackageSetting ps) { 11849 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11850 } 11851 11852 private static boolean isMultiArch(ApplicationInfo info) { 11853 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11854 } 11855 11856 private static boolean isExternal(PackageParser.Package pkg) { 11857 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11858 } 11859 11860 private static boolean isExternal(PackageSetting ps) { 11861 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11862 } 11863 11864 private static boolean isExternal(ApplicationInfo info) { 11865 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11866 } 11867 11868 private static boolean isSystemApp(PackageParser.Package pkg) { 11869 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11870 } 11871 11872 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11873 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11874 } 11875 11876 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11877 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11878 } 11879 11880 private static boolean isSystemApp(PackageSetting ps) { 11881 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11882 } 11883 11884 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11885 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11886 } 11887 11888 private int packageFlagsToInstallFlags(PackageSetting ps) { 11889 int installFlags = 0; 11890 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11891 // This existing package was an external ASEC install when we have 11892 // the external flag without a UUID 11893 installFlags |= PackageManager.INSTALL_EXTERNAL; 11894 } 11895 if (ps.isForwardLocked()) { 11896 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11897 } 11898 return installFlags; 11899 } 11900 11901 private void deleteTempPackageFiles() { 11902 final FilenameFilter filter = new FilenameFilter() { 11903 public boolean accept(File dir, String name) { 11904 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11905 } 11906 }; 11907 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11908 file.delete(); 11909 } 11910 } 11911 11912 @Override 11913 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11914 int flags) { 11915 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11916 flags); 11917 } 11918 11919 @Override 11920 public void deletePackage(final String packageName, 11921 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11922 mContext.enforceCallingOrSelfPermission( 11923 android.Manifest.permission.DELETE_PACKAGES, null); 11924 final int uid = Binder.getCallingUid(); 11925 if (UserHandle.getUserId(uid) != userId) { 11926 mContext.enforceCallingPermission( 11927 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11928 "deletePackage for user " + userId); 11929 } 11930 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11931 try { 11932 observer.onPackageDeleted(packageName, 11933 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11934 } catch (RemoteException re) { 11935 } 11936 return; 11937 } 11938 11939 boolean uninstallBlocked = false; 11940 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11941 int[] users = sUserManager.getUserIds(); 11942 for (int i = 0; i < users.length; ++i) { 11943 if (getBlockUninstallForUser(packageName, users[i])) { 11944 uninstallBlocked = true; 11945 break; 11946 } 11947 } 11948 } else { 11949 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11950 } 11951 if (uninstallBlocked) { 11952 try { 11953 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11954 null); 11955 } catch (RemoteException re) { 11956 } 11957 return; 11958 } 11959 11960 if (DEBUG_REMOVE) { 11961 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11962 } 11963 // Queue up an async operation since the package deletion may take a little while. 11964 mHandler.post(new Runnable() { 11965 public void run() { 11966 mHandler.removeCallbacks(this); 11967 final int returnCode = deletePackageX(packageName, userId, flags); 11968 if (observer != null) { 11969 try { 11970 observer.onPackageDeleted(packageName, returnCode, null); 11971 } catch (RemoteException e) { 11972 Log.i(TAG, "Observer no longer exists."); 11973 } //end catch 11974 } //end if 11975 } //end run 11976 }); 11977 } 11978 11979 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11980 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11981 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11982 try { 11983 if (dpm != null) { 11984 if (dpm.isDeviceOwner(packageName)) { 11985 return true; 11986 } 11987 int[] users; 11988 if (userId == UserHandle.USER_ALL) { 11989 users = sUserManager.getUserIds(); 11990 } else { 11991 users = new int[]{userId}; 11992 } 11993 for (int i = 0; i < users.length; ++i) { 11994 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11995 return true; 11996 } 11997 } 11998 } 11999 } catch (RemoteException e) { 12000 } 12001 return false; 12002 } 12003 12004 /** 12005 * This method is an internal method that could be get invoked either 12006 * to delete an installed package or to clean up a failed installation. 12007 * After deleting an installed package, a broadcast is sent to notify any 12008 * listeners that the package has been installed. For cleaning up a failed 12009 * installation, the broadcast is not necessary since the package's 12010 * installation wouldn't have sent the initial broadcast either 12011 * The key steps in deleting a package are 12012 * deleting the package information in internal structures like mPackages, 12013 * deleting the packages base directories through installd 12014 * updating mSettings to reflect current status 12015 * persisting settings for later use 12016 * sending a broadcast if necessary 12017 */ 12018 private int deletePackageX(String packageName, int userId, int flags) { 12019 final PackageRemovedInfo info = new PackageRemovedInfo(); 12020 final boolean res; 12021 12022 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12023 ? UserHandle.ALL : new UserHandle(userId); 12024 12025 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12026 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12027 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12028 } 12029 12030 boolean removedForAllUsers = false; 12031 boolean systemUpdate = false; 12032 12033 // for the uninstall-updates case and restricted profiles, remember the per- 12034 // userhandle installed state 12035 int[] allUsers; 12036 boolean[] perUserInstalled; 12037 synchronized (mPackages) { 12038 PackageSetting ps = mSettings.mPackages.get(packageName); 12039 allUsers = sUserManager.getUserIds(); 12040 perUserInstalled = new boolean[allUsers.length]; 12041 for (int i = 0; i < allUsers.length; i++) { 12042 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12043 } 12044 } 12045 12046 synchronized (mInstallLock) { 12047 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12048 res = deletePackageLI(packageName, removeForUser, 12049 true, allUsers, perUserInstalled, 12050 flags | REMOVE_CHATTY, info, true); 12051 systemUpdate = info.isRemovedPackageSystemUpdate; 12052 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12053 removedForAllUsers = true; 12054 } 12055 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12056 + " removedForAllUsers=" + removedForAllUsers); 12057 } 12058 12059 if (res) { 12060 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12061 12062 // If the removed package was a system update, the old system package 12063 // was re-enabled; we need to broadcast this information 12064 if (systemUpdate) { 12065 Bundle extras = new Bundle(1); 12066 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12067 ? info.removedAppId : info.uid); 12068 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12069 12070 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12071 extras, null, null, null); 12072 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12073 extras, null, null, null); 12074 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12075 null, packageName, null, null); 12076 } 12077 } 12078 // Force a gc here. 12079 Runtime.getRuntime().gc(); 12080 // Delete the resources here after sending the broadcast to let 12081 // other processes clean up before deleting resources. 12082 if (info.args != null) { 12083 synchronized (mInstallLock) { 12084 info.args.doPostDeleteLI(true); 12085 } 12086 } 12087 12088 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12089 } 12090 12091 class PackageRemovedInfo { 12092 String removedPackage; 12093 int uid = -1; 12094 int removedAppId = -1; 12095 int[] removedUsers = null; 12096 boolean isRemovedPackageSystemUpdate = false; 12097 // Clean up resources deleted packages. 12098 InstallArgs args = null; 12099 12100 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12101 Bundle extras = new Bundle(1); 12102 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12103 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12104 if (replacing) { 12105 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12106 } 12107 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12108 if (removedPackage != null) { 12109 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12110 extras, null, null, removedUsers); 12111 if (fullRemove && !replacing) { 12112 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12113 extras, null, null, removedUsers); 12114 } 12115 } 12116 if (removedAppId >= 0) { 12117 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12118 removedUsers); 12119 } 12120 } 12121 } 12122 12123 /* 12124 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12125 * flag is not set, the data directory is removed as well. 12126 * make sure this flag is set for partially installed apps. If not its meaningless to 12127 * delete a partially installed application. 12128 */ 12129 private void removePackageDataLI(PackageSetting ps, 12130 int[] allUserHandles, boolean[] perUserInstalled, 12131 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12132 String packageName = ps.name; 12133 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12134 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12135 // Retrieve object to delete permissions for shared user later on 12136 final PackageSetting deletedPs; 12137 // reader 12138 synchronized (mPackages) { 12139 deletedPs = mSettings.mPackages.get(packageName); 12140 if (outInfo != null) { 12141 outInfo.removedPackage = packageName; 12142 outInfo.removedUsers = deletedPs != null 12143 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12144 : null; 12145 } 12146 } 12147 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12148 removeDataDirsLI(ps.volumeUuid, packageName); 12149 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12150 } 12151 // writer 12152 synchronized (mPackages) { 12153 if (deletedPs != null) { 12154 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12155 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12156 clearDefaultBrowserIfNeeded(packageName); 12157 if (outInfo != null) { 12158 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12159 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12160 } 12161 updatePermissionsLPw(deletedPs.name, null, 0); 12162 if (deletedPs.sharedUser != null) { 12163 // Remove permissions associated with package. Since runtime 12164 // permissions are per user we have to kill the removed package 12165 // or packages running under the shared user of the removed 12166 // package if revoking the permissions requested only by the removed 12167 // package is successful and this causes a change in gids. 12168 for (int userId : UserManagerService.getInstance().getUserIds()) { 12169 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12170 userId); 12171 if (userIdToKill == UserHandle.USER_ALL 12172 || userIdToKill >= UserHandle.USER_OWNER) { 12173 // If gids changed for this user, kill all affected packages. 12174 mHandler.post(new Runnable() { 12175 @Override 12176 public void run() { 12177 // This has to happen with no lock held. 12178 killSettingPackagesForUser(deletedPs, userIdToKill, 12179 KILL_APP_REASON_GIDS_CHANGED); 12180 } 12181 }); 12182 break; 12183 } 12184 } 12185 } 12186 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12187 } 12188 // make sure to preserve per-user disabled state if this removal was just 12189 // a downgrade of a system app to the factory package 12190 if (allUserHandles != null && perUserInstalled != null) { 12191 if (DEBUG_REMOVE) { 12192 Slog.d(TAG, "Propagating install state across downgrade"); 12193 } 12194 for (int i = 0; i < allUserHandles.length; i++) { 12195 if (DEBUG_REMOVE) { 12196 Slog.d(TAG, " user " + allUserHandles[i] 12197 + " => " + perUserInstalled[i]); 12198 } 12199 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12200 } 12201 } 12202 } 12203 // can downgrade to reader 12204 if (writeSettings) { 12205 // Save settings now 12206 mSettings.writeLPr(); 12207 } 12208 } 12209 if (outInfo != null) { 12210 // A user ID was deleted here. Go through all users and remove it 12211 // from KeyStore. 12212 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12213 } 12214 } 12215 12216 static boolean locationIsPrivileged(File path) { 12217 try { 12218 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12219 .getCanonicalPath(); 12220 return path.getCanonicalPath().startsWith(privilegedAppDir); 12221 } catch (IOException e) { 12222 Slog.e(TAG, "Unable to access code path " + path); 12223 } 12224 return false; 12225 } 12226 12227 /* 12228 * Tries to delete system package. 12229 */ 12230 private boolean deleteSystemPackageLI(PackageSetting newPs, 12231 int[] allUserHandles, boolean[] perUserInstalled, 12232 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12233 final boolean applyUserRestrictions 12234 = (allUserHandles != null) && (perUserInstalled != null); 12235 PackageSetting disabledPs = null; 12236 // Confirm if the system package has been updated 12237 // An updated system app can be deleted. This will also have to restore 12238 // the system pkg from system partition 12239 // reader 12240 synchronized (mPackages) { 12241 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12242 } 12243 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12244 + " disabledPs=" + disabledPs); 12245 if (disabledPs == null) { 12246 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12247 return false; 12248 } else if (DEBUG_REMOVE) { 12249 Slog.d(TAG, "Deleting system pkg from data partition"); 12250 } 12251 if (DEBUG_REMOVE) { 12252 if (applyUserRestrictions) { 12253 Slog.d(TAG, "Remembering install states:"); 12254 for (int i = 0; i < allUserHandles.length; i++) { 12255 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12256 } 12257 } 12258 } 12259 // Delete the updated package 12260 outInfo.isRemovedPackageSystemUpdate = true; 12261 if (disabledPs.versionCode < newPs.versionCode) { 12262 // Delete data for downgrades 12263 flags &= ~PackageManager.DELETE_KEEP_DATA; 12264 } else { 12265 // Preserve data by setting flag 12266 flags |= PackageManager.DELETE_KEEP_DATA; 12267 } 12268 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12269 allUserHandles, perUserInstalled, outInfo, writeSettings); 12270 if (!ret) { 12271 return false; 12272 } 12273 // writer 12274 synchronized (mPackages) { 12275 // Reinstate the old system package 12276 mSettings.enableSystemPackageLPw(newPs.name); 12277 // Remove any native libraries from the upgraded package. 12278 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12279 } 12280 // Install the system package 12281 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12282 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12283 if (locationIsPrivileged(disabledPs.codePath)) { 12284 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12285 } 12286 12287 final PackageParser.Package newPkg; 12288 try { 12289 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12290 } catch (PackageManagerException e) { 12291 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12292 return false; 12293 } 12294 12295 // writer 12296 synchronized (mPackages) { 12297 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12298 updatePermissionsLPw(newPkg.packageName, newPkg, 12299 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12300 if (applyUserRestrictions) { 12301 if (DEBUG_REMOVE) { 12302 Slog.d(TAG, "Propagating install state across reinstall"); 12303 } 12304 for (int i = 0; i < allUserHandles.length; i++) { 12305 if (DEBUG_REMOVE) { 12306 Slog.d(TAG, " user " + allUserHandles[i] 12307 + " => " + perUserInstalled[i]); 12308 } 12309 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12310 } 12311 // Regardless of writeSettings we need to ensure that this restriction 12312 // state propagation is persisted 12313 mSettings.writeAllUsersPackageRestrictionsLPr(); 12314 } 12315 // can downgrade to reader here 12316 if (writeSettings) { 12317 mSettings.writeLPr(); 12318 } 12319 } 12320 return true; 12321 } 12322 12323 private boolean deleteInstalledPackageLI(PackageSetting ps, 12324 boolean deleteCodeAndResources, int flags, 12325 int[] allUserHandles, boolean[] perUserInstalled, 12326 PackageRemovedInfo outInfo, boolean writeSettings) { 12327 if (outInfo != null) { 12328 outInfo.uid = ps.appId; 12329 } 12330 12331 // Delete package data from internal structures and also remove data if flag is set 12332 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12333 12334 // Delete application code and resources 12335 if (deleteCodeAndResources && (outInfo != null)) { 12336 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12337 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12338 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12339 } 12340 return true; 12341 } 12342 12343 @Override 12344 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12345 int userId) { 12346 mContext.enforceCallingOrSelfPermission( 12347 android.Manifest.permission.DELETE_PACKAGES, null); 12348 synchronized (mPackages) { 12349 PackageSetting ps = mSettings.mPackages.get(packageName); 12350 if (ps == null) { 12351 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12352 return false; 12353 } 12354 if (!ps.getInstalled(userId)) { 12355 // Can't block uninstall for an app that is not installed or enabled. 12356 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12357 return false; 12358 } 12359 ps.setBlockUninstall(blockUninstall, userId); 12360 mSettings.writePackageRestrictionsLPr(userId); 12361 } 12362 return true; 12363 } 12364 12365 @Override 12366 public boolean getBlockUninstallForUser(String packageName, int userId) { 12367 synchronized (mPackages) { 12368 PackageSetting ps = mSettings.mPackages.get(packageName); 12369 if (ps == null) { 12370 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12371 return false; 12372 } 12373 return ps.getBlockUninstall(userId); 12374 } 12375 } 12376 12377 /* 12378 * This method handles package deletion in general 12379 */ 12380 private boolean deletePackageLI(String packageName, UserHandle user, 12381 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12382 int flags, PackageRemovedInfo outInfo, 12383 boolean writeSettings) { 12384 if (packageName == null) { 12385 Slog.w(TAG, "Attempt to delete null packageName."); 12386 return false; 12387 } 12388 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12389 PackageSetting ps; 12390 boolean dataOnly = false; 12391 int removeUser = -1; 12392 int appId = -1; 12393 synchronized (mPackages) { 12394 ps = mSettings.mPackages.get(packageName); 12395 if (ps == null) { 12396 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12397 return false; 12398 } 12399 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12400 && user.getIdentifier() != UserHandle.USER_ALL) { 12401 // The caller is asking that the package only be deleted for a single 12402 // user. To do this, we just mark its uninstalled state and delete 12403 // its data. If this is a system app, we only allow this to happen if 12404 // they have set the special DELETE_SYSTEM_APP which requests different 12405 // semantics than normal for uninstalling system apps. 12406 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12407 ps.setUserState(user.getIdentifier(), 12408 COMPONENT_ENABLED_STATE_DEFAULT, 12409 false, //installed 12410 true, //stopped 12411 true, //notLaunched 12412 false, //hidden 12413 null, null, null, 12414 false, // blockUninstall 12415 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12416 if (!isSystemApp(ps)) { 12417 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12418 // Other user still have this package installed, so all 12419 // we need to do is clear this user's data and save that 12420 // it is uninstalled. 12421 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12422 removeUser = user.getIdentifier(); 12423 appId = ps.appId; 12424 scheduleWritePackageRestrictionsLocked(removeUser); 12425 } else { 12426 // We need to set it back to 'installed' so the uninstall 12427 // broadcasts will be sent correctly. 12428 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12429 ps.setInstalled(true, user.getIdentifier()); 12430 } 12431 } else { 12432 // This is a system app, so we assume that the 12433 // other users still have this package installed, so all 12434 // we need to do is clear this user's data and save that 12435 // it is uninstalled. 12436 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12437 removeUser = user.getIdentifier(); 12438 appId = ps.appId; 12439 scheduleWritePackageRestrictionsLocked(removeUser); 12440 } 12441 } 12442 } 12443 12444 if (removeUser >= 0) { 12445 // From above, we determined that we are deleting this only 12446 // for a single user. Continue the work here. 12447 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12448 if (outInfo != null) { 12449 outInfo.removedPackage = packageName; 12450 outInfo.removedAppId = appId; 12451 outInfo.removedUsers = new int[] {removeUser}; 12452 } 12453 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12454 removeKeystoreDataIfNeeded(removeUser, appId); 12455 schedulePackageCleaning(packageName, removeUser, false); 12456 synchronized (mPackages) { 12457 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12458 scheduleWritePackageRestrictionsLocked(removeUser); 12459 } 12460 } 12461 return true; 12462 } 12463 12464 if (dataOnly) { 12465 // Delete application data first 12466 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12467 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12468 return true; 12469 } 12470 12471 boolean ret = false; 12472 if (isSystemApp(ps)) { 12473 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12474 // When an updated system application is deleted we delete the existing resources as well and 12475 // fall back to existing code in system partition 12476 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12477 flags, outInfo, writeSettings); 12478 } else { 12479 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12480 // Kill application pre-emptively especially for apps on sd. 12481 killApplication(packageName, ps.appId, "uninstall pkg"); 12482 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12483 allUserHandles, perUserInstalled, 12484 outInfo, writeSettings); 12485 } 12486 12487 return ret; 12488 } 12489 12490 private final class ClearStorageConnection implements ServiceConnection { 12491 IMediaContainerService mContainerService; 12492 12493 @Override 12494 public void onServiceConnected(ComponentName name, IBinder service) { 12495 synchronized (this) { 12496 mContainerService = IMediaContainerService.Stub.asInterface(service); 12497 notifyAll(); 12498 } 12499 } 12500 12501 @Override 12502 public void onServiceDisconnected(ComponentName name) { 12503 } 12504 } 12505 12506 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12507 final boolean mounted; 12508 if (Environment.isExternalStorageEmulated()) { 12509 mounted = true; 12510 } else { 12511 final String status = Environment.getExternalStorageState(); 12512 12513 mounted = status.equals(Environment.MEDIA_MOUNTED) 12514 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12515 } 12516 12517 if (!mounted) { 12518 return; 12519 } 12520 12521 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12522 int[] users; 12523 if (userId == UserHandle.USER_ALL) { 12524 users = sUserManager.getUserIds(); 12525 } else { 12526 users = new int[] { userId }; 12527 } 12528 final ClearStorageConnection conn = new ClearStorageConnection(); 12529 if (mContext.bindServiceAsUser( 12530 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12531 try { 12532 for (int curUser : users) { 12533 long timeout = SystemClock.uptimeMillis() + 5000; 12534 synchronized (conn) { 12535 long now = SystemClock.uptimeMillis(); 12536 while (conn.mContainerService == null && now < timeout) { 12537 try { 12538 conn.wait(timeout - now); 12539 } catch (InterruptedException e) { 12540 } 12541 } 12542 } 12543 if (conn.mContainerService == null) { 12544 return; 12545 } 12546 12547 final UserEnvironment userEnv = new UserEnvironment(curUser); 12548 clearDirectory(conn.mContainerService, 12549 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12550 if (allData) { 12551 clearDirectory(conn.mContainerService, 12552 userEnv.buildExternalStorageAppDataDirs(packageName)); 12553 clearDirectory(conn.mContainerService, 12554 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12555 } 12556 } 12557 } finally { 12558 mContext.unbindService(conn); 12559 } 12560 } 12561 } 12562 12563 @Override 12564 public void clearApplicationUserData(final String packageName, 12565 final IPackageDataObserver observer, final int userId) { 12566 mContext.enforceCallingOrSelfPermission( 12567 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12568 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12569 // Queue up an async operation since the package deletion may take a little while. 12570 mHandler.post(new Runnable() { 12571 public void run() { 12572 mHandler.removeCallbacks(this); 12573 final boolean succeeded; 12574 synchronized (mInstallLock) { 12575 succeeded = clearApplicationUserDataLI(packageName, userId); 12576 } 12577 clearExternalStorageDataSync(packageName, userId, true); 12578 if (succeeded) { 12579 // invoke DeviceStorageMonitor's update method to clear any notifications 12580 DeviceStorageMonitorInternal 12581 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12582 if (dsm != null) { 12583 dsm.checkMemory(); 12584 } 12585 } 12586 if(observer != null) { 12587 try { 12588 observer.onRemoveCompleted(packageName, succeeded); 12589 } catch (RemoteException e) { 12590 Log.i(TAG, "Observer no longer exists."); 12591 } 12592 } //end if observer 12593 } //end run 12594 }); 12595 } 12596 12597 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12598 if (packageName == null) { 12599 Slog.w(TAG, "Attempt to delete null packageName."); 12600 return false; 12601 } 12602 12603 // Try finding details about the requested package 12604 PackageParser.Package pkg; 12605 synchronized (mPackages) { 12606 pkg = mPackages.get(packageName); 12607 if (pkg == null) { 12608 final PackageSetting ps = mSettings.mPackages.get(packageName); 12609 if (ps != null) { 12610 pkg = ps.pkg; 12611 } 12612 } 12613 } 12614 12615 if (pkg == null) { 12616 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12617 } 12618 12619 // Always delete data directories for package, even if we found no other 12620 // record of app. This helps users recover from UID mismatches without 12621 // resorting to a full data wipe. 12622 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12623 if (retCode < 0) { 12624 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12625 return false; 12626 } 12627 12628 if (pkg == null) { 12629 return false; 12630 } 12631 12632 if (pkg != null && pkg.applicationInfo != null) { 12633 final int appId = pkg.applicationInfo.uid; 12634 removeKeystoreDataIfNeeded(userId, appId); 12635 } 12636 12637 // Create a native library symlink only if we have native libraries 12638 // and if the native libraries are 32 bit libraries. We do not provide 12639 // this symlink for 64 bit libraries. 12640 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12641 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12642 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12643 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12644 nativeLibPath, userId) < 0) { 12645 Slog.w(TAG, "Failed linking native library dir"); 12646 return false; 12647 } 12648 } 12649 12650 return true; 12651 } 12652 12653 /** 12654 * Remove entries from the keystore daemon. Will only remove it if the 12655 * {@code appId} is valid. 12656 */ 12657 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12658 if (appId < 0) { 12659 return; 12660 } 12661 12662 final KeyStore keyStore = KeyStore.getInstance(); 12663 if (keyStore != null) { 12664 if (userId == UserHandle.USER_ALL) { 12665 for (final int individual : sUserManager.getUserIds()) { 12666 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12667 } 12668 } else { 12669 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12670 } 12671 } else { 12672 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12673 } 12674 } 12675 12676 @Override 12677 public void deleteApplicationCacheFiles(final String packageName, 12678 final IPackageDataObserver observer) { 12679 mContext.enforceCallingOrSelfPermission( 12680 android.Manifest.permission.DELETE_CACHE_FILES, null); 12681 // Queue up an async operation since the package deletion may take a little while. 12682 final int userId = UserHandle.getCallingUserId(); 12683 mHandler.post(new Runnable() { 12684 public void run() { 12685 mHandler.removeCallbacks(this); 12686 final boolean succeded; 12687 synchronized (mInstallLock) { 12688 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12689 } 12690 clearExternalStorageDataSync(packageName, userId, false); 12691 if (observer != null) { 12692 try { 12693 observer.onRemoveCompleted(packageName, succeded); 12694 } catch (RemoteException e) { 12695 Log.i(TAG, "Observer no longer exists."); 12696 } 12697 } //end if observer 12698 } //end run 12699 }); 12700 } 12701 12702 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12703 if (packageName == null) { 12704 Slog.w(TAG, "Attempt to delete null packageName."); 12705 return false; 12706 } 12707 PackageParser.Package p; 12708 synchronized (mPackages) { 12709 p = mPackages.get(packageName); 12710 } 12711 if (p == null) { 12712 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12713 return false; 12714 } 12715 final ApplicationInfo applicationInfo = p.applicationInfo; 12716 if (applicationInfo == null) { 12717 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12718 return false; 12719 } 12720 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12721 if (retCode < 0) { 12722 Slog.w(TAG, "Couldn't remove cache files for package: " 12723 + packageName + " u" + userId); 12724 return false; 12725 } 12726 return true; 12727 } 12728 12729 @Override 12730 public void getPackageSizeInfo(final String packageName, int userHandle, 12731 final IPackageStatsObserver observer) { 12732 mContext.enforceCallingOrSelfPermission( 12733 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12734 if (packageName == null) { 12735 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12736 } 12737 12738 PackageStats stats = new PackageStats(packageName, userHandle); 12739 12740 /* 12741 * Queue up an async operation since the package measurement may take a 12742 * little while. 12743 */ 12744 Message msg = mHandler.obtainMessage(INIT_COPY); 12745 msg.obj = new MeasureParams(stats, observer); 12746 mHandler.sendMessage(msg); 12747 } 12748 12749 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12750 PackageStats pStats) { 12751 if (packageName == null) { 12752 Slog.w(TAG, "Attempt to get size of null packageName."); 12753 return false; 12754 } 12755 PackageParser.Package p; 12756 boolean dataOnly = false; 12757 String libDirRoot = null; 12758 String asecPath = null; 12759 PackageSetting ps = null; 12760 synchronized (mPackages) { 12761 p = mPackages.get(packageName); 12762 ps = mSettings.mPackages.get(packageName); 12763 if(p == null) { 12764 dataOnly = true; 12765 if((ps == null) || (ps.pkg == null)) { 12766 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12767 return false; 12768 } 12769 p = ps.pkg; 12770 } 12771 if (ps != null) { 12772 libDirRoot = ps.legacyNativeLibraryPathString; 12773 } 12774 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12775 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12776 if (secureContainerId != null) { 12777 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12778 } 12779 } 12780 } 12781 String publicSrcDir = null; 12782 if(!dataOnly) { 12783 final ApplicationInfo applicationInfo = p.applicationInfo; 12784 if (applicationInfo == null) { 12785 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12786 return false; 12787 } 12788 if (p.isForwardLocked()) { 12789 publicSrcDir = applicationInfo.getBaseResourcePath(); 12790 } 12791 } 12792 // TODO: extend to measure size of split APKs 12793 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12794 // not just the first level. 12795 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12796 // just the primary. 12797 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12798 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12799 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12800 if (res < 0) { 12801 return false; 12802 } 12803 12804 // Fix-up for forward-locked applications in ASEC containers. 12805 if (!isExternal(p)) { 12806 pStats.codeSize += pStats.externalCodeSize; 12807 pStats.externalCodeSize = 0L; 12808 } 12809 12810 return true; 12811 } 12812 12813 12814 @Override 12815 public void addPackageToPreferred(String packageName) { 12816 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12817 } 12818 12819 @Override 12820 public void removePackageFromPreferred(String packageName) { 12821 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12822 } 12823 12824 @Override 12825 public List<PackageInfo> getPreferredPackages(int flags) { 12826 return new ArrayList<PackageInfo>(); 12827 } 12828 12829 private int getUidTargetSdkVersionLockedLPr(int uid) { 12830 Object obj = mSettings.getUserIdLPr(uid); 12831 if (obj instanceof SharedUserSetting) { 12832 final SharedUserSetting sus = (SharedUserSetting) obj; 12833 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12834 final Iterator<PackageSetting> it = sus.packages.iterator(); 12835 while (it.hasNext()) { 12836 final PackageSetting ps = it.next(); 12837 if (ps.pkg != null) { 12838 int v = ps.pkg.applicationInfo.targetSdkVersion; 12839 if (v < vers) vers = v; 12840 } 12841 } 12842 return vers; 12843 } else if (obj instanceof PackageSetting) { 12844 final PackageSetting ps = (PackageSetting) obj; 12845 if (ps.pkg != null) { 12846 return ps.pkg.applicationInfo.targetSdkVersion; 12847 } 12848 } 12849 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12850 } 12851 12852 @Override 12853 public void addPreferredActivity(IntentFilter filter, int match, 12854 ComponentName[] set, ComponentName activity, int userId) { 12855 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12856 "Adding preferred"); 12857 } 12858 12859 private void addPreferredActivityInternal(IntentFilter filter, int match, 12860 ComponentName[] set, ComponentName activity, boolean always, int userId, 12861 String opname) { 12862 // writer 12863 int callingUid = Binder.getCallingUid(); 12864 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12865 if (filter.countActions() == 0) { 12866 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12867 return; 12868 } 12869 synchronized (mPackages) { 12870 if (mContext.checkCallingOrSelfPermission( 12871 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12872 != PackageManager.PERMISSION_GRANTED) { 12873 if (getUidTargetSdkVersionLockedLPr(callingUid) 12874 < Build.VERSION_CODES.FROYO) { 12875 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12876 + callingUid); 12877 return; 12878 } 12879 mContext.enforceCallingOrSelfPermission( 12880 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12881 } 12882 12883 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12884 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12885 + userId + ":"); 12886 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12887 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12888 scheduleWritePackageRestrictionsLocked(userId); 12889 } 12890 } 12891 12892 @Override 12893 public void replacePreferredActivity(IntentFilter filter, int match, 12894 ComponentName[] set, ComponentName activity, int userId) { 12895 if (filter.countActions() != 1) { 12896 throw new IllegalArgumentException( 12897 "replacePreferredActivity expects filter to have only 1 action."); 12898 } 12899 if (filter.countDataAuthorities() != 0 12900 || filter.countDataPaths() != 0 12901 || filter.countDataSchemes() > 1 12902 || filter.countDataTypes() != 0) { 12903 throw new IllegalArgumentException( 12904 "replacePreferredActivity expects filter to have no data authorities, " + 12905 "paths, or types; and at most one scheme."); 12906 } 12907 12908 final int callingUid = Binder.getCallingUid(); 12909 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12910 synchronized (mPackages) { 12911 if (mContext.checkCallingOrSelfPermission( 12912 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12913 != PackageManager.PERMISSION_GRANTED) { 12914 if (getUidTargetSdkVersionLockedLPr(callingUid) 12915 < Build.VERSION_CODES.FROYO) { 12916 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12917 + Binder.getCallingUid()); 12918 return; 12919 } 12920 mContext.enforceCallingOrSelfPermission( 12921 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12922 } 12923 12924 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12925 if (pir != null) { 12926 // Get all of the existing entries that exactly match this filter. 12927 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12928 if (existing != null && existing.size() == 1) { 12929 PreferredActivity cur = existing.get(0); 12930 if (DEBUG_PREFERRED) { 12931 Slog.i(TAG, "Checking replace of preferred:"); 12932 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12933 if (!cur.mPref.mAlways) { 12934 Slog.i(TAG, " -- CUR; not mAlways!"); 12935 } else { 12936 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12937 Slog.i(TAG, " -- CUR: mSet=" 12938 + Arrays.toString(cur.mPref.mSetComponents)); 12939 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12940 Slog.i(TAG, " -- NEW: mMatch=" 12941 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12942 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12943 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12944 } 12945 } 12946 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12947 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12948 && cur.mPref.sameSet(set)) { 12949 // Setting the preferred activity to what it happens to be already 12950 if (DEBUG_PREFERRED) { 12951 Slog.i(TAG, "Replacing with same preferred activity " 12952 + cur.mPref.mShortComponent + " for user " 12953 + userId + ":"); 12954 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12955 } 12956 return; 12957 } 12958 } 12959 12960 if (existing != null) { 12961 if (DEBUG_PREFERRED) { 12962 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12963 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12964 } 12965 for (int i = 0; i < existing.size(); i++) { 12966 PreferredActivity pa = existing.get(i); 12967 if (DEBUG_PREFERRED) { 12968 Slog.i(TAG, "Removing existing preferred activity " 12969 + pa.mPref.mComponent + ":"); 12970 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12971 } 12972 pir.removeFilter(pa); 12973 } 12974 } 12975 } 12976 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12977 "Replacing preferred"); 12978 } 12979 } 12980 12981 @Override 12982 public void clearPackagePreferredActivities(String packageName) { 12983 final int uid = Binder.getCallingUid(); 12984 // writer 12985 synchronized (mPackages) { 12986 PackageParser.Package pkg = mPackages.get(packageName); 12987 if (pkg == null || pkg.applicationInfo.uid != uid) { 12988 if (mContext.checkCallingOrSelfPermission( 12989 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12990 != PackageManager.PERMISSION_GRANTED) { 12991 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12992 < Build.VERSION_CODES.FROYO) { 12993 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12994 + Binder.getCallingUid()); 12995 return; 12996 } 12997 mContext.enforceCallingOrSelfPermission( 12998 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12999 } 13000 } 13001 13002 int user = UserHandle.getCallingUserId(); 13003 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13004 scheduleWritePackageRestrictionsLocked(user); 13005 } 13006 } 13007 } 13008 13009 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13010 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13011 ArrayList<PreferredActivity> removed = null; 13012 boolean changed = false; 13013 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13014 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13015 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13016 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13017 continue; 13018 } 13019 Iterator<PreferredActivity> it = pir.filterIterator(); 13020 while (it.hasNext()) { 13021 PreferredActivity pa = it.next(); 13022 // Mark entry for removal only if it matches the package name 13023 // and the entry is of type "always". 13024 if (packageName == null || 13025 (pa.mPref.mComponent.getPackageName().equals(packageName) 13026 && pa.mPref.mAlways)) { 13027 if (removed == null) { 13028 removed = new ArrayList<PreferredActivity>(); 13029 } 13030 removed.add(pa); 13031 } 13032 } 13033 if (removed != null) { 13034 for (int j=0; j<removed.size(); j++) { 13035 PreferredActivity pa = removed.get(j); 13036 pir.removeFilter(pa); 13037 } 13038 changed = true; 13039 } 13040 } 13041 return changed; 13042 } 13043 13044 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13045 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13046 if (userId == UserHandle.USER_ALL) { 13047 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13048 sUserManager.getUserIds())) { 13049 for (int oneUserId : sUserManager.getUserIds()) { 13050 scheduleWritePackageRestrictionsLocked(oneUserId); 13051 } 13052 } 13053 } else { 13054 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13055 scheduleWritePackageRestrictionsLocked(userId); 13056 } 13057 } 13058 } 13059 13060 13061 void clearDefaultBrowserIfNeeded(String packageName) { 13062 for (int oneUserId : sUserManager.getUserIds()) { 13063 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13064 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13065 if (packageName.equals(defaultBrowserPackageName)) { 13066 setDefaultBrowserPackageName(null, oneUserId); 13067 } 13068 } 13069 } 13070 13071 @Override 13072 public void resetPreferredActivities(int userId) { 13073 /* TODO: Actually use userId. Why is it being passed in? */ 13074 mContext.enforceCallingOrSelfPermission( 13075 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13076 // writer 13077 synchronized (mPackages) { 13078 int user = UserHandle.getCallingUserId(); 13079 clearPackagePreferredActivitiesLPw(null, user); 13080 mSettings.readDefaultPreferredAppsLPw(this, user); 13081 scheduleWritePackageRestrictionsLocked(user); 13082 } 13083 } 13084 13085 @Override 13086 public int getPreferredActivities(List<IntentFilter> outFilters, 13087 List<ComponentName> outActivities, String packageName) { 13088 13089 int num = 0; 13090 final int userId = UserHandle.getCallingUserId(); 13091 // reader 13092 synchronized (mPackages) { 13093 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13094 if (pir != null) { 13095 final Iterator<PreferredActivity> it = pir.filterIterator(); 13096 while (it.hasNext()) { 13097 final PreferredActivity pa = it.next(); 13098 if (packageName == null 13099 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13100 && pa.mPref.mAlways)) { 13101 if (outFilters != null) { 13102 outFilters.add(new IntentFilter(pa)); 13103 } 13104 if (outActivities != null) { 13105 outActivities.add(pa.mPref.mComponent); 13106 } 13107 } 13108 } 13109 } 13110 } 13111 13112 return num; 13113 } 13114 13115 @Override 13116 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13117 int userId) { 13118 int callingUid = Binder.getCallingUid(); 13119 if (callingUid != Process.SYSTEM_UID) { 13120 throw new SecurityException( 13121 "addPersistentPreferredActivity can only be run by the system"); 13122 } 13123 if (filter.countActions() == 0) { 13124 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13125 return; 13126 } 13127 synchronized (mPackages) { 13128 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13129 " :"); 13130 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13131 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13132 new PersistentPreferredActivity(filter, activity)); 13133 scheduleWritePackageRestrictionsLocked(userId); 13134 } 13135 } 13136 13137 @Override 13138 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13139 int callingUid = Binder.getCallingUid(); 13140 if (callingUid != Process.SYSTEM_UID) { 13141 throw new SecurityException( 13142 "clearPackagePersistentPreferredActivities can only be run by the system"); 13143 } 13144 ArrayList<PersistentPreferredActivity> removed = null; 13145 boolean changed = false; 13146 synchronized (mPackages) { 13147 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13148 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13149 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13150 .valueAt(i); 13151 if (userId != thisUserId) { 13152 continue; 13153 } 13154 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13155 while (it.hasNext()) { 13156 PersistentPreferredActivity ppa = it.next(); 13157 // Mark entry for removal only if it matches the package name. 13158 if (ppa.mComponent.getPackageName().equals(packageName)) { 13159 if (removed == null) { 13160 removed = new ArrayList<PersistentPreferredActivity>(); 13161 } 13162 removed.add(ppa); 13163 } 13164 } 13165 if (removed != null) { 13166 for (int j=0; j<removed.size(); j++) { 13167 PersistentPreferredActivity ppa = removed.get(j); 13168 ppir.removeFilter(ppa); 13169 } 13170 changed = true; 13171 } 13172 } 13173 13174 if (changed) { 13175 scheduleWritePackageRestrictionsLocked(userId); 13176 } 13177 } 13178 } 13179 13180 /** 13181 * Non-Binder method, support for the backup/restore mechanism: write the 13182 * full set of preferred activities in its canonical XML format. Returns true 13183 * on success; false otherwise. 13184 */ 13185 @Override 13186 public byte[] getPreferredActivityBackup(int userId) { 13187 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13188 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13189 } 13190 13191 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13192 try { 13193 final XmlSerializer serializer = new FastXmlSerializer(); 13194 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13195 serializer.startDocument(null, true); 13196 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13197 13198 synchronized (mPackages) { 13199 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13200 } 13201 13202 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13203 serializer.endDocument(); 13204 serializer.flush(); 13205 } catch (Exception e) { 13206 if (DEBUG_BACKUP) { 13207 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13208 } 13209 return null; 13210 } 13211 13212 return dataStream.toByteArray(); 13213 } 13214 13215 @Override 13216 public void restorePreferredActivities(byte[] backup, int userId) { 13217 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13218 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13219 } 13220 13221 try { 13222 final XmlPullParser parser = Xml.newPullParser(); 13223 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13224 13225 int type; 13226 while ((type = parser.next()) != XmlPullParser.START_TAG 13227 && type != XmlPullParser.END_DOCUMENT) { 13228 } 13229 if (type != XmlPullParser.START_TAG) { 13230 // oops didn't find a start tag?! 13231 if (DEBUG_BACKUP) { 13232 Slog.e(TAG, "Didn't find start tag during restore"); 13233 } 13234 return; 13235 } 13236 13237 // this is supposed to be TAG_PREFERRED_BACKUP 13238 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13239 if (DEBUG_BACKUP) { 13240 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13241 } 13242 return; 13243 } 13244 13245 // skip interfering stuff, then we're aligned with the backing implementation 13246 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13247 synchronized (mPackages) { 13248 mSettings.readPreferredActivitiesLPw(parser, userId); 13249 } 13250 } catch (Exception e) { 13251 if (DEBUG_BACKUP) { 13252 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13253 } 13254 } 13255 } 13256 13257 @Override 13258 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13259 int sourceUserId, int targetUserId, int flags) { 13260 mContext.enforceCallingOrSelfPermission( 13261 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13262 int callingUid = Binder.getCallingUid(); 13263 enforceOwnerRights(ownerPackage, callingUid); 13264 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13265 if (intentFilter.countActions() == 0) { 13266 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13267 return; 13268 } 13269 synchronized (mPackages) { 13270 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13271 ownerPackage, targetUserId, flags); 13272 CrossProfileIntentResolver resolver = 13273 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13274 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13275 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13276 if (existing != null) { 13277 int size = existing.size(); 13278 for (int i = 0; i < size; i++) { 13279 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13280 return; 13281 } 13282 } 13283 } 13284 resolver.addFilter(newFilter); 13285 scheduleWritePackageRestrictionsLocked(sourceUserId); 13286 } 13287 } 13288 13289 @Override 13290 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13291 mContext.enforceCallingOrSelfPermission( 13292 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13293 int callingUid = Binder.getCallingUid(); 13294 enforceOwnerRights(ownerPackage, callingUid); 13295 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13296 synchronized (mPackages) { 13297 CrossProfileIntentResolver resolver = 13298 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13299 ArraySet<CrossProfileIntentFilter> set = 13300 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13301 for (CrossProfileIntentFilter filter : set) { 13302 if (filter.getOwnerPackage().equals(ownerPackage)) { 13303 resolver.removeFilter(filter); 13304 } 13305 } 13306 scheduleWritePackageRestrictionsLocked(sourceUserId); 13307 } 13308 } 13309 13310 // Enforcing that callingUid is owning pkg on userId 13311 private void enforceOwnerRights(String pkg, int callingUid) { 13312 // The system owns everything. 13313 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13314 return; 13315 } 13316 int callingUserId = UserHandle.getUserId(callingUid); 13317 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13318 if (pi == null) { 13319 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13320 + callingUserId); 13321 } 13322 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13323 throw new SecurityException("Calling uid " + callingUid 13324 + " does not own package " + pkg); 13325 } 13326 } 13327 13328 @Override 13329 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13330 Intent intent = new Intent(Intent.ACTION_MAIN); 13331 intent.addCategory(Intent.CATEGORY_HOME); 13332 13333 final int callingUserId = UserHandle.getCallingUserId(); 13334 List<ResolveInfo> list = queryIntentActivities(intent, null, 13335 PackageManager.GET_META_DATA, callingUserId); 13336 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13337 true, false, false, callingUserId); 13338 13339 allHomeCandidates.clear(); 13340 if (list != null) { 13341 for (ResolveInfo ri : list) { 13342 allHomeCandidates.add(ri); 13343 } 13344 } 13345 return (preferred == null || preferred.activityInfo == null) 13346 ? null 13347 : new ComponentName(preferred.activityInfo.packageName, 13348 preferred.activityInfo.name); 13349 } 13350 13351 @Override 13352 public void setApplicationEnabledSetting(String appPackageName, 13353 int newState, int flags, int userId, String callingPackage) { 13354 if (!sUserManager.exists(userId)) return; 13355 if (callingPackage == null) { 13356 callingPackage = Integer.toString(Binder.getCallingUid()); 13357 } 13358 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13359 } 13360 13361 @Override 13362 public void setComponentEnabledSetting(ComponentName componentName, 13363 int newState, int flags, int userId) { 13364 if (!sUserManager.exists(userId)) return; 13365 setEnabledSetting(componentName.getPackageName(), 13366 componentName.getClassName(), newState, flags, userId, null); 13367 } 13368 13369 private void setEnabledSetting(final String packageName, String className, int newState, 13370 final int flags, int userId, String callingPackage) { 13371 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13372 || newState == COMPONENT_ENABLED_STATE_ENABLED 13373 || newState == COMPONENT_ENABLED_STATE_DISABLED 13374 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13375 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13376 throw new IllegalArgumentException("Invalid new component state: " 13377 + newState); 13378 } 13379 PackageSetting pkgSetting; 13380 final int uid = Binder.getCallingUid(); 13381 final int permission = mContext.checkCallingOrSelfPermission( 13382 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13383 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13384 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13385 boolean sendNow = false; 13386 boolean isApp = (className == null); 13387 String componentName = isApp ? packageName : className; 13388 int packageUid = -1; 13389 ArrayList<String> components; 13390 13391 // writer 13392 synchronized (mPackages) { 13393 pkgSetting = mSettings.mPackages.get(packageName); 13394 if (pkgSetting == null) { 13395 if (className == null) { 13396 throw new IllegalArgumentException( 13397 "Unknown package: " + packageName); 13398 } 13399 throw new IllegalArgumentException( 13400 "Unknown component: " + packageName 13401 + "/" + className); 13402 } 13403 // Allow root and verify that userId is not being specified by a different user 13404 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13405 throw new SecurityException( 13406 "Permission Denial: attempt to change component state from pid=" 13407 + Binder.getCallingPid() 13408 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13409 } 13410 if (className == null) { 13411 // We're dealing with an application/package level state change 13412 if (pkgSetting.getEnabled(userId) == newState) { 13413 // Nothing to do 13414 return; 13415 } 13416 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13417 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13418 // Don't care about who enables an app. 13419 callingPackage = null; 13420 } 13421 pkgSetting.setEnabled(newState, userId, callingPackage); 13422 // pkgSetting.pkg.mSetEnabled = newState; 13423 } else { 13424 // We're dealing with a component level state change 13425 // First, verify that this is a valid class name. 13426 PackageParser.Package pkg = pkgSetting.pkg; 13427 if (pkg == null || !pkg.hasComponentClassName(className)) { 13428 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13429 throw new IllegalArgumentException("Component class " + className 13430 + " does not exist in " + packageName); 13431 } else { 13432 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13433 + className + " does not exist in " + packageName); 13434 } 13435 } 13436 switch (newState) { 13437 case COMPONENT_ENABLED_STATE_ENABLED: 13438 if (!pkgSetting.enableComponentLPw(className, userId)) { 13439 return; 13440 } 13441 break; 13442 case COMPONENT_ENABLED_STATE_DISABLED: 13443 if (!pkgSetting.disableComponentLPw(className, userId)) { 13444 return; 13445 } 13446 break; 13447 case COMPONENT_ENABLED_STATE_DEFAULT: 13448 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13449 return; 13450 } 13451 break; 13452 default: 13453 Slog.e(TAG, "Invalid new component state: " + newState); 13454 return; 13455 } 13456 } 13457 scheduleWritePackageRestrictionsLocked(userId); 13458 components = mPendingBroadcasts.get(userId, packageName); 13459 final boolean newPackage = components == null; 13460 if (newPackage) { 13461 components = new ArrayList<String>(); 13462 } 13463 if (!components.contains(componentName)) { 13464 components.add(componentName); 13465 } 13466 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13467 sendNow = true; 13468 // Purge entry from pending broadcast list if another one exists already 13469 // since we are sending one right away. 13470 mPendingBroadcasts.remove(userId, packageName); 13471 } else { 13472 if (newPackage) { 13473 mPendingBroadcasts.put(userId, packageName, components); 13474 } 13475 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13476 // Schedule a message 13477 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13478 } 13479 } 13480 } 13481 13482 long callingId = Binder.clearCallingIdentity(); 13483 try { 13484 if (sendNow) { 13485 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13486 sendPackageChangedBroadcast(packageName, 13487 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13488 } 13489 } finally { 13490 Binder.restoreCallingIdentity(callingId); 13491 } 13492 } 13493 13494 private void sendPackageChangedBroadcast(String packageName, 13495 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13496 if (DEBUG_INSTALL) 13497 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13498 + componentNames); 13499 Bundle extras = new Bundle(4); 13500 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13501 String nameList[] = new String[componentNames.size()]; 13502 componentNames.toArray(nameList); 13503 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13504 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13505 extras.putInt(Intent.EXTRA_UID, packageUid); 13506 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13507 new int[] {UserHandle.getUserId(packageUid)}); 13508 } 13509 13510 @Override 13511 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13512 if (!sUserManager.exists(userId)) return; 13513 final int uid = Binder.getCallingUid(); 13514 final int permission = mContext.checkCallingOrSelfPermission( 13515 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13516 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13517 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13518 // writer 13519 synchronized (mPackages) { 13520 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13521 allowedByPermission, uid, userId)) { 13522 scheduleWritePackageRestrictionsLocked(userId); 13523 } 13524 } 13525 } 13526 13527 @Override 13528 public String getInstallerPackageName(String packageName) { 13529 // reader 13530 synchronized (mPackages) { 13531 return mSettings.getInstallerPackageNameLPr(packageName); 13532 } 13533 } 13534 13535 @Override 13536 public int getApplicationEnabledSetting(String packageName, int userId) { 13537 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13538 int uid = Binder.getCallingUid(); 13539 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13540 // reader 13541 synchronized (mPackages) { 13542 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13543 } 13544 } 13545 13546 @Override 13547 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13548 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13549 int uid = Binder.getCallingUid(); 13550 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13551 // reader 13552 synchronized (mPackages) { 13553 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13554 } 13555 } 13556 13557 @Override 13558 public void enterSafeMode() { 13559 enforceSystemOrRoot("Only the system can request entering safe mode"); 13560 13561 if (!mSystemReady) { 13562 mSafeMode = true; 13563 } 13564 } 13565 13566 @Override 13567 public void systemReady() { 13568 mSystemReady = true; 13569 13570 // Read the compatibilty setting when the system is ready. 13571 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13572 mContext.getContentResolver(), 13573 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13574 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13575 if (DEBUG_SETTINGS) { 13576 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13577 } 13578 13579 synchronized (mPackages) { 13580 // Verify that all of the preferred activity components actually 13581 // exist. It is possible for applications to be updated and at 13582 // that point remove a previously declared activity component that 13583 // had been set as a preferred activity. We try to clean this up 13584 // the next time we encounter that preferred activity, but it is 13585 // possible for the user flow to never be able to return to that 13586 // situation so here we do a sanity check to make sure we haven't 13587 // left any junk around. 13588 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13589 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13590 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13591 removed.clear(); 13592 for (PreferredActivity pa : pir.filterSet()) { 13593 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13594 removed.add(pa); 13595 } 13596 } 13597 if (removed.size() > 0) { 13598 for (int r=0; r<removed.size(); r++) { 13599 PreferredActivity pa = removed.get(r); 13600 Slog.w(TAG, "Removing dangling preferred activity: " 13601 + pa.mPref.mComponent); 13602 pir.removeFilter(pa); 13603 } 13604 mSettings.writePackageRestrictionsLPr( 13605 mSettings.mPreferredActivities.keyAt(i)); 13606 } 13607 } 13608 } 13609 sUserManager.systemReady(); 13610 13611 // Kick off any messages waiting for system ready 13612 if (mPostSystemReadyMessages != null) { 13613 for (Message msg : mPostSystemReadyMessages) { 13614 msg.sendToTarget(); 13615 } 13616 mPostSystemReadyMessages = null; 13617 } 13618 13619 // Watch for external volumes that come and go over time 13620 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13621 storage.registerListener(mStorageListener); 13622 13623 mInstallerService.systemReady(); 13624 mPackageDexOptimizer.systemReady(); 13625 } 13626 13627 @Override 13628 public boolean isSafeMode() { 13629 return mSafeMode; 13630 } 13631 13632 @Override 13633 public boolean hasSystemUidErrors() { 13634 return mHasSystemUidErrors; 13635 } 13636 13637 static String arrayToString(int[] array) { 13638 StringBuffer buf = new StringBuffer(128); 13639 buf.append('['); 13640 if (array != null) { 13641 for (int i=0; i<array.length; i++) { 13642 if (i > 0) buf.append(", "); 13643 buf.append(array[i]); 13644 } 13645 } 13646 buf.append(']'); 13647 return buf.toString(); 13648 } 13649 13650 static class DumpState { 13651 public static final int DUMP_LIBS = 1 << 0; 13652 public static final int DUMP_FEATURES = 1 << 1; 13653 public static final int DUMP_RESOLVERS = 1 << 2; 13654 public static final int DUMP_PERMISSIONS = 1 << 3; 13655 public static final int DUMP_PACKAGES = 1 << 4; 13656 public static final int DUMP_SHARED_USERS = 1 << 5; 13657 public static final int DUMP_MESSAGES = 1 << 6; 13658 public static final int DUMP_PROVIDERS = 1 << 7; 13659 public static final int DUMP_VERIFIERS = 1 << 8; 13660 public static final int DUMP_PREFERRED = 1 << 9; 13661 public static final int DUMP_PREFERRED_XML = 1 << 10; 13662 public static final int DUMP_KEYSETS = 1 << 11; 13663 public static final int DUMP_VERSION = 1 << 12; 13664 public static final int DUMP_INSTALLS = 1 << 13; 13665 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13666 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13667 13668 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13669 13670 private int mTypes; 13671 13672 private int mOptions; 13673 13674 private boolean mTitlePrinted; 13675 13676 private SharedUserSetting mSharedUser; 13677 13678 public boolean isDumping(int type) { 13679 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13680 return true; 13681 } 13682 13683 return (mTypes & type) != 0; 13684 } 13685 13686 public void setDump(int type) { 13687 mTypes |= type; 13688 } 13689 13690 public boolean isOptionEnabled(int option) { 13691 return (mOptions & option) != 0; 13692 } 13693 13694 public void setOptionEnabled(int option) { 13695 mOptions |= option; 13696 } 13697 13698 public boolean onTitlePrinted() { 13699 final boolean printed = mTitlePrinted; 13700 mTitlePrinted = true; 13701 return printed; 13702 } 13703 13704 public boolean getTitlePrinted() { 13705 return mTitlePrinted; 13706 } 13707 13708 public void setTitlePrinted(boolean enabled) { 13709 mTitlePrinted = enabled; 13710 } 13711 13712 public SharedUserSetting getSharedUser() { 13713 return mSharedUser; 13714 } 13715 13716 public void setSharedUser(SharedUserSetting user) { 13717 mSharedUser = user; 13718 } 13719 } 13720 13721 @Override 13722 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13723 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13724 != PackageManager.PERMISSION_GRANTED) { 13725 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13726 + Binder.getCallingPid() 13727 + ", uid=" + Binder.getCallingUid() 13728 + " without permission " 13729 + android.Manifest.permission.DUMP); 13730 return; 13731 } 13732 13733 DumpState dumpState = new DumpState(); 13734 boolean fullPreferred = false; 13735 boolean checkin = false; 13736 13737 String packageName = null; 13738 13739 int opti = 0; 13740 while (opti < args.length) { 13741 String opt = args[opti]; 13742 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13743 break; 13744 } 13745 opti++; 13746 13747 if ("-a".equals(opt)) { 13748 // Right now we only know how to print all. 13749 } else if ("-h".equals(opt)) { 13750 pw.println("Package manager dump options:"); 13751 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13752 pw.println(" --checkin: dump for a checkin"); 13753 pw.println(" -f: print details of intent filters"); 13754 pw.println(" -h: print this help"); 13755 pw.println(" cmd may be one of:"); 13756 pw.println(" l[ibraries]: list known shared libraries"); 13757 pw.println(" f[ibraries]: list device features"); 13758 pw.println(" k[eysets]: print known keysets"); 13759 pw.println(" r[esolvers]: dump intent resolvers"); 13760 pw.println(" perm[issions]: dump permissions"); 13761 pw.println(" pref[erred]: print preferred package settings"); 13762 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13763 pw.println(" prov[iders]: dump content providers"); 13764 pw.println(" p[ackages]: dump installed packages"); 13765 pw.println(" s[hared-users]: dump shared user IDs"); 13766 pw.println(" m[essages]: print collected runtime messages"); 13767 pw.println(" v[erifiers]: print package verifier info"); 13768 pw.println(" version: print database version info"); 13769 pw.println(" write: write current settings now"); 13770 pw.println(" <package.name>: info about given package"); 13771 pw.println(" installs: details about install sessions"); 13772 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13773 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13774 return; 13775 } else if ("--checkin".equals(opt)) { 13776 checkin = true; 13777 } else if ("-f".equals(opt)) { 13778 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13779 } else { 13780 pw.println("Unknown argument: " + opt + "; use -h for help"); 13781 } 13782 } 13783 13784 // Is the caller requesting to dump a particular piece of data? 13785 if (opti < args.length) { 13786 String cmd = args[opti]; 13787 opti++; 13788 // Is this a package name? 13789 if ("android".equals(cmd) || cmd.contains(".")) { 13790 packageName = cmd; 13791 // When dumping a single package, we always dump all of its 13792 // filter information since the amount of data will be reasonable. 13793 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13794 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13795 dumpState.setDump(DumpState.DUMP_LIBS); 13796 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13797 dumpState.setDump(DumpState.DUMP_FEATURES); 13798 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13799 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13800 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13801 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13802 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13803 dumpState.setDump(DumpState.DUMP_PREFERRED); 13804 } else if ("preferred-xml".equals(cmd)) { 13805 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13806 if (opti < args.length && "--full".equals(args[opti])) { 13807 fullPreferred = true; 13808 opti++; 13809 } 13810 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13811 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13812 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13813 dumpState.setDump(DumpState.DUMP_PACKAGES); 13814 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13815 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13816 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13817 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13818 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13819 dumpState.setDump(DumpState.DUMP_MESSAGES); 13820 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13821 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13822 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13823 || "intent-filter-verifiers".equals(cmd)) { 13824 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13825 } else if ("version".equals(cmd)) { 13826 dumpState.setDump(DumpState.DUMP_VERSION); 13827 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13828 dumpState.setDump(DumpState.DUMP_KEYSETS); 13829 } else if ("installs".equals(cmd)) { 13830 dumpState.setDump(DumpState.DUMP_INSTALLS); 13831 } else if ("write".equals(cmd)) { 13832 synchronized (mPackages) { 13833 mSettings.writeLPr(); 13834 pw.println("Settings written."); 13835 return; 13836 } 13837 } 13838 } 13839 13840 if (checkin) { 13841 pw.println("vers,1"); 13842 } 13843 13844 // reader 13845 synchronized (mPackages) { 13846 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13847 if (!checkin) { 13848 if (dumpState.onTitlePrinted()) 13849 pw.println(); 13850 pw.println("Database versions:"); 13851 pw.print(" SDK Version:"); 13852 pw.print(" internal="); 13853 pw.print(mSettings.mInternalSdkPlatform); 13854 pw.print(" external="); 13855 pw.println(mSettings.mExternalSdkPlatform); 13856 pw.print(" DB Version:"); 13857 pw.print(" internal="); 13858 pw.print(mSettings.mInternalDatabaseVersion); 13859 pw.print(" external="); 13860 pw.println(mSettings.mExternalDatabaseVersion); 13861 } 13862 } 13863 13864 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13865 if (!checkin) { 13866 if (dumpState.onTitlePrinted()) 13867 pw.println(); 13868 pw.println("Verifiers:"); 13869 pw.print(" Required: "); 13870 pw.print(mRequiredVerifierPackage); 13871 pw.print(" (uid="); 13872 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13873 pw.println(")"); 13874 } else if (mRequiredVerifierPackage != null) { 13875 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13876 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13877 } 13878 } 13879 13880 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13881 packageName == null) { 13882 if (mIntentFilterVerifierComponent != null) { 13883 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13884 if (!checkin) { 13885 if (dumpState.onTitlePrinted()) 13886 pw.println(); 13887 pw.println("Intent Filter Verifier:"); 13888 pw.print(" Using: "); 13889 pw.print(verifierPackageName); 13890 pw.print(" (uid="); 13891 pw.print(getPackageUid(verifierPackageName, 0)); 13892 pw.println(")"); 13893 } else if (verifierPackageName != null) { 13894 pw.print("ifv,"); pw.print(verifierPackageName); 13895 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13896 } 13897 } else { 13898 pw.println(); 13899 pw.println("No Intent Filter Verifier available!"); 13900 } 13901 } 13902 13903 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13904 boolean printedHeader = false; 13905 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13906 while (it.hasNext()) { 13907 String name = it.next(); 13908 SharedLibraryEntry ent = mSharedLibraries.get(name); 13909 if (!checkin) { 13910 if (!printedHeader) { 13911 if (dumpState.onTitlePrinted()) 13912 pw.println(); 13913 pw.println("Libraries:"); 13914 printedHeader = true; 13915 } 13916 pw.print(" "); 13917 } else { 13918 pw.print("lib,"); 13919 } 13920 pw.print(name); 13921 if (!checkin) { 13922 pw.print(" -> "); 13923 } 13924 if (ent.path != null) { 13925 if (!checkin) { 13926 pw.print("(jar) "); 13927 pw.print(ent.path); 13928 } else { 13929 pw.print(",jar,"); 13930 pw.print(ent.path); 13931 } 13932 } else { 13933 if (!checkin) { 13934 pw.print("(apk) "); 13935 pw.print(ent.apk); 13936 } else { 13937 pw.print(",apk,"); 13938 pw.print(ent.apk); 13939 } 13940 } 13941 pw.println(); 13942 } 13943 } 13944 13945 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13946 if (dumpState.onTitlePrinted()) 13947 pw.println(); 13948 if (!checkin) { 13949 pw.println("Features:"); 13950 } 13951 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13952 while (it.hasNext()) { 13953 String name = it.next(); 13954 if (!checkin) { 13955 pw.print(" "); 13956 } else { 13957 pw.print("feat,"); 13958 } 13959 pw.println(name); 13960 } 13961 } 13962 13963 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13964 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13965 : "Activity Resolver Table:", " ", packageName, 13966 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13967 dumpState.setTitlePrinted(true); 13968 } 13969 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13970 : "Receiver Resolver Table:", " ", packageName, 13971 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13972 dumpState.setTitlePrinted(true); 13973 } 13974 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13975 : "Service Resolver Table:", " ", packageName, 13976 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13977 dumpState.setTitlePrinted(true); 13978 } 13979 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13980 : "Provider Resolver Table:", " ", packageName, 13981 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13982 dumpState.setTitlePrinted(true); 13983 } 13984 } 13985 13986 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13987 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13988 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13989 int user = mSettings.mPreferredActivities.keyAt(i); 13990 if (pir.dump(pw, 13991 dumpState.getTitlePrinted() 13992 ? "\nPreferred Activities User " + user + ":" 13993 : "Preferred Activities User " + user + ":", " ", 13994 packageName, true, false)) { 13995 dumpState.setTitlePrinted(true); 13996 } 13997 } 13998 } 13999 14000 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14001 pw.flush(); 14002 FileOutputStream fout = new FileOutputStream(fd); 14003 BufferedOutputStream str = new BufferedOutputStream(fout); 14004 XmlSerializer serializer = new FastXmlSerializer(); 14005 try { 14006 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14007 serializer.startDocument(null, true); 14008 serializer.setFeature( 14009 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14010 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14011 serializer.endDocument(); 14012 serializer.flush(); 14013 } catch (IllegalArgumentException e) { 14014 pw.println("Failed writing: " + e); 14015 } catch (IllegalStateException e) { 14016 pw.println("Failed writing: " + e); 14017 } catch (IOException e) { 14018 pw.println("Failed writing: " + e); 14019 } 14020 } 14021 14022 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 14023 pw.println(); 14024 int count = mSettings.mPackages.size(); 14025 if (count == 0) { 14026 pw.println("No domain preferred apps!"); 14027 pw.println(); 14028 } else { 14029 final String prefix = " "; 14030 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14031 if (allPackageSettings.size() == 0) { 14032 pw.println("No domain preferred apps!"); 14033 pw.println(); 14034 } else { 14035 pw.println("Domain preferred apps status:"); 14036 pw.println(); 14037 count = 0; 14038 for (PackageSetting ps : allPackageSettings) { 14039 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14040 if (ivi == null || ivi.getPackageName() == null) continue; 14041 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14042 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14043 pw.println(prefix + "Status: " + ivi.getStatusString()); 14044 pw.println(); 14045 count++; 14046 } 14047 if (count == 0) { 14048 pw.println(prefix + "No domain preferred app status!"); 14049 pw.println(); 14050 } 14051 for (int userId : sUserManager.getUserIds()) { 14052 pw.println("Domain preferred apps for User " + userId + ":"); 14053 pw.println(); 14054 count = 0; 14055 for (PackageSetting ps : allPackageSettings) { 14056 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14057 if (ivi == null || ivi.getPackageName() == null) { 14058 continue; 14059 } 14060 final int status = ps.getDomainVerificationStatusForUser(userId); 14061 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14062 continue; 14063 } 14064 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14065 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14066 String statusStr = IntentFilterVerificationInfo. 14067 getStatusStringFromValue(status); 14068 pw.println(prefix + "Status: " + statusStr); 14069 pw.println(); 14070 count++; 14071 } 14072 if (count == 0) { 14073 pw.println(prefix + "No domain preferred apps!"); 14074 pw.println(); 14075 } 14076 } 14077 } 14078 } 14079 } 14080 14081 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14082 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14083 if (packageName == null) { 14084 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14085 if (iperm == 0) { 14086 if (dumpState.onTitlePrinted()) 14087 pw.println(); 14088 pw.println("AppOp Permissions:"); 14089 } 14090 pw.print(" AppOp Permission "); 14091 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14092 pw.println(":"); 14093 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14094 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14095 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14096 } 14097 } 14098 } 14099 } 14100 14101 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14102 boolean printedSomething = false; 14103 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14104 if (packageName != null && !packageName.equals(p.info.packageName)) { 14105 continue; 14106 } 14107 if (!printedSomething) { 14108 if (dumpState.onTitlePrinted()) 14109 pw.println(); 14110 pw.println("Registered ContentProviders:"); 14111 printedSomething = true; 14112 } 14113 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14114 pw.print(" "); pw.println(p.toString()); 14115 } 14116 printedSomething = false; 14117 for (Map.Entry<String, PackageParser.Provider> entry : 14118 mProvidersByAuthority.entrySet()) { 14119 PackageParser.Provider p = entry.getValue(); 14120 if (packageName != null && !packageName.equals(p.info.packageName)) { 14121 continue; 14122 } 14123 if (!printedSomething) { 14124 if (dumpState.onTitlePrinted()) 14125 pw.println(); 14126 pw.println("ContentProvider Authorities:"); 14127 printedSomething = true; 14128 } 14129 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14130 pw.print(" "); pw.println(p.toString()); 14131 if (p.info != null && p.info.applicationInfo != null) { 14132 final String appInfo = p.info.applicationInfo.toString(); 14133 pw.print(" applicationInfo="); pw.println(appInfo); 14134 } 14135 } 14136 } 14137 14138 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14139 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14140 } 14141 14142 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14143 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14144 } 14145 14146 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14147 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14148 } 14149 14150 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14151 // XXX should handle packageName != null by dumping only install data that 14152 // the given package is involved with. 14153 if (dumpState.onTitlePrinted()) pw.println(); 14154 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14155 } 14156 14157 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14158 if (dumpState.onTitlePrinted()) pw.println(); 14159 mSettings.dumpReadMessagesLPr(pw, dumpState); 14160 14161 pw.println(); 14162 pw.println("Package warning messages:"); 14163 BufferedReader in = null; 14164 String line = null; 14165 try { 14166 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14167 while ((line = in.readLine()) != null) { 14168 if (line.contains("ignored: updated version")) continue; 14169 pw.println(line); 14170 } 14171 } catch (IOException ignored) { 14172 } finally { 14173 IoUtils.closeQuietly(in); 14174 } 14175 } 14176 14177 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14178 BufferedReader in = null; 14179 String line = null; 14180 try { 14181 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14182 while ((line = in.readLine()) != null) { 14183 if (line.contains("ignored: updated version")) continue; 14184 pw.print("msg,"); 14185 pw.println(line); 14186 } 14187 } catch (IOException ignored) { 14188 } finally { 14189 IoUtils.closeQuietly(in); 14190 } 14191 } 14192 } 14193 } 14194 14195 // ------- apps on sdcard specific code ------- 14196 static final boolean DEBUG_SD_INSTALL = false; 14197 14198 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14199 14200 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14201 14202 private boolean mMediaMounted = false; 14203 14204 static String getEncryptKey() { 14205 try { 14206 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14207 SD_ENCRYPTION_KEYSTORE_NAME); 14208 if (sdEncKey == null) { 14209 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14210 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14211 if (sdEncKey == null) { 14212 Slog.e(TAG, "Failed to create encryption keys"); 14213 return null; 14214 } 14215 } 14216 return sdEncKey; 14217 } catch (NoSuchAlgorithmException nsae) { 14218 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14219 return null; 14220 } catch (IOException ioe) { 14221 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14222 return null; 14223 } 14224 } 14225 14226 /* 14227 * Update media status on PackageManager. 14228 */ 14229 @Override 14230 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14231 int callingUid = Binder.getCallingUid(); 14232 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14233 throw new SecurityException("Media status can only be updated by the system"); 14234 } 14235 // reader; this apparently protects mMediaMounted, but should probably 14236 // be a different lock in that case. 14237 synchronized (mPackages) { 14238 Log.i(TAG, "Updating external media status from " 14239 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14240 + (mediaStatus ? "mounted" : "unmounted")); 14241 if (DEBUG_SD_INSTALL) 14242 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14243 + ", mMediaMounted=" + mMediaMounted); 14244 if (mediaStatus == mMediaMounted) { 14245 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14246 : 0, -1); 14247 mHandler.sendMessage(msg); 14248 return; 14249 } 14250 mMediaMounted = mediaStatus; 14251 } 14252 // Queue up an async operation since the package installation may take a 14253 // little while. 14254 mHandler.post(new Runnable() { 14255 public void run() { 14256 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14257 } 14258 }); 14259 } 14260 14261 /** 14262 * Called by MountService when the initial ASECs to scan are available. 14263 * Should block until all the ASEC containers are finished being scanned. 14264 */ 14265 public void scanAvailableAsecs() { 14266 updateExternalMediaStatusInner(true, false, false); 14267 if (mShouldRestoreconData) { 14268 SELinuxMMAC.setRestoreconDone(); 14269 mShouldRestoreconData = false; 14270 } 14271 } 14272 14273 /* 14274 * Collect information of applications on external media, map them against 14275 * existing containers and update information based on current mount status. 14276 * Please note that we always have to report status if reportStatus has been 14277 * set to true especially when unloading packages. 14278 */ 14279 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14280 boolean externalStorage) { 14281 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14282 int[] uidArr = EmptyArray.INT; 14283 14284 final String[] list = PackageHelper.getSecureContainerList(); 14285 if (ArrayUtils.isEmpty(list)) { 14286 Log.i(TAG, "No secure containers found"); 14287 } else { 14288 // Process list of secure containers and categorize them 14289 // as active or stale based on their package internal state. 14290 14291 // reader 14292 synchronized (mPackages) { 14293 for (String cid : list) { 14294 // Leave stages untouched for now; installer service owns them 14295 if (PackageInstallerService.isStageName(cid)) continue; 14296 14297 if (DEBUG_SD_INSTALL) 14298 Log.i(TAG, "Processing container " + cid); 14299 String pkgName = getAsecPackageName(cid); 14300 if (pkgName == null) { 14301 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14302 continue; 14303 } 14304 if (DEBUG_SD_INSTALL) 14305 Log.i(TAG, "Looking for pkg : " + pkgName); 14306 14307 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14308 if (ps == null) { 14309 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14310 continue; 14311 } 14312 14313 /* 14314 * Skip packages that are not external if we're unmounting 14315 * external storage. 14316 */ 14317 if (externalStorage && !isMounted && !isExternal(ps)) { 14318 continue; 14319 } 14320 14321 final AsecInstallArgs args = new AsecInstallArgs(cid, 14322 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14323 // The package status is changed only if the code path 14324 // matches between settings and the container id. 14325 if (ps.codePathString != null 14326 && ps.codePathString.startsWith(args.getCodePath())) { 14327 if (DEBUG_SD_INSTALL) { 14328 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14329 + " at code path: " + ps.codePathString); 14330 } 14331 14332 // We do have a valid package installed on sdcard 14333 processCids.put(args, ps.codePathString); 14334 final int uid = ps.appId; 14335 if (uid != -1) { 14336 uidArr = ArrayUtils.appendInt(uidArr, uid); 14337 } 14338 } else { 14339 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14340 + ps.codePathString); 14341 } 14342 } 14343 } 14344 14345 Arrays.sort(uidArr); 14346 } 14347 14348 // Process packages with valid entries. 14349 if (isMounted) { 14350 if (DEBUG_SD_INSTALL) 14351 Log.i(TAG, "Loading packages"); 14352 loadMediaPackages(processCids, uidArr); 14353 startCleaningPackages(); 14354 mInstallerService.onSecureContainersAvailable(); 14355 } else { 14356 if (DEBUG_SD_INSTALL) 14357 Log.i(TAG, "Unloading packages"); 14358 unloadMediaPackages(processCids, uidArr, reportStatus); 14359 } 14360 } 14361 14362 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14363 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14364 final int size = infos.size(); 14365 final String[] packageNames = new String[size]; 14366 final int[] packageUids = new int[size]; 14367 for (int i = 0; i < size; i++) { 14368 final ApplicationInfo info = infos.get(i); 14369 packageNames[i] = info.packageName; 14370 packageUids[i] = info.uid; 14371 } 14372 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14373 finishedReceiver); 14374 } 14375 14376 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14377 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14378 sendResourcesChangedBroadcast(mediaStatus, replacing, 14379 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14380 } 14381 14382 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14383 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14384 int size = pkgList.length; 14385 if (size > 0) { 14386 // Send broadcasts here 14387 Bundle extras = new Bundle(); 14388 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14389 if (uidArr != null) { 14390 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14391 } 14392 if (replacing) { 14393 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14394 } 14395 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14396 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14397 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14398 } 14399 } 14400 14401 /* 14402 * Look at potentially valid container ids from processCids If package 14403 * information doesn't match the one on record or package scanning fails, 14404 * the cid is added to list of removeCids. We currently don't delete stale 14405 * containers. 14406 */ 14407 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14408 ArrayList<String> pkgList = new ArrayList<String>(); 14409 Set<AsecInstallArgs> keys = processCids.keySet(); 14410 14411 for (AsecInstallArgs args : keys) { 14412 String codePath = processCids.get(args); 14413 if (DEBUG_SD_INSTALL) 14414 Log.i(TAG, "Loading container : " + args.cid); 14415 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14416 try { 14417 // Make sure there are no container errors first. 14418 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14419 Slog.e(TAG, "Failed to mount cid : " + args.cid 14420 + " when installing from sdcard"); 14421 continue; 14422 } 14423 // Check code path here. 14424 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14425 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14426 + " does not match one in settings " + codePath); 14427 continue; 14428 } 14429 // Parse package 14430 int parseFlags = mDefParseFlags; 14431 if (args.isExternalAsec()) { 14432 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14433 } 14434 if (args.isFwdLocked()) { 14435 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14436 } 14437 14438 synchronized (mInstallLock) { 14439 PackageParser.Package pkg = null; 14440 try { 14441 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14442 } catch (PackageManagerException e) { 14443 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14444 } 14445 // Scan the package 14446 if (pkg != null) { 14447 /* 14448 * TODO why is the lock being held? doPostInstall is 14449 * called in other places without the lock. This needs 14450 * to be straightened out. 14451 */ 14452 // writer 14453 synchronized (mPackages) { 14454 retCode = PackageManager.INSTALL_SUCCEEDED; 14455 pkgList.add(pkg.packageName); 14456 // Post process args 14457 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14458 pkg.applicationInfo.uid); 14459 } 14460 } else { 14461 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14462 } 14463 } 14464 14465 } finally { 14466 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14467 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14468 } 14469 } 14470 } 14471 // writer 14472 synchronized (mPackages) { 14473 // If the platform SDK has changed since the last time we booted, 14474 // we need to re-grant app permission to catch any new ones that 14475 // appear. This is really a hack, and means that apps can in some 14476 // cases get permissions that the user didn't initially explicitly 14477 // allow... it would be nice to have some better way to handle 14478 // this situation. 14479 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14480 if (regrantPermissions) 14481 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14482 + mSdkVersion + "; regranting permissions for external storage"); 14483 mSettings.mExternalSdkPlatform = mSdkVersion; 14484 14485 // Make sure group IDs have been assigned, and any permission 14486 // changes in other apps are accounted for 14487 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14488 | (regrantPermissions 14489 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14490 : 0)); 14491 14492 mSettings.updateExternalDatabaseVersion(); 14493 14494 // can downgrade to reader 14495 // Persist settings 14496 mSettings.writeLPr(); 14497 } 14498 // Send a broadcast to let everyone know we are done processing 14499 if (pkgList.size() > 0) { 14500 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14501 } 14502 } 14503 14504 /* 14505 * Utility method to unload a list of specified containers 14506 */ 14507 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14508 // Just unmount all valid containers. 14509 for (AsecInstallArgs arg : cidArgs) { 14510 synchronized (mInstallLock) { 14511 arg.doPostDeleteLI(false); 14512 } 14513 } 14514 } 14515 14516 /* 14517 * Unload packages mounted on external media. This involves deleting package 14518 * data from internal structures, sending broadcasts about diabled packages, 14519 * gc'ing to free up references, unmounting all secure containers 14520 * corresponding to packages on external media, and posting a 14521 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14522 * that we always have to post this message if status has been requested no 14523 * matter what. 14524 */ 14525 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14526 final boolean reportStatus) { 14527 if (DEBUG_SD_INSTALL) 14528 Log.i(TAG, "unloading media packages"); 14529 ArrayList<String> pkgList = new ArrayList<String>(); 14530 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14531 final Set<AsecInstallArgs> keys = processCids.keySet(); 14532 for (AsecInstallArgs args : keys) { 14533 String pkgName = args.getPackageName(); 14534 if (DEBUG_SD_INSTALL) 14535 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14536 // Delete package internally 14537 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14538 synchronized (mInstallLock) { 14539 boolean res = deletePackageLI(pkgName, null, false, null, null, 14540 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14541 if (res) { 14542 pkgList.add(pkgName); 14543 } else { 14544 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14545 failedList.add(args); 14546 } 14547 } 14548 } 14549 14550 // reader 14551 synchronized (mPackages) { 14552 // We didn't update the settings after removing each package; 14553 // write them now for all packages. 14554 mSettings.writeLPr(); 14555 } 14556 14557 // We have to absolutely send UPDATED_MEDIA_STATUS only 14558 // after confirming that all the receivers processed the ordered 14559 // broadcast when packages get disabled, force a gc to clean things up. 14560 // and unload all the containers. 14561 if (pkgList.size() > 0) { 14562 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14563 new IIntentReceiver.Stub() { 14564 public void performReceive(Intent intent, int resultCode, String data, 14565 Bundle extras, boolean ordered, boolean sticky, 14566 int sendingUser) throws RemoteException { 14567 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14568 reportStatus ? 1 : 0, 1, keys); 14569 mHandler.sendMessage(msg); 14570 } 14571 }); 14572 } else { 14573 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14574 keys); 14575 mHandler.sendMessage(msg); 14576 } 14577 } 14578 14579 private void loadPrivatePackages(VolumeInfo vol) { 14580 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14581 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14582 synchronized (mInstallLock) { 14583 synchronized (mPackages) { 14584 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14585 for (PackageSetting ps : packages) { 14586 final PackageParser.Package pkg; 14587 try { 14588 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14589 loaded.add(pkg.applicationInfo); 14590 } catch (PackageManagerException e) { 14591 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14592 } 14593 } 14594 14595 // TODO: regrant any permissions that changed based since original install 14596 14597 mSettings.writeLPr(); 14598 } 14599 } 14600 14601 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14602 sendResourcesChangedBroadcast(true, false, loaded, null); 14603 } 14604 14605 private void unloadPrivatePackages(VolumeInfo vol) { 14606 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14607 synchronized (mInstallLock) { 14608 synchronized (mPackages) { 14609 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14610 for (PackageSetting ps : packages) { 14611 if (ps.pkg == null) continue; 14612 14613 final ApplicationInfo info = ps.pkg.applicationInfo; 14614 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14615 if (deletePackageLI(ps.name, null, false, null, null, 14616 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14617 unloaded.add(info); 14618 } else { 14619 Slog.w(TAG, "Failed to unload " + ps.codePath); 14620 } 14621 } 14622 14623 mSettings.writeLPr(); 14624 } 14625 } 14626 14627 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14628 sendResourcesChangedBroadcast(false, false, unloaded, null); 14629 } 14630 14631 private void unfreezePackage(String packageName) { 14632 synchronized (mPackages) { 14633 final PackageSetting ps = mSettings.mPackages.get(packageName); 14634 if (ps != null) { 14635 ps.frozen = false; 14636 } 14637 } 14638 } 14639 14640 @Override 14641 public int movePackage(final String packageName, final String volumeUuid) { 14642 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14643 14644 final int moveId = mNextMoveId.getAndIncrement(); 14645 try { 14646 movePackageInternal(packageName, volumeUuid, moveId); 14647 } catch (PackageManagerException e) { 14648 Slog.w(TAG, "Failed to move " + packageName, e); 14649 mMoveCallbacks.notifyStatusChanged(moveId, 14650 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14651 } 14652 return moveId; 14653 } 14654 14655 private void movePackageInternal(final String packageName, final String volumeUuid, 14656 final int moveId) throws PackageManagerException { 14657 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14658 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14659 final PackageManager pm = mContext.getPackageManager(); 14660 14661 final boolean currentAsec; 14662 final String currentVolumeUuid; 14663 final File codeFile; 14664 final String installerPackageName; 14665 final String packageAbiOverride; 14666 final int appId; 14667 final String seinfo; 14668 final String label; 14669 14670 // reader 14671 synchronized (mPackages) { 14672 final PackageParser.Package pkg = mPackages.get(packageName); 14673 final PackageSetting ps = mSettings.mPackages.get(packageName); 14674 if (pkg == null || ps == null) { 14675 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14676 } 14677 14678 if (pkg.applicationInfo.isSystemApp()) { 14679 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14680 "Cannot move system application"); 14681 } 14682 14683 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14684 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14685 "Package already moved to " + volumeUuid); 14686 } 14687 14688 final File probe = new File(pkg.codePath); 14689 final File probeOat = new File(probe, "oat"); 14690 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14691 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14692 "Move only supported for modern cluster style installs"); 14693 } 14694 14695 if (ps.frozen) { 14696 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14697 "Failed to move already frozen package"); 14698 } 14699 ps.frozen = true; 14700 14701 currentAsec = pkg.applicationInfo.isForwardLocked() 14702 || pkg.applicationInfo.isExternalAsec(); 14703 currentVolumeUuid = ps.volumeUuid; 14704 codeFile = new File(pkg.codePath); 14705 installerPackageName = ps.installerPackageName; 14706 packageAbiOverride = ps.cpuAbiOverrideString; 14707 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14708 seinfo = pkg.applicationInfo.seinfo; 14709 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14710 } 14711 14712 // Now that we're guarded by frozen state, kill app during move 14713 killApplication(packageName, appId, "move pkg"); 14714 14715 final Bundle extras = new Bundle(); 14716 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14717 extras.putString(Intent.EXTRA_TITLE, label); 14718 mMoveCallbacks.notifyCreated(moveId, extras); 14719 14720 int installFlags; 14721 final boolean moveCompleteApp; 14722 final File measurePath; 14723 14724 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14725 installFlags = INSTALL_INTERNAL; 14726 moveCompleteApp = !currentAsec; 14727 measurePath = Environment.getDataAppDirectory(volumeUuid); 14728 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14729 installFlags = INSTALL_EXTERNAL; 14730 moveCompleteApp = false; 14731 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14732 } else { 14733 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14734 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14735 || !volume.isMountedWritable()) { 14736 unfreezePackage(packageName); 14737 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14738 "Move location not mounted private volume"); 14739 } 14740 14741 Preconditions.checkState(!currentAsec); 14742 14743 installFlags = INSTALL_INTERNAL; 14744 moveCompleteApp = true; 14745 measurePath = Environment.getDataAppDirectory(volumeUuid); 14746 } 14747 14748 final PackageStats stats = new PackageStats(null, -1); 14749 synchronized (mInstaller) { 14750 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14751 unfreezePackage(packageName); 14752 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14753 "Failed to measure package size"); 14754 } 14755 } 14756 14757 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14758 + stats.dataSize); 14759 14760 final long startFreeBytes = measurePath.getFreeSpace(); 14761 final long sizeBytes; 14762 if (moveCompleteApp) { 14763 sizeBytes = stats.codeSize + stats.dataSize; 14764 } else { 14765 sizeBytes = stats.codeSize; 14766 } 14767 14768 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14769 unfreezePackage(packageName); 14770 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14771 "Not enough free space to move"); 14772 } 14773 14774 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14775 14776 final CountDownLatch installedLatch = new CountDownLatch(1); 14777 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14778 @Override 14779 public void onUserActionRequired(Intent intent) throws RemoteException { 14780 throw new IllegalStateException(); 14781 } 14782 14783 @Override 14784 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14785 Bundle extras) throws RemoteException { 14786 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14787 + PackageManager.installStatusToString(returnCode, msg)); 14788 14789 installedLatch.countDown(); 14790 14791 // Regardless of success or failure of the move operation, 14792 // always unfreeze the package 14793 unfreezePackage(packageName); 14794 14795 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14796 switch (status) { 14797 case PackageInstaller.STATUS_SUCCESS: 14798 mMoveCallbacks.notifyStatusChanged(moveId, 14799 PackageManager.MOVE_SUCCEEDED); 14800 break; 14801 case PackageInstaller.STATUS_FAILURE_STORAGE: 14802 mMoveCallbacks.notifyStatusChanged(moveId, 14803 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14804 break; 14805 default: 14806 mMoveCallbacks.notifyStatusChanged(moveId, 14807 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14808 break; 14809 } 14810 } 14811 }; 14812 14813 final MoveInfo move; 14814 if (moveCompleteApp) { 14815 // Kick off a thread to report progress estimates 14816 new Thread() { 14817 @Override 14818 public void run() { 14819 while (true) { 14820 try { 14821 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14822 break; 14823 } 14824 } catch (InterruptedException ignored) { 14825 } 14826 14827 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14828 final int progress = 10 + (int) MathUtils.constrain( 14829 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14830 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14831 } 14832 } 14833 }.start(); 14834 14835 final String dataAppName = codeFile.getName(); 14836 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14837 dataAppName, appId, seinfo); 14838 } else { 14839 move = null; 14840 } 14841 14842 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14843 14844 final Message msg = mHandler.obtainMessage(INIT_COPY); 14845 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14846 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14847 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14848 mHandler.sendMessage(msg); 14849 } 14850 14851 @Override 14852 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14853 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14854 14855 final int realMoveId = mNextMoveId.getAndIncrement(); 14856 final Bundle extras = new Bundle(); 14857 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14858 mMoveCallbacks.notifyCreated(realMoveId, extras); 14859 14860 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14861 @Override 14862 public void onCreated(int moveId, Bundle extras) { 14863 // Ignored 14864 } 14865 14866 @Override 14867 public void onStatusChanged(int moveId, int status, long estMillis) { 14868 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14869 } 14870 }; 14871 14872 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14873 storage.setPrimaryStorageUuid(volumeUuid, callback); 14874 return realMoveId; 14875 } 14876 14877 @Override 14878 public int getMoveStatus(int moveId) { 14879 mContext.enforceCallingOrSelfPermission( 14880 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14881 return mMoveCallbacks.mLastStatus.get(moveId); 14882 } 14883 14884 @Override 14885 public void registerMoveCallback(IPackageMoveObserver callback) { 14886 mContext.enforceCallingOrSelfPermission( 14887 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14888 mMoveCallbacks.register(callback); 14889 } 14890 14891 @Override 14892 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14893 mContext.enforceCallingOrSelfPermission( 14894 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14895 mMoveCallbacks.unregister(callback); 14896 } 14897 14898 @Override 14899 public boolean setInstallLocation(int loc) { 14900 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14901 null); 14902 if (getInstallLocation() == loc) { 14903 return true; 14904 } 14905 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14906 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14907 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14908 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14909 return true; 14910 } 14911 return false; 14912 } 14913 14914 @Override 14915 public int getInstallLocation() { 14916 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14917 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14918 PackageHelper.APP_INSTALL_AUTO); 14919 } 14920 14921 /** Called by UserManagerService */ 14922 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14923 mDirtyUsers.remove(userHandle); 14924 mSettings.removeUserLPw(userHandle); 14925 mPendingBroadcasts.remove(userHandle); 14926 if (mInstaller != null) { 14927 // Technically, we shouldn't be doing this with the package lock 14928 // held. However, this is very rare, and there is already so much 14929 // other disk I/O going on, that we'll let it slide for now. 14930 final StorageManager storage = StorageManager.from(mContext); 14931 final List<VolumeInfo> vols = storage.getVolumes(); 14932 for (VolumeInfo vol : vols) { 14933 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14934 final String volumeUuid = vol.getFsUuid(); 14935 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14936 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14937 } 14938 } 14939 } 14940 mUserNeedsBadging.delete(userHandle); 14941 removeUnusedPackagesLILPw(userManager, userHandle); 14942 } 14943 14944 /** 14945 * We're removing userHandle and would like to remove any downloaded packages 14946 * that are no longer in use by any other user. 14947 * @param userHandle the user being removed 14948 */ 14949 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14950 final boolean DEBUG_CLEAN_APKS = false; 14951 int [] users = userManager.getUserIdsLPr(); 14952 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14953 while (psit.hasNext()) { 14954 PackageSetting ps = psit.next(); 14955 if (ps.pkg == null) { 14956 continue; 14957 } 14958 final String packageName = ps.pkg.packageName; 14959 // Skip over if system app 14960 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14961 continue; 14962 } 14963 if (DEBUG_CLEAN_APKS) { 14964 Slog.i(TAG, "Checking package " + packageName); 14965 } 14966 boolean keep = false; 14967 for (int i = 0; i < users.length; i++) { 14968 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14969 keep = true; 14970 if (DEBUG_CLEAN_APKS) { 14971 Slog.i(TAG, " Keeping package " + packageName + " for user " 14972 + users[i]); 14973 } 14974 break; 14975 } 14976 } 14977 if (!keep) { 14978 if (DEBUG_CLEAN_APKS) { 14979 Slog.i(TAG, " Removing package " + packageName); 14980 } 14981 mHandler.post(new Runnable() { 14982 public void run() { 14983 deletePackageX(packageName, userHandle, 0); 14984 } //end run 14985 }); 14986 } 14987 } 14988 } 14989 14990 /** Called by UserManagerService */ 14991 void createNewUserLILPw(int userHandle, File path) { 14992 if (mInstaller != null) { 14993 mInstaller.createUserConfig(userHandle); 14994 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14995 } 14996 } 14997 14998 void newUserCreatedLILPw(int userHandle) { 14999 // Adding a user requires updating runtime permissions for system apps. 15000 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 15001 } 15002 15003 @Override 15004 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15005 mContext.enforceCallingOrSelfPermission( 15006 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15007 "Only package verification agents can read the verifier device identity"); 15008 15009 synchronized (mPackages) { 15010 return mSettings.getVerifierDeviceIdentityLPw(); 15011 } 15012 } 15013 15014 @Override 15015 public void setPermissionEnforced(String permission, boolean enforced) { 15016 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15017 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15018 synchronized (mPackages) { 15019 if (mSettings.mReadExternalStorageEnforced == null 15020 || mSettings.mReadExternalStorageEnforced != enforced) { 15021 mSettings.mReadExternalStorageEnforced = enforced; 15022 mSettings.writeLPr(); 15023 } 15024 } 15025 // kill any non-foreground processes so we restart them and 15026 // grant/revoke the GID. 15027 final IActivityManager am = ActivityManagerNative.getDefault(); 15028 if (am != null) { 15029 final long token = Binder.clearCallingIdentity(); 15030 try { 15031 am.killProcessesBelowForeground("setPermissionEnforcement"); 15032 } catch (RemoteException e) { 15033 } finally { 15034 Binder.restoreCallingIdentity(token); 15035 } 15036 } 15037 } else { 15038 throw new IllegalArgumentException("No selective enforcement for " + permission); 15039 } 15040 } 15041 15042 @Override 15043 @Deprecated 15044 public boolean isPermissionEnforced(String permission) { 15045 return true; 15046 } 15047 15048 @Override 15049 public boolean isStorageLow() { 15050 final long token = Binder.clearCallingIdentity(); 15051 try { 15052 final DeviceStorageMonitorInternal 15053 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15054 if (dsm != null) { 15055 return dsm.isMemoryLow(); 15056 } else { 15057 return false; 15058 } 15059 } finally { 15060 Binder.restoreCallingIdentity(token); 15061 } 15062 } 15063 15064 @Override 15065 public IPackageInstaller getPackageInstaller() { 15066 return mInstallerService; 15067 } 15068 15069 private boolean userNeedsBadging(int userId) { 15070 int index = mUserNeedsBadging.indexOfKey(userId); 15071 if (index < 0) { 15072 final UserInfo userInfo; 15073 final long token = Binder.clearCallingIdentity(); 15074 try { 15075 userInfo = sUserManager.getUserInfo(userId); 15076 } finally { 15077 Binder.restoreCallingIdentity(token); 15078 } 15079 final boolean b; 15080 if (userInfo != null && userInfo.isManagedProfile()) { 15081 b = true; 15082 } else { 15083 b = false; 15084 } 15085 mUserNeedsBadging.put(userId, b); 15086 return b; 15087 } 15088 return mUserNeedsBadging.valueAt(index); 15089 } 15090 15091 @Override 15092 public KeySet getKeySetByAlias(String packageName, String alias) { 15093 if (packageName == null || alias == null) { 15094 return null; 15095 } 15096 synchronized(mPackages) { 15097 final PackageParser.Package pkg = mPackages.get(packageName); 15098 if (pkg == null) { 15099 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15100 throw new IllegalArgumentException("Unknown package: " + packageName); 15101 } 15102 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15103 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15104 } 15105 } 15106 15107 @Override 15108 public KeySet getSigningKeySet(String packageName) { 15109 if (packageName == null) { 15110 return null; 15111 } 15112 synchronized(mPackages) { 15113 final PackageParser.Package pkg = mPackages.get(packageName); 15114 if (pkg == null) { 15115 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15116 throw new IllegalArgumentException("Unknown package: " + packageName); 15117 } 15118 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15119 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15120 throw new SecurityException("May not access signing KeySet of other apps."); 15121 } 15122 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15123 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15124 } 15125 } 15126 15127 @Override 15128 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15129 if (packageName == null || ks == null) { 15130 return false; 15131 } 15132 synchronized(mPackages) { 15133 final PackageParser.Package pkg = mPackages.get(packageName); 15134 if (pkg == null) { 15135 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15136 throw new IllegalArgumentException("Unknown package: " + packageName); 15137 } 15138 IBinder ksh = ks.getToken(); 15139 if (ksh instanceof KeySetHandle) { 15140 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15141 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15142 } 15143 return false; 15144 } 15145 } 15146 15147 @Override 15148 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15149 if (packageName == null || ks == null) { 15150 return false; 15151 } 15152 synchronized(mPackages) { 15153 final PackageParser.Package pkg = mPackages.get(packageName); 15154 if (pkg == null) { 15155 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15156 throw new IllegalArgumentException("Unknown package: " + packageName); 15157 } 15158 IBinder ksh = ks.getToken(); 15159 if (ksh instanceof KeySetHandle) { 15160 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15161 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15162 } 15163 return false; 15164 } 15165 } 15166 15167 public void getUsageStatsIfNoPackageUsageInfo() { 15168 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15169 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15170 if (usm == null) { 15171 throw new IllegalStateException("UsageStatsManager must be initialized"); 15172 } 15173 long now = System.currentTimeMillis(); 15174 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15175 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15176 String packageName = entry.getKey(); 15177 PackageParser.Package pkg = mPackages.get(packageName); 15178 if (pkg == null) { 15179 continue; 15180 } 15181 UsageStats usage = entry.getValue(); 15182 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15183 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15184 } 15185 } 15186 } 15187 15188 /** 15189 * Check and throw if the given before/after packages would be considered a 15190 * downgrade. 15191 */ 15192 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15193 throws PackageManagerException { 15194 if (after.versionCode < before.mVersionCode) { 15195 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15196 "Update version code " + after.versionCode + " is older than current " 15197 + before.mVersionCode); 15198 } else if (after.versionCode == before.mVersionCode) { 15199 if (after.baseRevisionCode < before.baseRevisionCode) { 15200 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15201 "Update base revision code " + after.baseRevisionCode 15202 + " is older than current " + before.baseRevisionCode); 15203 } 15204 15205 if (!ArrayUtils.isEmpty(after.splitNames)) { 15206 for (int i = 0; i < after.splitNames.length; i++) { 15207 final String splitName = after.splitNames[i]; 15208 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15209 if (j != -1) { 15210 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15211 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15212 "Update split " + splitName + " revision code " 15213 + after.splitRevisionCodes[i] + " is older than current " 15214 + before.splitRevisionCodes[j]); 15215 } 15216 } 15217 } 15218 } 15219 } 15220 } 15221 15222 private static class MoveCallbacks extends Handler { 15223 private static final int MSG_CREATED = 1; 15224 private static final int MSG_STATUS_CHANGED = 2; 15225 15226 private final RemoteCallbackList<IPackageMoveObserver> 15227 mCallbacks = new RemoteCallbackList<>(); 15228 15229 private final SparseIntArray mLastStatus = new SparseIntArray(); 15230 15231 public MoveCallbacks(Looper looper) { 15232 super(looper); 15233 } 15234 15235 public void register(IPackageMoveObserver callback) { 15236 mCallbacks.register(callback); 15237 } 15238 15239 public void unregister(IPackageMoveObserver callback) { 15240 mCallbacks.unregister(callback); 15241 } 15242 15243 @Override 15244 public void handleMessage(Message msg) { 15245 final SomeArgs args = (SomeArgs) msg.obj; 15246 final int n = mCallbacks.beginBroadcast(); 15247 for (int i = 0; i < n; i++) { 15248 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15249 try { 15250 invokeCallback(callback, msg.what, args); 15251 } catch (RemoteException ignored) { 15252 } 15253 } 15254 mCallbacks.finishBroadcast(); 15255 args.recycle(); 15256 } 15257 15258 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15259 throws RemoteException { 15260 switch (what) { 15261 case MSG_CREATED: { 15262 callback.onCreated(args.argi1, (Bundle) args.arg2); 15263 break; 15264 } 15265 case MSG_STATUS_CHANGED: { 15266 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15267 break; 15268 } 15269 } 15270 } 15271 15272 private void notifyCreated(int moveId, Bundle extras) { 15273 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15274 15275 final SomeArgs args = SomeArgs.obtain(); 15276 args.argi1 = moveId; 15277 args.arg2 = extras; 15278 obtainMessage(MSG_CREATED, args).sendToTarget(); 15279 } 15280 15281 private void notifyStatusChanged(int moveId, int status) { 15282 notifyStatusChanged(moveId, status, -1); 15283 } 15284 15285 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15286 Slog.v(TAG, "Move " + moveId + " status " + status); 15287 15288 final SomeArgs args = SomeArgs.obtain(); 15289 args.argi1 = moveId; 15290 args.argi2 = status; 15291 args.arg3 = estMillis; 15292 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15293 15294 synchronized (mLastStatus) { 15295 mLastStatus.put(moveId, status); 15296 } 15297 } 15298 } 15299} 15300