PackageManagerService.java revision 47fc7fe7f6bd5a44c20c4b03d3195f601bcc3735
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 282 private static final int RADIO_UID = Process.PHONE_UID; 283 private static final int LOG_UID = Process.LOG_UID; 284 private static final int NFC_UID = Process.NFC_UID; 285 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 286 private static final int SHELL_UID = Process.SHELL_UID; 287 288 // Cap the size of permission trees that 3rd party apps can define 289 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 290 291 // Suffix used during package installation when copying/moving 292 // package apks to install directory. 293 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 294 295 static final int SCAN_NO_DEX = 1<<1; 296 static final int SCAN_FORCE_DEX = 1<<2; 297 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 298 static final int SCAN_NEW_INSTALL = 1<<4; 299 static final int SCAN_NO_PATHS = 1<<5; 300 static final int SCAN_UPDATE_TIME = 1<<6; 301 static final int SCAN_DEFER_DEX = 1<<7; 302 static final int SCAN_BOOTING = 1<<8; 303 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 304 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 305 static final int SCAN_REQUIRE_KNOWN = 1<<12; 306 static final int SCAN_MOVE = 1<<13; 307 308 static final int REMOVE_CHATTY = 1<<16; 309 310 private static final int[] EMPTY_INT_ARRAY = new int[0]; 311 312 /** 313 * Timeout (in milliseconds) after which the watchdog should declare that 314 * our handler thread is wedged. The usual default for such things is one 315 * minute but we sometimes do very lengthy I/O operations on this thread, 316 * such as installing multi-gigabyte applications, so ours needs to be longer. 317 */ 318 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 319 320 /** 321 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 322 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 323 * settings entry if available, otherwise we use the hardcoded default. If it's been 324 * more than this long since the last fstrim, we force one during the boot sequence. 325 * 326 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 327 * one gets run at the next available charging+idle time. This final mandatory 328 * no-fstrim check kicks in only of the other scheduling criteria is never met. 329 */ 330 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 331 332 /** 333 * Whether verification is enabled by default. 334 */ 335 private static final boolean DEFAULT_VERIFY_ENABLE = true; 336 337 /** 338 * The default maximum time to wait for the verification agent to return in 339 * milliseconds. 340 */ 341 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 342 343 /** 344 * The default response for package verification timeout. 345 * 346 * This can be either PackageManager.VERIFICATION_ALLOW or 347 * PackageManager.VERIFICATION_REJECT. 348 */ 349 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 350 351 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 352 353 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 354 DEFAULT_CONTAINER_PACKAGE, 355 "com.android.defcontainer.DefaultContainerService"); 356 357 private static final String KILL_APP_REASON_GIDS_CHANGED = 358 "permission grant or revoke changed gids"; 359 360 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 361 "permissions revoked"; 362 363 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 364 365 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 366 367 /** Permission grant: not grant the permission. */ 368 private static final int GRANT_DENIED = 1; 369 370 /** Permission grant: grant the permission as an install permission. */ 371 private static final int GRANT_INSTALL = 2; 372 373 /** Permission grant: grant the permission as an install permission for a legacy app. */ 374 private static final int GRANT_INSTALL_LEGACY = 3; 375 376 /** Permission grant: grant the permission as a runtime one. */ 377 private static final int GRANT_RUNTIME = 4; 378 379 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 380 private static final int GRANT_UPGRADE = 5; 381 382 final ServiceThread mHandlerThread; 383 384 final PackageHandler mHandler; 385 386 /** 387 * Messages for {@link #mHandler} that need to wait for system ready before 388 * being dispatched. 389 */ 390 private ArrayList<Message> mPostSystemReadyMessages; 391 392 final int mSdkVersion = Build.VERSION.SDK_INT; 393 394 final Context mContext; 395 final boolean mFactoryTest; 396 final boolean mOnlyCore; 397 final boolean mLazyDexOpt; 398 final long mDexOptLRUThresholdInMills; 399 final DisplayMetrics mMetrics; 400 final int mDefParseFlags; 401 final String[] mSeparateProcesses; 402 final boolean mIsUpgrade; 403 404 // This is where all application persistent data goes. 405 final File mAppDataDir; 406 407 // This is where all application persistent data goes for secondary users. 408 final File mUserAppDataDir; 409 410 /** The location for ASEC container files on internal storage. */ 411 final String mAsecInternalPath; 412 413 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 414 // LOCK HELD. Can be called with mInstallLock held. 415 final Installer mInstaller; 416 417 /** Directory where installed third-party apps stored */ 418 final File mAppInstallDir; 419 420 /** 421 * Directory to which applications installed internally have their 422 * 32 bit native libraries copied. 423 */ 424 private File mAppLib32InstallDir; 425 426 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 427 // apps. 428 final File mDrmAppPrivateInstallDir; 429 430 // ---------------------------------------------------------------- 431 432 // Lock for state used when installing and doing other long running 433 // operations. Methods that must be called with this lock held have 434 // the suffix "LI". 435 final Object mInstallLock = new Object(); 436 437 // ---------------------------------------------------------------- 438 439 // Keys are String (package name), values are Package. This also serves 440 // as the lock for the global state. Methods that must be called with 441 // this lock held have the prefix "LP". 442 final ArrayMap<String, PackageParser.Package> mPackages = 443 new ArrayMap<String, PackageParser.Package>(); 444 445 // Tracks available target package names -> overlay package paths. 446 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 447 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 448 449 final Settings mSettings; 450 boolean mRestoredSettings; 451 452 // System configuration read by SystemConfig. 453 final int[] mGlobalGids; 454 final SparseArray<ArraySet<String>> mSystemPermissions; 455 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 456 457 // If mac_permissions.xml was found for seinfo labeling. 458 boolean mFoundPolicyFile; 459 460 // If a recursive restorecon of /data/data/<pkg> is needed. 461 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 462 463 public static final class SharedLibraryEntry { 464 public final String path; 465 public final String apk; 466 467 SharedLibraryEntry(String _path, String _apk) { 468 path = _path; 469 apk = _apk; 470 } 471 } 472 473 // Currently known shared libraries. 474 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 475 new ArrayMap<String, SharedLibraryEntry>(); 476 477 // All available activities, for your resolving pleasure. 478 final ActivityIntentResolver mActivities = 479 new ActivityIntentResolver(); 480 481 // All available receivers, for your resolving pleasure. 482 final ActivityIntentResolver mReceivers = 483 new ActivityIntentResolver(); 484 485 // All available services, for your resolving pleasure. 486 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 487 488 // All available providers, for your resolving pleasure. 489 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 490 491 // Mapping from provider base names (first directory in content URI codePath) 492 // to the provider information. 493 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 494 new ArrayMap<String, PackageParser.Provider>(); 495 496 // Mapping from instrumentation class names to info about them. 497 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 498 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 499 500 // Mapping from permission names to info about them. 501 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 502 new ArrayMap<String, PackageParser.PermissionGroup>(); 503 504 // Packages whose data we have transfered into another package, thus 505 // should no longer exist. 506 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 507 508 // Broadcast actions that are only available to the system. 509 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 510 511 /** List of packages waiting for verification. */ 512 final SparseArray<PackageVerificationState> mPendingVerification 513 = new SparseArray<PackageVerificationState>(); 514 515 /** Set of packages associated with each app op permission. */ 516 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 517 518 final PackageInstallerService mInstallerService; 519 520 private final PackageDexOptimizer mPackageDexOptimizer; 521 522 private AtomicInteger mNextMoveId = new AtomicInteger(); 523 private final MoveCallbacks mMoveCallbacks; 524 525 // Cache of users who need badging. 526 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 527 528 /** Token for keys in mPendingVerification. */ 529 private int mPendingVerificationToken = 0; 530 531 volatile boolean mSystemReady; 532 volatile boolean mSafeMode; 533 volatile boolean mHasSystemUidErrors; 534 535 ApplicationInfo mAndroidApplication; 536 final ActivityInfo mResolveActivity = new ActivityInfo(); 537 final ResolveInfo mResolveInfo = new ResolveInfo(); 538 ComponentName mResolveComponentName; 539 PackageParser.Package mPlatformPackage; 540 ComponentName mCustomResolverComponentName; 541 542 boolean mResolverReplaced = false; 543 544 private final ComponentName mIntentFilterVerifierComponent; 545 private int mIntentFilterVerificationToken = 0; 546 547 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 548 = new SparseArray<IntentFilterVerificationState>(); 549 550 private interface IntentFilterVerifier<T extends IntentFilter> { 551 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 552 T filter, String packageName); 553 void startVerifications(int userId); 554 void receiveVerificationResponse(int verificationId); 555 } 556 557 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 558 private Context mContext; 559 private ComponentName mIntentFilterVerifierComponent; 560 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 561 562 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 563 mContext = context; 564 mIntentFilterVerifierComponent = verifierComponent; 565 } 566 567 private String getDefaultScheme() { 568 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 569 return IntentFilter.SCHEME_HTTP; 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 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 624 } 625 626 public void receiveVerificationResponse(int verificationId) { 627 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 628 629 final boolean verified = ivs.isVerified(); 630 631 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 632 final int count = filters.size(); 633 for (int n=0; n<count; n++) { 634 PackageParser.ActivityIntentInfo filter = filters.get(n); 635 filter.setVerified(verified); 636 637 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 638 + verified + " and hosts:" + ivs.getHostsString()); 639 } 640 641 mIntentFilterVerificationStates.remove(verificationId); 642 643 final String packageName = ivs.getPackageName(); 644 IntentFilterVerificationInfo ivi = null; 645 646 synchronized (mPackages) { 647 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 648 } 649 if (ivi == null) { 650 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 651 + verificationId + " packageName:" + packageName); 652 return; 653 } 654 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 655 + verificationId); 656 657 synchronized (mPackages) { 658 if (verified) { 659 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 660 } else { 661 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 662 } 663 scheduleWriteSettingsLocked(); 664 665 final int userId = ivs.getUserId(); 666 if (userId != UserHandle.USER_ALL) { 667 final int userStatus = 668 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 669 670 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 671 boolean needUpdate = false; 672 673 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 674 // already been set by the User thru the Disambiguation dialog 675 switch (userStatus) { 676 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 677 if (verified) { 678 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 679 } else { 680 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 681 } 682 needUpdate = true; 683 break; 684 685 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 686 if (verified) { 687 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 688 needUpdate = true; 689 } 690 break; 691 692 default: 693 // Nothing to do 694 } 695 696 if (needUpdate) { 697 mSettings.updateIntentFilterVerificationStatusLPw( 698 packageName, updatedStatus, userId); 699 scheduleWritePackageRestrictionsLocked(userId); 700 } 701 } 702 } 703 } 704 705 @Override 706 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 707 ActivityIntentInfo filter, String packageName) { 708 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 709 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 710 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 711 return false; 712 } 713 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 714 if (ivs == null) { 715 ivs = createDomainVerificationState(verifierId, userId, verificationId, 716 packageName); 717 } 718 if (!hasValidDomains(filter)) { 719 return false; 720 } 721 ivs.addFilter(filter); 722 return true; 723 } 724 725 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 726 int userId, int verificationId, String packageName) { 727 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 728 verifierId, userId, packageName); 729 ivs.setPendingState(); 730 synchronized (mPackages) { 731 mIntentFilterVerificationStates.append(verificationId, ivs); 732 mCurrentIntentFilterVerifications.add(verificationId); 733 } 734 return ivs; 735 } 736 } 737 738 private static boolean hasValidDomains(ActivityIntentInfo filter) { 739 return hasValidDomains(filter, true); 740 } 741 742 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 743 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 744 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 745 if (!hasHTTPorHTTPS) { 746 if (logging) { 747 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 748 } 749 return false; 750 } 751 return true; 752 } 753 754 private IntentFilterVerifier mIntentFilterVerifier; 755 756 // Set of pending broadcasts for aggregating enable/disable of components. 757 static class PendingPackageBroadcasts { 758 // for each user id, a map of <package name -> components within that package> 759 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 760 761 public PendingPackageBroadcasts() { 762 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 763 } 764 765 public ArrayList<String> get(int userId, String packageName) { 766 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 767 return packages.get(packageName); 768 } 769 770 public void put(int userId, String packageName, ArrayList<String> components) { 771 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 772 packages.put(packageName, components); 773 } 774 775 public void remove(int userId, String packageName) { 776 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 777 if (packages != null) { 778 packages.remove(packageName); 779 } 780 } 781 782 public void remove(int userId) { 783 mUidMap.remove(userId); 784 } 785 786 public int userIdCount() { 787 return mUidMap.size(); 788 } 789 790 public int userIdAt(int n) { 791 return mUidMap.keyAt(n); 792 } 793 794 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 795 return mUidMap.get(userId); 796 } 797 798 public int size() { 799 // total number of pending broadcast entries across all userIds 800 int num = 0; 801 for (int i = 0; i< mUidMap.size(); i++) { 802 num += mUidMap.valueAt(i).size(); 803 } 804 return num; 805 } 806 807 public void clear() { 808 mUidMap.clear(); 809 } 810 811 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 812 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 813 if (map == null) { 814 map = new ArrayMap<String, ArrayList<String>>(); 815 mUidMap.put(userId, map); 816 } 817 return map; 818 } 819 } 820 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 821 822 // Service Connection to remote media container service to copy 823 // package uri's from external media onto secure containers 824 // or internal storage. 825 private IMediaContainerService mContainerService = null; 826 827 static final int SEND_PENDING_BROADCAST = 1; 828 static final int MCS_BOUND = 3; 829 static final int END_COPY = 4; 830 static final int INIT_COPY = 5; 831 static final int MCS_UNBIND = 6; 832 static final int START_CLEANING_PACKAGE = 7; 833 static final int FIND_INSTALL_LOC = 8; 834 static final int POST_INSTALL = 9; 835 static final int MCS_RECONNECT = 10; 836 static final int MCS_GIVE_UP = 11; 837 static final int UPDATED_MEDIA_STATUS = 12; 838 static final int WRITE_SETTINGS = 13; 839 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 840 static final int PACKAGE_VERIFIED = 15; 841 static final int CHECK_PENDING_VERIFICATION = 16; 842 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 843 static final int INTENT_FILTER_VERIFIED = 18; 844 845 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 846 847 // Delay time in millisecs 848 static final int BROADCAST_DELAY = 10 * 1000; 849 850 static UserManagerService sUserManager; 851 852 // Stores a list of users whose package restrictions file needs to be updated 853 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 854 855 final private DefaultContainerConnection mDefContainerConn = 856 new DefaultContainerConnection(); 857 class DefaultContainerConnection implements ServiceConnection { 858 public void onServiceConnected(ComponentName name, IBinder service) { 859 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 860 IMediaContainerService imcs = 861 IMediaContainerService.Stub.asInterface(service); 862 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 863 } 864 865 public void onServiceDisconnected(ComponentName name) { 866 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 867 } 868 }; 869 870 // Recordkeeping of restore-after-install operations that are currently in flight 871 // between the Package Manager and the Backup Manager 872 class PostInstallData { 873 public InstallArgs args; 874 public PackageInstalledInfo res; 875 876 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 877 args = _a; 878 res = _r; 879 } 880 }; 881 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 882 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 883 884 // backup/restore of preferred activity state 885 private static final String TAG_PREFERRED_BACKUP = "pa"; 886 887 private final String mRequiredVerifierPackage; 888 889 private final PackageUsage mPackageUsage = new PackageUsage(); 890 891 private class PackageUsage { 892 private static final int WRITE_INTERVAL 893 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 894 895 private final Object mFileLock = new Object(); 896 private final AtomicLong mLastWritten = new AtomicLong(0); 897 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 898 899 private boolean mIsHistoricalPackageUsageAvailable = true; 900 901 boolean isHistoricalPackageUsageAvailable() { 902 return mIsHistoricalPackageUsageAvailable; 903 } 904 905 void write(boolean force) { 906 if (force) { 907 writeInternal(); 908 return; 909 } 910 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 911 && !DEBUG_DEXOPT) { 912 return; 913 } 914 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 915 new Thread("PackageUsage_DiskWriter") { 916 @Override 917 public void run() { 918 try { 919 writeInternal(); 920 } finally { 921 mBackgroundWriteRunning.set(false); 922 } 923 } 924 }.start(); 925 } 926 } 927 928 private void writeInternal() { 929 synchronized (mPackages) { 930 synchronized (mFileLock) { 931 AtomicFile file = getFile(); 932 FileOutputStream f = null; 933 try { 934 f = file.startWrite(); 935 BufferedOutputStream out = new BufferedOutputStream(f); 936 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 937 StringBuilder sb = new StringBuilder(); 938 for (PackageParser.Package pkg : mPackages.values()) { 939 if (pkg.mLastPackageUsageTimeInMills == 0) { 940 continue; 941 } 942 sb.setLength(0); 943 sb.append(pkg.packageName); 944 sb.append(' '); 945 sb.append((long)pkg.mLastPackageUsageTimeInMills); 946 sb.append('\n'); 947 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 948 } 949 out.flush(); 950 file.finishWrite(f); 951 } catch (IOException e) { 952 if (f != null) { 953 file.failWrite(f); 954 } 955 Log.e(TAG, "Failed to write package usage times", e); 956 } 957 } 958 } 959 mLastWritten.set(SystemClock.elapsedRealtime()); 960 } 961 962 void readLP() { 963 synchronized (mFileLock) { 964 AtomicFile file = getFile(); 965 BufferedInputStream in = null; 966 try { 967 in = new BufferedInputStream(file.openRead()); 968 StringBuffer sb = new StringBuffer(); 969 while (true) { 970 String packageName = readToken(in, sb, ' '); 971 if (packageName == null) { 972 break; 973 } 974 String timeInMillisString = readToken(in, sb, '\n'); 975 if (timeInMillisString == null) { 976 throw new IOException("Failed to find last usage time for package " 977 + packageName); 978 } 979 PackageParser.Package pkg = mPackages.get(packageName); 980 if (pkg == null) { 981 continue; 982 } 983 long timeInMillis; 984 try { 985 timeInMillis = Long.parseLong(timeInMillisString.toString()); 986 } catch (NumberFormatException e) { 987 throw new IOException("Failed to parse " + timeInMillisString 988 + " as a long.", e); 989 } 990 pkg.mLastPackageUsageTimeInMills = timeInMillis; 991 } 992 } catch (FileNotFoundException expected) { 993 mIsHistoricalPackageUsageAvailable = false; 994 } catch (IOException e) { 995 Log.w(TAG, "Failed to read package usage times", e); 996 } finally { 997 IoUtils.closeQuietly(in); 998 } 999 } 1000 mLastWritten.set(SystemClock.elapsedRealtime()); 1001 } 1002 1003 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1004 throws IOException { 1005 sb.setLength(0); 1006 while (true) { 1007 int ch = in.read(); 1008 if (ch == -1) { 1009 if (sb.length() == 0) { 1010 return null; 1011 } 1012 throw new IOException("Unexpected EOF"); 1013 } 1014 if (ch == endOfToken) { 1015 return sb.toString(); 1016 } 1017 sb.append((char)ch); 1018 } 1019 } 1020 1021 private AtomicFile getFile() { 1022 File dataDir = Environment.getDataDirectory(); 1023 File systemDir = new File(dataDir, "system"); 1024 File fname = new File(systemDir, "package-usage.list"); 1025 return new AtomicFile(fname); 1026 } 1027 } 1028 1029 class PackageHandler extends Handler { 1030 private boolean mBound = false; 1031 final ArrayList<HandlerParams> mPendingInstalls = 1032 new ArrayList<HandlerParams>(); 1033 1034 private boolean connectToService() { 1035 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1036 " DefaultContainerService"); 1037 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1038 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1039 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1040 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1041 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1042 mBound = true; 1043 return true; 1044 } 1045 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1046 return false; 1047 } 1048 1049 private void disconnectService() { 1050 mContainerService = null; 1051 mBound = false; 1052 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1053 mContext.unbindService(mDefContainerConn); 1054 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1055 } 1056 1057 PackageHandler(Looper looper) { 1058 super(looper); 1059 } 1060 1061 public void handleMessage(Message msg) { 1062 try { 1063 doHandleMessage(msg); 1064 } finally { 1065 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1066 } 1067 } 1068 1069 void doHandleMessage(Message msg) { 1070 switch (msg.what) { 1071 case INIT_COPY: { 1072 HandlerParams params = (HandlerParams) msg.obj; 1073 int idx = mPendingInstalls.size(); 1074 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1075 // If a bind was already initiated we dont really 1076 // need to do anything. The pending install 1077 // will be processed later on. 1078 if (!mBound) { 1079 // If this is the only one pending we might 1080 // have to bind to the service again. 1081 if (!connectToService()) { 1082 Slog.e(TAG, "Failed to bind to media container service"); 1083 params.serviceError(); 1084 return; 1085 } else { 1086 // Once we bind to the service, the first 1087 // pending request will be processed. 1088 mPendingInstalls.add(idx, params); 1089 } 1090 } else { 1091 mPendingInstalls.add(idx, params); 1092 // Already bound to the service. Just make 1093 // sure we trigger off processing the first request. 1094 if (idx == 0) { 1095 mHandler.sendEmptyMessage(MCS_BOUND); 1096 } 1097 } 1098 break; 1099 } 1100 case MCS_BOUND: { 1101 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1102 if (msg.obj != null) { 1103 mContainerService = (IMediaContainerService) msg.obj; 1104 } 1105 if (mContainerService == null) { 1106 // Something seriously wrong. Bail out 1107 Slog.e(TAG, "Cannot bind to media container service"); 1108 for (HandlerParams params : mPendingInstalls) { 1109 // Indicate service bind error 1110 params.serviceError(); 1111 } 1112 mPendingInstalls.clear(); 1113 } else if (mPendingInstalls.size() > 0) { 1114 HandlerParams params = mPendingInstalls.get(0); 1115 if (params != null) { 1116 if (params.startCopy()) { 1117 // We are done... look for more work or to 1118 // go idle. 1119 if (DEBUG_SD_INSTALL) Log.i(TAG, 1120 "Checking for more work or unbind..."); 1121 // Delete pending install 1122 if (mPendingInstalls.size() > 0) { 1123 mPendingInstalls.remove(0); 1124 } 1125 if (mPendingInstalls.size() == 0) { 1126 if (mBound) { 1127 if (DEBUG_SD_INSTALL) Log.i(TAG, 1128 "Posting delayed MCS_UNBIND"); 1129 removeMessages(MCS_UNBIND); 1130 Message ubmsg = obtainMessage(MCS_UNBIND); 1131 // Unbind after a little delay, to avoid 1132 // continual thrashing. 1133 sendMessageDelayed(ubmsg, 10000); 1134 } 1135 } else { 1136 // There are more pending requests in queue. 1137 // Just post MCS_BOUND message to trigger processing 1138 // of next pending install. 1139 if (DEBUG_SD_INSTALL) Log.i(TAG, 1140 "Posting MCS_BOUND for next work"); 1141 mHandler.sendEmptyMessage(MCS_BOUND); 1142 } 1143 } 1144 } 1145 } else { 1146 // Should never happen ideally. 1147 Slog.w(TAG, "Empty queue"); 1148 } 1149 break; 1150 } 1151 case MCS_RECONNECT: { 1152 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1153 if (mPendingInstalls.size() > 0) { 1154 if (mBound) { 1155 disconnectService(); 1156 } 1157 if (!connectToService()) { 1158 Slog.e(TAG, "Failed to bind to media container service"); 1159 for (HandlerParams params : mPendingInstalls) { 1160 // Indicate service bind error 1161 params.serviceError(); 1162 } 1163 mPendingInstalls.clear(); 1164 } 1165 } 1166 break; 1167 } 1168 case MCS_UNBIND: { 1169 // If there is no actual work left, then time to unbind. 1170 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1171 1172 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1173 if (mBound) { 1174 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1175 1176 disconnectService(); 1177 } 1178 } else if (mPendingInstalls.size() > 0) { 1179 // There are more pending requests in queue. 1180 // Just post MCS_BOUND message to trigger processing 1181 // of next pending install. 1182 mHandler.sendEmptyMessage(MCS_BOUND); 1183 } 1184 1185 break; 1186 } 1187 case MCS_GIVE_UP: { 1188 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1189 mPendingInstalls.remove(0); 1190 break; 1191 } 1192 case SEND_PENDING_BROADCAST: { 1193 String packages[]; 1194 ArrayList<String> components[]; 1195 int size = 0; 1196 int uids[]; 1197 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1198 synchronized (mPackages) { 1199 if (mPendingBroadcasts == null) { 1200 return; 1201 } 1202 size = mPendingBroadcasts.size(); 1203 if (size <= 0) { 1204 // Nothing to be done. Just return 1205 return; 1206 } 1207 packages = new String[size]; 1208 components = new ArrayList[size]; 1209 uids = new int[size]; 1210 int i = 0; // filling out the above arrays 1211 1212 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1213 int packageUserId = mPendingBroadcasts.userIdAt(n); 1214 Iterator<Map.Entry<String, ArrayList<String>>> it 1215 = mPendingBroadcasts.packagesForUserId(packageUserId) 1216 .entrySet().iterator(); 1217 while (it.hasNext() && i < size) { 1218 Map.Entry<String, ArrayList<String>> ent = it.next(); 1219 packages[i] = ent.getKey(); 1220 components[i] = ent.getValue(); 1221 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1222 uids[i] = (ps != null) 1223 ? UserHandle.getUid(packageUserId, ps.appId) 1224 : -1; 1225 i++; 1226 } 1227 } 1228 size = i; 1229 mPendingBroadcasts.clear(); 1230 } 1231 // Send broadcasts 1232 for (int i = 0; i < size; i++) { 1233 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1234 } 1235 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1236 break; 1237 } 1238 case START_CLEANING_PACKAGE: { 1239 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1240 final String packageName = (String)msg.obj; 1241 final int userId = msg.arg1; 1242 final boolean andCode = msg.arg2 != 0; 1243 synchronized (mPackages) { 1244 if (userId == UserHandle.USER_ALL) { 1245 int[] users = sUserManager.getUserIds(); 1246 for (int user : users) { 1247 mSettings.addPackageToCleanLPw( 1248 new PackageCleanItem(user, packageName, andCode)); 1249 } 1250 } else { 1251 mSettings.addPackageToCleanLPw( 1252 new PackageCleanItem(userId, packageName, andCode)); 1253 } 1254 } 1255 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1256 startCleaningPackages(); 1257 } break; 1258 case POST_INSTALL: { 1259 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1260 PostInstallData data = mRunningInstalls.get(msg.arg1); 1261 mRunningInstalls.delete(msg.arg1); 1262 boolean deleteOld = false; 1263 1264 if (data != null) { 1265 InstallArgs args = data.args; 1266 PackageInstalledInfo res = data.res; 1267 1268 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1269 res.removedInfo.sendBroadcast(false, true, false); 1270 Bundle extras = new Bundle(1); 1271 extras.putInt(Intent.EXTRA_UID, res.uid); 1272 1273 // Now that we successfully installed the package, grant runtime 1274 // permissions if requested before broadcasting the install. 1275 if ((args.installFlags 1276 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1277 grantRequestedRuntimePermissions(res.pkg, 1278 args.user.getIdentifier()); 1279 } 1280 1281 // Determine the set of users who are adding this 1282 // package for the first time vs. those who are seeing 1283 // an update. 1284 int[] firstUsers; 1285 int[] updateUsers = new int[0]; 1286 if (res.origUsers == null || res.origUsers.length == 0) { 1287 firstUsers = res.newUsers; 1288 } else { 1289 firstUsers = new int[0]; 1290 for (int i=0; i<res.newUsers.length; i++) { 1291 int user = res.newUsers[i]; 1292 boolean isNew = true; 1293 for (int j=0; j<res.origUsers.length; j++) { 1294 if (res.origUsers[j] == user) { 1295 isNew = false; 1296 break; 1297 } 1298 } 1299 if (isNew) { 1300 int[] newFirst = new int[firstUsers.length+1]; 1301 System.arraycopy(firstUsers, 0, newFirst, 0, 1302 firstUsers.length); 1303 newFirst[firstUsers.length] = user; 1304 firstUsers = newFirst; 1305 } else { 1306 int[] newUpdate = new int[updateUsers.length+1]; 1307 System.arraycopy(updateUsers, 0, newUpdate, 0, 1308 updateUsers.length); 1309 newUpdate[updateUsers.length] = user; 1310 updateUsers = newUpdate; 1311 } 1312 } 1313 } 1314 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1315 res.pkg.applicationInfo.packageName, 1316 extras, null, null, firstUsers); 1317 final boolean update = res.removedInfo.removedPackage != null; 1318 if (update) { 1319 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1320 } 1321 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1322 res.pkg.applicationInfo.packageName, 1323 extras, null, null, updateUsers); 1324 if (update) { 1325 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1326 res.pkg.applicationInfo.packageName, 1327 extras, null, null, updateUsers); 1328 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1329 null, null, 1330 res.pkg.applicationInfo.packageName, null, updateUsers); 1331 1332 // treat asec-hosted packages like removable media on upgrade 1333 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1334 if (DEBUG_INSTALL) { 1335 Slog.i(TAG, "upgrading pkg " + res.pkg 1336 + " is ASEC-hosted -> AVAILABLE"); 1337 } 1338 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1339 ArrayList<String> pkgList = new ArrayList<String>(1); 1340 pkgList.add(res.pkg.applicationInfo.packageName); 1341 sendResourcesChangedBroadcast(true, true, 1342 pkgList,uidArray, null); 1343 } 1344 } 1345 if (res.removedInfo.args != null) { 1346 // Remove the replaced package's older resources safely now 1347 deleteOld = true; 1348 } 1349 1350 // Log current value of "unknown sources" setting 1351 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1352 getUnknownSourcesSettings()); 1353 } 1354 // Force a gc to clear up things 1355 Runtime.getRuntime().gc(); 1356 // We delete after a gc for applications on sdcard. 1357 if (deleteOld) { 1358 synchronized (mInstallLock) { 1359 res.removedInfo.args.doPostDeleteLI(true); 1360 } 1361 } 1362 if (args.observer != null) { 1363 try { 1364 Bundle extras = extrasForInstallResult(res); 1365 args.observer.onPackageInstalled(res.name, res.returnCode, 1366 res.returnMsg, extras); 1367 } catch (RemoteException e) { 1368 Slog.i(TAG, "Observer no longer exists."); 1369 } 1370 } 1371 } else { 1372 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1373 } 1374 } break; 1375 case UPDATED_MEDIA_STATUS: { 1376 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1377 boolean reportStatus = msg.arg1 == 1; 1378 boolean doGc = msg.arg2 == 1; 1379 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1380 if (doGc) { 1381 // Force a gc to clear up stale containers. 1382 Runtime.getRuntime().gc(); 1383 } 1384 if (msg.obj != null) { 1385 @SuppressWarnings("unchecked") 1386 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1387 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1388 // Unload containers 1389 unloadAllContainers(args); 1390 } 1391 if (reportStatus) { 1392 try { 1393 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1394 PackageHelper.getMountService().finishMediaUpdate(); 1395 } catch (RemoteException e) { 1396 Log.e(TAG, "MountService not running?"); 1397 } 1398 } 1399 } break; 1400 case WRITE_SETTINGS: { 1401 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1402 synchronized (mPackages) { 1403 removeMessages(WRITE_SETTINGS); 1404 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1405 mSettings.writeLPr(); 1406 mDirtyUsers.clear(); 1407 } 1408 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1409 } break; 1410 case WRITE_PACKAGE_RESTRICTIONS: { 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1412 synchronized (mPackages) { 1413 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1414 for (int userId : mDirtyUsers) { 1415 mSettings.writePackageRestrictionsLPr(userId); 1416 } 1417 mDirtyUsers.clear(); 1418 } 1419 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1420 } break; 1421 case CHECK_PENDING_VERIFICATION: { 1422 final int verificationId = msg.arg1; 1423 final PackageVerificationState state = mPendingVerification.get(verificationId); 1424 1425 if ((state != null) && !state.timeoutExtended()) { 1426 final InstallArgs args = state.getInstallArgs(); 1427 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1428 1429 Slog.i(TAG, "Verification timed out for " + originUri); 1430 mPendingVerification.remove(verificationId); 1431 1432 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1433 1434 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1435 Slog.i(TAG, "Continuing with installation of " + originUri); 1436 state.setVerifierResponse(Binder.getCallingUid(), 1437 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1438 broadcastPackageVerified(verificationId, originUri, 1439 PackageManager.VERIFICATION_ALLOW, 1440 state.getInstallArgs().getUser()); 1441 try { 1442 ret = args.copyApk(mContainerService, true); 1443 } catch (RemoteException e) { 1444 Slog.e(TAG, "Could not contact the ContainerService"); 1445 } 1446 } else { 1447 broadcastPackageVerified(verificationId, originUri, 1448 PackageManager.VERIFICATION_REJECT, 1449 state.getInstallArgs().getUser()); 1450 } 1451 1452 processPendingInstall(args, ret); 1453 mHandler.sendEmptyMessage(MCS_UNBIND); 1454 } 1455 break; 1456 } 1457 case PACKAGE_VERIFIED: { 1458 final int verificationId = msg.arg1; 1459 1460 final PackageVerificationState state = mPendingVerification.get(verificationId); 1461 if (state == null) { 1462 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1463 break; 1464 } 1465 1466 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1467 1468 state.setVerifierResponse(response.callerUid, response.code); 1469 1470 if (state.isVerificationComplete()) { 1471 mPendingVerification.remove(verificationId); 1472 1473 final InstallArgs args = state.getInstallArgs(); 1474 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1475 1476 int ret; 1477 if (state.isInstallAllowed()) { 1478 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1479 broadcastPackageVerified(verificationId, originUri, 1480 response.code, state.getInstallArgs().getUser()); 1481 try { 1482 ret = args.copyApk(mContainerService, true); 1483 } catch (RemoteException e) { 1484 Slog.e(TAG, "Could not contact the ContainerService"); 1485 } 1486 } else { 1487 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1488 } 1489 1490 processPendingInstall(args, ret); 1491 1492 mHandler.sendEmptyMessage(MCS_UNBIND); 1493 } 1494 1495 break; 1496 } 1497 case START_INTENT_FILTER_VERIFICATIONS: { 1498 int userId = msg.arg1; 1499 int verifierUid = msg.arg2; 1500 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1501 1502 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1503 break; 1504 } 1505 case INTENT_FILTER_VERIFIED: { 1506 final int verificationId = msg.arg1; 1507 1508 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1509 verificationId); 1510 if (state == null) { 1511 Slog.w(TAG, "Invalid IntentFilter verification token " 1512 + verificationId + " received"); 1513 break; 1514 } 1515 1516 final int userId = state.getUserId(); 1517 1518 Slog.d(TAG, "Processing IntentFilter verification with token:" 1519 + verificationId + " and userId:" + userId); 1520 1521 final IntentFilterVerificationResponse response = 1522 (IntentFilterVerificationResponse) msg.obj; 1523 1524 state.setVerifierResponse(response.callerUid, response.code); 1525 1526 Slog.d(TAG, "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 Slog.d(TAG, "Domains failing verification: " 1533 + response.getFailedDomainsString()); 1534 } 1535 1536 if (state.isVerificationComplete()) { 1537 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1538 } else { 1539 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1540 + " was not said to be complete"); 1541 } 1542 1543 break; 1544 } 1545 } 1546 } 1547 } 1548 1549 private StorageEventListener mStorageListener = new StorageEventListener() { 1550 @Override 1551 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1552 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1553 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1554 // TODO: ensure that private directories exist for all active users 1555 // TODO: remove user data whose serial number doesn't match 1556 loadPrivatePackages(vol); 1557 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1558 unloadPrivatePackages(vol); 1559 } 1560 } 1561 1562 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1563 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1564 updateExternalMediaStatus(true, false); 1565 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1566 updateExternalMediaStatus(false, false); 1567 } 1568 } 1569 } 1570 1571 @Override 1572 public void onVolumeForgotten(String fsUuid) { 1573 // TODO: remove all packages hosted on this uuid 1574 } 1575 }; 1576 1577 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1578 if (userId >= UserHandle.USER_OWNER) { 1579 grantRequestedRuntimePermissionsForUser(pkg, userId); 1580 } else if (userId == UserHandle.USER_ALL) { 1581 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1582 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1583 } 1584 } 1585 } 1586 1587 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1588 SettingBase sb = (SettingBase) pkg.mExtras; 1589 if (sb == null) { 1590 return; 1591 } 1592 1593 PermissionsState permissionsState = sb.getPermissionsState(); 1594 1595 for (String permission : pkg.requestedPermissions) { 1596 BasePermission bp = mSettings.mPermissions.get(permission); 1597 if (bp != null && bp.isRuntime()) { 1598 permissionsState.grantRuntimePermission(bp, userId); 1599 } 1600 } 1601 } 1602 1603 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1604 Bundle extras = null; 1605 switch (res.returnCode) { 1606 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1607 extras = new Bundle(); 1608 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1609 res.origPermission); 1610 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1611 res.origPackage); 1612 break; 1613 } 1614 case PackageManager.INSTALL_SUCCEEDED: { 1615 extras = new Bundle(); 1616 extras.putBoolean(Intent.EXTRA_REPLACING, 1617 res.removedInfo != null && res.removedInfo.removedPackage != null); 1618 break; 1619 } 1620 } 1621 return extras; 1622 } 1623 1624 void scheduleWriteSettingsLocked() { 1625 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1626 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1627 } 1628 } 1629 1630 void scheduleWritePackageRestrictionsLocked(int userId) { 1631 if (!sUserManager.exists(userId)) return; 1632 mDirtyUsers.add(userId); 1633 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1634 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1635 } 1636 } 1637 1638 public static PackageManagerService main(Context context, Installer installer, 1639 boolean factoryTest, boolean onlyCore) { 1640 PackageManagerService m = new PackageManagerService(context, installer, 1641 factoryTest, onlyCore); 1642 ServiceManager.addService("package", m); 1643 return m; 1644 } 1645 1646 static String[] splitString(String str, char sep) { 1647 int count = 1; 1648 int i = 0; 1649 while ((i=str.indexOf(sep, i)) >= 0) { 1650 count++; 1651 i++; 1652 } 1653 1654 String[] res = new String[count]; 1655 i=0; 1656 count = 0; 1657 int lastI=0; 1658 while ((i=str.indexOf(sep, i)) >= 0) { 1659 res[count] = str.substring(lastI, i); 1660 count++; 1661 i++; 1662 lastI = i; 1663 } 1664 res[count] = str.substring(lastI, str.length()); 1665 return res; 1666 } 1667 1668 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1669 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1670 Context.DISPLAY_SERVICE); 1671 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1672 } 1673 1674 public PackageManagerService(Context context, Installer installer, 1675 boolean factoryTest, boolean onlyCore) { 1676 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1677 SystemClock.uptimeMillis()); 1678 1679 if (mSdkVersion <= 0) { 1680 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1681 } 1682 1683 mContext = context; 1684 mFactoryTest = factoryTest; 1685 mOnlyCore = onlyCore; 1686 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1687 mMetrics = new DisplayMetrics(); 1688 mSettings = new Settings(mPackages); 1689 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1690 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1691 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1692 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1693 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1694 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1695 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1696 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1697 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1698 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1699 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1700 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1701 1702 // TODO: add a property to control this? 1703 long dexOptLRUThresholdInMinutes; 1704 if (mLazyDexOpt) { 1705 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1706 } else { 1707 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1708 } 1709 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1710 1711 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1712 if (separateProcesses != null && separateProcesses.length() > 0) { 1713 if ("*".equals(separateProcesses)) { 1714 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1715 mSeparateProcesses = null; 1716 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1717 } else { 1718 mDefParseFlags = 0; 1719 mSeparateProcesses = separateProcesses.split(","); 1720 Slog.w(TAG, "Running with debug.separate_processes: " 1721 + separateProcesses); 1722 } 1723 } else { 1724 mDefParseFlags = 0; 1725 mSeparateProcesses = null; 1726 } 1727 1728 mInstaller = installer; 1729 mPackageDexOptimizer = new PackageDexOptimizer(this); 1730 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1731 1732 getDefaultDisplayMetrics(context, mMetrics); 1733 1734 SystemConfig systemConfig = SystemConfig.getInstance(); 1735 mGlobalGids = systemConfig.getGlobalGids(); 1736 mSystemPermissions = systemConfig.getSystemPermissions(); 1737 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1738 1739 synchronized (mInstallLock) { 1740 // writer 1741 synchronized (mPackages) { 1742 mHandlerThread = new ServiceThread(TAG, 1743 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1744 mHandlerThread.start(); 1745 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1746 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1747 1748 File dataDir = Environment.getDataDirectory(); 1749 mAppDataDir = new File(dataDir, "data"); 1750 mAppInstallDir = new File(dataDir, "app"); 1751 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1752 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1753 mUserAppDataDir = new File(dataDir, "user"); 1754 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1755 1756 sUserManager = new UserManagerService(context, this, 1757 mInstallLock, mPackages); 1758 1759 // Propagate permission configuration in to package manager. 1760 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1761 = systemConfig.getPermissions(); 1762 for (int i=0; i<permConfig.size(); i++) { 1763 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1764 BasePermission bp = mSettings.mPermissions.get(perm.name); 1765 if (bp == null) { 1766 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1767 mSettings.mPermissions.put(perm.name, bp); 1768 } 1769 if (perm.gids != null) { 1770 bp.setGids(perm.gids, perm.perUser); 1771 } 1772 } 1773 1774 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1775 for (int i=0; i<libConfig.size(); i++) { 1776 mSharedLibraries.put(libConfig.keyAt(i), 1777 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1778 } 1779 1780 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1781 1782 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1783 mSdkVersion, mOnlyCore); 1784 1785 String customResolverActivity = Resources.getSystem().getString( 1786 R.string.config_customResolverActivity); 1787 if (TextUtils.isEmpty(customResolverActivity)) { 1788 customResolverActivity = null; 1789 } else { 1790 mCustomResolverComponentName = ComponentName.unflattenFromString( 1791 customResolverActivity); 1792 } 1793 1794 long startTime = SystemClock.uptimeMillis(); 1795 1796 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1797 startTime); 1798 1799 // Set flag to monitor and not change apk file paths when 1800 // scanning install directories. 1801 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1802 1803 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1804 1805 /** 1806 * Add everything in the in the boot class path to the 1807 * list of process files because dexopt will have been run 1808 * if necessary during zygote startup. 1809 */ 1810 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1811 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1812 1813 if (bootClassPath != null) { 1814 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1815 for (String element : bootClassPathElements) { 1816 alreadyDexOpted.add(element); 1817 } 1818 } else { 1819 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1820 } 1821 1822 if (systemServerClassPath != null) { 1823 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1824 for (String element : systemServerClassPathElements) { 1825 alreadyDexOpted.add(element); 1826 } 1827 } else { 1828 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1829 } 1830 1831 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1832 final String[] dexCodeInstructionSets = 1833 getDexCodeInstructionSets( 1834 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1835 1836 /** 1837 * Ensure all external libraries have had dexopt run on them. 1838 */ 1839 if (mSharedLibraries.size() > 0) { 1840 // NOTE: For now, we're compiling these system "shared libraries" 1841 // (and framework jars) into all available architectures. It's possible 1842 // to compile them only when we come across an app that uses them (there's 1843 // already logic for that in scanPackageLI) but that adds some complexity. 1844 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1845 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1846 final String lib = libEntry.path; 1847 if (lib == null) { 1848 continue; 1849 } 1850 1851 try { 1852 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1853 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1854 alreadyDexOpted.add(lib); 1855 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1856 } 1857 } catch (FileNotFoundException e) { 1858 Slog.w(TAG, "Library not found: " + lib); 1859 } catch (IOException e) { 1860 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1861 + e.getMessage()); 1862 } 1863 } 1864 } 1865 } 1866 1867 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1868 1869 // Gross hack for now: we know this file doesn't contain any 1870 // code, so don't dexopt it to avoid the resulting log spew. 1871 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1872 1873 // Gross hack for now: we know this file is only part of 1874 // the boot class path for art, so don't dexopt it to 1875 // avoid the resulting log spew. 1876 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1877 1878 /** 1879 * And there are a number of commands implemented in Java, which 1880 * we currently need to do the dexopt on so that they can be 1881 * run from a non-root shell. 1882 */ 1883 String[] frameworkFiles = frameworkDir.list(); 1884 if (frameworkFiles != null) { 1885 // TODO: We could compile these only for the most preferred ABI. We should 1886 // first double check that the dex files for these commands are not referenced 1887 // by other system apps. 1888 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1889 for (int i=0; i<frameworkFiles.length; i++) { 1890 File libPath = new File(frameworkDir, frameworkFiles[i]); 1891 String path = libPath.getPath(); 1892 // Skip the file if we already did it. 1893 if (alreadyDexOpted.contains(path)) { 1894 continue; 1895 } 1896 // Skip the file if it is not a type we want to dexopt. 1897 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1898 continue; 1899 } 1900 try { 1901 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1902 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1903 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1904 } 1905 } catch (FileNotFoundException e) { 1906 Slog.w(TAG, "Jar not found: " + path); 1907 } catch (IOException e) { 1908 Slog.w(TAG, "Exception reading jar: " + path, e); 1909 } 1910 } 1911 } 1912 } 1913 1914 // Collect vendor overlay packages. 1915 // (Do this before scanning any apps.) 1916 // For security and version matching reason, only consider 1917 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1918 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1919 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1920 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1921 1922 // Find base frameworks (resource packages without code). 1923 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1924 | PackageParser.PARSE_IS_SYSTEM_DIR 1925 | PackageParser.PARSE_IS_PRIVILEGED, 1926 scanFlags | SCAN_NO_DEX, 0); 1927 1928 // Collected privileged system packages. 1929 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1930 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1931 | PackageParser.PARSE_IS_SYSTEM_DIR 1932 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1933 1934 // Collect ordinary system packages. 1935 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1936 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1937 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1938 1939 // Collect all vendor packages. 1940 File vendorAppDir = new File("/vendor/app"); 1941 try { 1942 vendorAppDir = vendorAppDir.getCanonicalFile(); 1943 } catch (IOException e) { 1944 // failed to look up canonical path, continue with original one 1945 } 1946 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1947 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1948 1949 // Collect all OEM packages. 1950 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1951 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1952 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1953 1954 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1955 mInstaller.moveFiles(); 1956 1957 // Prune any system packages that no longer exist. 1958 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1959 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1960 if (!mOnlyCore) { 1961 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1962 while (psit.hasNext()) { 1963 PackageSetting ps = psit.next(); 1964 1965 /* 1966 * If this is not a system app, it can't be a 1967 * disable system app. 1968 */ 1969 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1970 continue; 1971 } 1972 1973 /* 1974 * If the package is scanned, it's not erased. 1975 */ 1976 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1977 if (scannedPkg != null) { 1978 /* 1979 * If the system app is both scanned and in the 1980 * disabled packages list, then it must have been 1981 * added via OTA. Remove it from the currently 1982 * scanned package so the previously user-installed 1983 * application can be scanned. 1984 */ 1985 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1986 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1987 + ps.name + "; removing system app. Last known codePath=" 1988 + ps.codePathString + ", installStatus=" + ps.installStatus 1989 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1990 + scannedPkg.mVersionCode); 1991 removePackageLI(ps, true); 1992 expectingBetter.put(ps.name, ps.codePath); 1993 } 1994 1995 continue; 1996 } 1997 1998 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1999 psit.remove(); 2000 logCriticalInfo(Log.WARN, "System package " + ps.name 2001 + " no longer exists; wiping its data"); 2002 removeDataDirsLI(null, ps.name); 2003 } else { 2004 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2005 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2006 possiblyDeletedUpdatedSystemApps.add(ps.name); 2007 } 2008 } 2009 } 2010 } 2011 2012 //look for any incomplete package installations 2013 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2014 //clean up list 2015 for(int i = 0; i < deletePkgsList.size(); i++) { 2016 //clean up here 2017 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2018 } 2019 //delete tmp files 2020 deleteTempPackageFiles(); 2021 2022 // Remove any shared userIDs that have no associated packages 2023 mSettings.pruneSharedUsersLPw(); 2024 2025 if (!mOnlyCore) { 2026 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2027 SystemClock.uptimeMillis()); 2028 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2029 2030 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2031 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2032 2033 /** 2034 * Remove disable package settings for any updated system 2035 * apps that were removed via an OTA. If they're not a 2036 * previously-updated app, remove them completely. 2037 * Otherwise, just revoke their system-level permissions. 2038 */ 2039 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2040 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2041 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2042 2043 String msg; 2044 if (deletedPkg == null) { 2045 msg = "Updated system package " + deletedAppName 2046 + " no longer exists; wiping its data"; 2047 removeDataDirsLI(null, deletedAppName); 2048 } else { 2049 msg = "Updated system app + " + deletedAppName 2050 + " no longer present; removing system privileges for " 2051 + deletedAppName; 2052 2053 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2054 2055 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2056 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2057 } 2058 logCriticalInfo(Log.WARN, msg); 2059 } 2060 2061 /** 2062 * Make sure all system apps that we expected to appear on 2063 * the userdata partition actually showed up. If they never 2064 * appeared, crawl back and revive the system version. 2065 */ 2066 for (int i = 0; i < expectingBetter.size(); i++) { 2067 final String packageName = expectingBetter.keyAt(i); 2068 if (!mPackages.containsKey(packageName)) { 2069 final File scanFile = expectingBetter.valueAt(i); 2070 2071 logCriticalInfo(Log.WARN, "Expected better " + packageName 2072 + " but never showed up; reverting to system"); 2073 2074 final int reparseFlags; 2075 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2076 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2077 | PackageParser.PARSE_IS_SYSTEM_DIR 2078 | PackageParser.PARSE_IS_PRIVILEGED; 2079 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2080 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2081 | PackageParser.PARSE_IS_SYSTEM_DIR; 2082 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2083 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2084 | PackageParser.PARSE_IS_SYSTEM_DIR; 2085 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2086 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2087 | PackageParser.PARSE_IS_SYSTEM_DIR; 2088 } else { 2089 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2090 continue; 2091 } 2092 2093 mSettings.enableSystemPackageLPw(packageName); 2094 2095 try { 2096 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2097 } catch (PackageManagerException e) { 2098 Slog.e(TAG, "Failed to parse original system package: " 2099 + e.getMessage()); 2100 } 2101 } 2102 } 2103 } 2104 2105 // Now that we know all of the shared libraries, update all clients to have 2106 // the correct library paths. 2107 updateAllSharedLibrariesLPw(); 2108 2109 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2110 // NOTE: We ignore potential failures here during a system scan (like 2111 // the rest of the commands above) because there's precious little we 2112 // can do about it. A settings error is reported, though. 2113 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2114 false /* force dexopt */, false /* defer dexopt */); 2115 } 2116 2117 // Now that we know all the packages we are keeping, 2118 // read and update their last usage times. 2119 mPackageUsage.readLP(); 2120 2121 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2122 SystemClock.uptimeMillis()); 2123 Slog.i(TAG, "Time to scan packages: " 2124 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2125 + " seconds"); 2126 2127 // If the platform SDK has changed since the last time we booted, 2128 // we need to re-grant app permission to catch any new ones that 2129 // appear. This is really a hack, and means that apps can in some 2130 // cases get permissions that the user didn't initially explicitly 2131 // allow... it would be nice to have some better way to handle 2132 // this situation. 2133 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2134 != mSdkVersion; 2135 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2136 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2137 + "; regranting permissions for internal storage"); 2138 mSettings.mInternalSdkPlatform = mSdkVersion; 2139 2140 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2141 | (regrantPermissions 2142 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2143 : 0)); 2144 2145 // If this is the first boot, and it is a normal boot, then 2146 // we need to initialize the default preferred apps. 2147 if (!mRestoredSettings && !onlyCore) { 2148 mSettings.readDefaultPreferredAppsLPw(this, 0); 2149 } 2150 2151 // If this is first boot after an OTA, and a normal boot, then 2152 // we need to clear code cache directories. 2153 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2154 if (mIsUpgrade && !onlyCore) { 2155 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2156 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2157 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2158 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2159 } 2160 mSettings.mFingerprint = Build.FINGERPRINT; 2161 } 2162 2163 primeDomainVerificationsLPw(false); 2164 checkDefaultBrowser(); 2165 2166 // All the changes are done during package scanning. 2167 mSettings.updateInternalDatabaseVersion(); 2168 2169 // can downgrade to reader 2170 mSettings.writeLPr(); 2171 2172 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2173 SystemClock.uptimeMillis()); 2174 2175 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2176 2177 mInstallerService = new PackageInstallerService(context, this); 2178 2179 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2180 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2181 mIntentFilterVerifierComponent); 2182 2183 } // synchronized (mPackages) 2184 } // synchronized (mInstallLock) 2185 2186 // Now after opening every single application zip, make sure they 2187 // are all flushed. Not really needed, but keeps things nice and 2188 // tidy. 2189 Runtime.getRuntime().gc(); 2190 } 2191 2192 @Override 2193 public boolean isFirstBoot() { 2194 return !mRestoredSettings; 2195 } 2196 2197 @Override 2198 public boolean isOnlyCoreApps() { 2199 return mOnlyCore; 2200 } 2201 2202 @Override 2203 public boolean isUpgrade() { 2204 return mIsUpgrade; 2205 } 2206 2207 private String getRequiredVerifierLPr() { 2208 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2209 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2210 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2211 2212 String requiredVerifier = null; 2213 2214 final int N = receivers.size(); 2215 for (int i = 0; i < N; i++) { 2216 final ResolveInfo info = receivers.get(i); 2217 2218 if (info.activityInfo == null) { 2219 continue; 2220 } 2221 2222 final String packageName = info.activityInfo.packageName; 2223 2224 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2225 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2226 continue; 2227 } 2228 2229 if (requiredVerifier != null) { 2230 throw new RuntimeException("There can be only one required verifier"); 2231 } 2232 2233 requiredVerifier = packageName; 2234 } 2235 2236 return requiredVerifier; 2237 } 2238 2239 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2240 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2241 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2242 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2243 2244 ComponentName verifierComponentName = null; 2245 2246 int priority = -1000; 2247 final int N = receivers.size(); 2248 for (int i = 0; i < N; i++) { 2249 final ResolveInfo info = receivers.get(i); 2250 2251 if (info.activityInfo == null) { 2252 continue; 2253 } 2254 2255 final String packageName = info.activityInfo.packageName; 2256 2257 final PackageSetting ps = mSettings.mPackages.get(packageName); 2258 if (ps == null) { 2259 continue; 2260 } 2261 2262 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2263 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2264 continue; 2265 } 2266 2267 // Select the IntentFilterVerifier with the highest priority 2268 if (priority < info.priority) { 2269 priority = info.priority; 2270 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2271 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2272 " with priority: " + info.priority); 2273 } 2274 } 2275 2276 return verifierComponentName; 2277 } 2278 2279 private void primeDomainVerificationsLPw(boolean logging) { 2280 Slog.d(TAG, "Start priming domain verifications"); 2281 boolean updated = false; 2282 ArraySet<String> allHostsSet = new ArraySet<>(); 2283 for (PackageParser.Package pkg : mPackages.values()) { 2284 final String packageName = pkg.packageName; 2285 if (!hasDomainURLs(pkg)) { 2286 if (logging) { 2287 Slog.d(TAG, "No priming domain verifications for " + 2288 "package with no domain URLs: " + packageName); 2289 } 2290 continue; 2291 } 2292 if (!pkg.isSystemApp()) { 2293 if (logging) { 2294 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2295 packageName); 2296 } 2297 continue; 2298 } 2299 for (PackageParser.Activity a : pkg.activities) { 2300 for (ActivityIntentInfo filter : a.intents) { 2301 if (hasValidDomains(filter, false)) { 2302 allHostsSet.addAll(filter.getHostsList()); 2303 } 2304 } 2305 } 2306 if (allHostsSet.size() == 0) { 2307 allHostsSet.add("*"); 2308 } 2309 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2310 IntentFilterVerificationInfo ivi = 2311 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2312 if (ivi != null) { 2313 // We will always log this 2314 Slog.d(TAG, "Priming domain verifications for package: " + packageName + 2315 " with hosts:" + ivi.getDomainsString()); 2316 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2317 updated = true; 2318 } 2319 else { 2320 if (logging) { 2321 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2322 } 2323 } 2324 allHostsSet.clear(); 2325 } 2326 if (updated) { 2327 if (logging) { 2328 Slog.d(TAG, "Will need to write primed domain verifications"); 2329 } 2330 } 2331 Slog.d(TAG, "End priming domain verifications"); 2332 } 2333 2334 private void checkDefaultBrowser() { 2335 final int myUserId = UserHandle.myUserId(); 2336 final String packageName = getDefaultBrowserPackageName(myUserId); 2337 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2338 if (info == null) { 2339 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2340 packageName); 2341 setDefaultBrowserPackageName(null, myUserId); 2342 } 2343 } 2344 2345 @Override 2346 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2347 throws RemoteException { 2348 try { 2349 return super.onTransact(code, data, reply, flags); 2350 } catch (RuntimeException e) { 2351 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2352 Slog.wtf(TAG, "Package Manager Crash", e); 2353 } 2354 throw e; 2355 } 2356 } 2357 2358 void cleanupInstallFailedPackage(PackageSetting ps) { 2359 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2360 2361 removeDataDirsLI(ps.volumeUuid, ps.name); 2362 if (ps.codePath != null) { 2363 if (ps.codePath.isDirectory()) { 2364 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2365 } else { 2366 ps.codePath.delete(); 2367 } 2368 } 2369 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2370 if (ps.resourcePath.isDirectory()) { 2371 FileUtils.deleteContents(ps.resourcePath); 2372 } 2373 ps.resourcePath.delete(); 2374 } 2375 mSettings.removePackageLPw(ps.name); 2376 } 2377 2378 static int[] appendInts(int[] cur, int[] add) { 2379 if (add == null) return cur; 2380 if (cur == null) return add; 2381 final int N = add.length; 2382 for (int i=0; i<N; i++) { 2383 cur = appendInt(cur, add[i]); 2384 } 2385 return cur; 2386 } 2387 2388 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2389 if (!sUserManager.exists(userId)) return null; 2390 final PackageSetting ps = (PackageSetting) p.mExtras; 2391 if (ps == null) { 2392 return null; 2393 } 2394 2395 final PermissionsState permissionsState = ps.getPermissionsState(); 2396 2397 final int[] gids = permissionsState.computeGids(userId); 2398 final Set<String> permissions = permissionsState.getPermissions(userId); 2399 final PackageUserState state = ps.readUserState(userId); 2400 2401 return PackageParser.generatePackageInfo(p, gids, flags, 2402 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2403 } 2404 2405 @Override 2406 public boolean isPackageFrozen(String packageName) { 2407 synchronized (mPackages) { 2408 final PackageSetting ps = mSettings.mPackages.get(packageName); 2409 if (ps != null) { 2410 return ps.frozen; 2411 } 2412 } 2413 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2414 return true; 2415 } 2416 2417 @Override 2418 public boolean isPackageAvailable(String packageName, int userId) { 2419 if (!sUserManager.exists(userId)) return false; 2420 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2421 synchronized (mPackages) { 2422 PackageParser.Package p = mPackages.get(packageName); 2423 if (p != null) { 2424 final PackageSetting ps = (PackageSetting) p.mExtras; 2425 if (ps != null) { 2426 final PackageUserState state = ps.readUserState(userId); 2427 if (state != null) { 2428 return PackageParser.isAvailable(state); 2429 } 2430 } 2431 } 2432 } 2433 return false; 2434 } 2435 2436 @Override 2437 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2438 if (!sUserManager.exists(userId)) return null; 2439 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2440 // reader 2441 synchronized (mPackages) { 2442 PackageParser.Package p = mPackages.get(packageName); 2443 if (DEBUG_PACKAGE_INFO) 2444 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2445 if (p != null) { 2446 return generatePackageInfo(p, flags, userId); 2447 } 2448 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2449 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2450 } 2451 } 2452 return null; 2453 } 2454 2455 @Override 2456 public String[] currentToCanonicalPackageNames(String[] names) { 2457 String[] out = new String[names.length]; 2458 // reader 2459 synchronized (mPackages) { 2460 for (int i=names.length-1; i>=0; i--) { 2461 PackageSetting ps = mSettings.mPackages.get(names[i]); 2462 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2463 } 2464 } 2465 return out; 2466 } 2467 2468 @Override 2469 public String[] canonicalToCurrentPackageNames(String[] names) { 2470 String[] out = new String[names.length]; 2471 // reader 2472 synchronized (mPackages) { 2473 for (int i=names.length-1; i>=0; i--) { 2474 String cur = mSettings.mRenamedPackages.get(names[i]); 2475 out[i] = cur != null ? cur : names[i]; 2476 } 2477 } 2478 return out; 2479 } 2480 2481 @Override 2482 public int getPackageUid(String packageName, int userId) { 2483 if (!sUserManager.exists(userId)) return -1; 2484 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2485 2486 // reader 2487 synchronized (mPackages) { 2488 PackageParser.Package p = mPackages.get(packageName); 2489 if(p != null) { 2490 return UserHandle.getUid(userId, p.applicationInfo.uid); 2491 } 2492 PackageSetting ps = mSettings.mPackages.get(packageName); 2493 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2494 return -1; 2495 } 2496 p = ps.pkg; 2497 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2498 } 2499 } 2500 2501 @Override 2502 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2503 if (!sUserManager.exists(userId)) { 2504 return null; 2505 } 2506 2507 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2508 "getPackageGids"); 2509 2510 // reader 2511 synchronized (mPackages) { 2512 PackageParser.Package p = mPackages.get(packageName); 2513 if (DEBUG_PACKAGE_INFO) { 2514 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2515 } 2516 if (p != null) { 2517 PackageSetting ps = (PackageSetting) p.mExtras; 2518 return ps.getPermissionsState().computeGids(userId); 2519 } 2520 } 2521 2522 return null; 2523 } 2524 2525 static PermissionInfo generatePermissionInfo( 2526 BasePermission bp, int flags) { 2527 if (bp.perm != null) { 2528 return PackageParser.generatePermissionInfo(bp.perm, flags); 2529 } 2530 PermissionInfo pi = new PermissionInfo(); 2531 pi.name = bp.name; 2532 pi.packageName = bp.sourcePackage; 2533 pi.nonLocalizedLabel = bp.name; 2534 pi.protectionLevel = bp.protectionLevel; 2535 return pi; 2536 } 2537 2538 @Override 2539 public PermissionInfo getPermissionInfo(String name, int flags) { 2540 // reader 2541 synchronized (mPackages) { 2542 final BasePermission p = mSettings.mPermissions.get(name); 2543 if (p != null) { 2544 return generatePermissionInfo(p, flags); 2545 } 2546 return null; 2547 } 2548 } 2549 2550 @Override 2551 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2552 // reader 2553 synchronized (mPackages) { 2554 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2555 for (BasePermission p : mSettings.mPermissions.values()) { 2556 if (group == null) { 2557 if (p.perm == null || p.perm.info.group == null) { 2558 out.add(generatePermissionInfo(p, flags)); 2559 } 2560 } else { 2561 if (p.perm != null && group.equals(p.perm.info.group)) { 2562 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2563 } 2564 } 2565 } 2566 2567 if (out.size() > 0) { 2568 return out; 2569 } 2570 return mPermissionGroups.containsKey(group) ? out : null; 2571 } 2572 } 2573 2574 @Override 2575 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2576 // reader 2577 synchronized (mPackages) { 2578 return PackageParser.generatePermissionGroupInfo( 2579 mPermissionGroups.get(name), flags); 2580 } 2581 } 2582 2583 @Override 2584 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2585 // reader 2586 synchronized (mPackages) { 2587 final int N = mPermissionGroups.size(); 2588 ArrayList<PermissionGroupInfo> out 2589 = new ArrayList<PermissionGroupInfo>(N); 2590 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2591 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2592 } 2593 return out; 2594 } 2595 } 2596 2597 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2598 int userId) { 2599 if (!sUserManager.exists(userId)) return null; 2600 PackageSetting ps = mSettings.mPackages.get(packageName); 2601 if (ps != null) { 2602 if (ps.pkg == null) { 2603 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2604 flags, userId); 2605 if (pInfo != null) { 2606 return pInfo.applicationInfo; 2607 } 2608 return null; 2609 } 2610 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2611 ps.readUserState(userId), userId); 2612 } 2613 return null; 2614 } 2615 2616 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2617 int userId) { 2618 if (!sUserManager.exists(userId)) return null; 2619 PackageSetting ps = mSettings.mPackages.get(packageName); 2620 if (ps != null) { 2621 PackageParser.Package pkg = ps.pkg; 2622 if (pkg == null) { 2623 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2624 return null; 2625 } 2626 // Only data remains, so we aren't worried about code paths 2627 pkg = new PackageParser.Package(packageName); 2628 pkg.applicationInfo.packageName = packageName; 2629 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2630 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2631 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2632 packageName, userId).getAbsolutePath(); 2633 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2634 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2635 } 2636 return generatePackageInfo(pkg, flags, userId); 2637 } 2638 return null; 2639 } 2640 2641 @Override 2642 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2643 if (!sUserManager.exists(userId)) return null; 2644 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2645 // writer 2646 synchronized (mPackages) { 2647 PackageParser.Package p = mPackages.get(packageName); 2648 if (DEBUG_PACKAGE_INFO) Log.v( 2649 TAG, "getApplicationInfo " + packageName 2650 + ": " + p); 2651 if (p != null) { 2652 PackageSetting ps = mSettings.mPackages.get(packageName); 2653 if (ps == null) return null; 2654 // Note: isEnabledLP() does not apply here - always return info 2655 return PackageParser.generateApplicationInfo( 2656 p, flags, ps.readUserState(userId), userId); 2657 } 2658 if ("android".equals(packageName)||"system".equals(packageName)) { 2659 return mAndroidApplication; 2660 } 2661 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2662 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2663 } 2664 } 2665 return null; 2666 } 2667 2668 @Override 2669 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2670 final IPackageDataObserver observer) { 2671 mContext.enforceCallingOrSelfPermission( 2672 android.Manifest.permission.CLEAR_APP_CACHE, null); 2673 // Queue up an async operation since clearing cache may take a little while. 2674 mHandler.post(new Runnable() { 2675 public void run() { 2676 mHandler.removeCallbacks(this); 2677 int retCode = -1; 2678 synchronized (mInstallLock) { 2679 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2680 if (retCode < 0) { 2681 Slog.w(TAG, "Couldn't clear application caches"); 2682 } 2683 } 2684 if (observer != null) { 2685 try { 2686 observer.onRemoveCompleted(null, (retCode >= 0)); 2687 } catch (RemoteException e) { 2688 Slog.w(TAG, "RemoveException when invoking call back"); 2689 } 2690 } 2691 } 2692 }); 2693 } 2694 2695 @Override 2696 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2697 final IntentSender pi) { 2698 mContext.enforceCallingOrSelfPermission( 2699 android.Manifest.permission.CLEAR_APP_CACHE, null); 2700 // Queue up an async operation since clearing cache may take a little while. 2701 mHandler.post(new Runnable() { 2702 public void run() { 2703 mHandler.removeCallbacks(this); 2704 int retCode = -1; 2705 synchronized (mInstallLock) { 2706 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2707 if (retCode < 0) { 2708 Slog.w(TAG, "Couldn't clear application caches"); 2709 } 2710 } 2711 if(pi != null) { 2712 try { 2713 // Callback via pending intent 2714 int code = (retCode >= 0) ? 1 : 0; 2715 pi.sendIntent(null, code, null, 2716 null, null); 2717 } catch (SendIntentException e1) { 2718 Slog.i(TAG, "Failed to send pending intent"); 2719 } 2720 } 2721 } 2722 }); 2723 } 2724 2725 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2726 synchronized (mInstallLock) { 2727 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2728 throw new IOException("Failed to free enough space"); 2729 } 2730 } 2731 } 2732 2733 @Override 2734 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2735 if (!sUserManager.exists(userId)) return null; 2736 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2737 synchronized (mPackages) { 2738 PackageParser.Activity a = mActivities.mActivities.get(component); 2739 2740 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2741 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2742 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2743 if (ps == null) return null; 2744 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2745 userId); 2746 } 2747 if (mResolveComponentName.equals(component)) { 2748 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2749 new PackageUserState(), userId); 2750 } 2751 } 2752 return null; 2753 } 2754 2755 @Override 2756 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2757 String resolvedType) { 2758 synchronized (mPackages) { 2759 PackageParser.Activity a = mActivities.mActivities.get(component); 2760 if (a == null) { 2761 return false; 2762 } 2763 for (int i=0; i<a.intents.size(); i++) { 2764 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2765 intent.getData(), intent.getCategories(), TAG) >= 0) { 2766 return true; 2767 } 2768 } 2769 return false; 2770 } 2771 } 2772 2773 @Override 2774 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2775 if (!sUserManager.exists(userId)) return null; 2776 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2777 synchronized (mPackages) { 2778 PackageParser.Activity a = mReceivers.mActivities.get(component); 2779 if (DEBUG_PACKAGE_INFO) Log.v( 2780 TAG, "getReceiverInfo " + component + ": " + a); 2781 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2782 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2783 if (ps == null) return null; 2784 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2785 userId); 2786 } 2787 } 2788 return null; 2789 } 2790 2791 @Override 2792 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2793 if (!sUserManager.exists(userId)) return null; 2794 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2795 synchronized (mPackages) { 2796 PackageParser.Service s = mServices.mServices.get(component); 2797 if (DEBUG_PACKAGE_INFO) Log.v( 2798 TAG, "getServiceInfo " + component + ": " + s); 2799 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2800 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2801 if (ps == null) return null; 2802 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2803 userId); 2804 } 2805 } 2806 return null; 2807 } 2808 2809 @Override 2810 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2811 if (!sUserManager.exists(userId)) return null; 2812 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2813 synchronized (mPackages) { 2814 PackageParser.Provider p = mProviders.mProviders.get(component); 2815 if (DEBUG_PACKAGE_INFO) Log.v( 2816 TAG, "getProviderInfo " + component + ": " + p); 2817 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2818 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2819 if (ps == null) return null; 2820 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2821 userId); 2822 } 2823 } 2824 return null; 2825 } 2826 2827 @Override 2828 public String[] getSystemSharedLibraryNames() { 2829 Set<String> libSet; 2830 synchronized (mPackages) { 2831 libSet = mSharedLibraries.keySet(); 2832 int size = libSet.size(); 2833 if (size > 0) { 2834 String[] libs = new String[size]; 2835 libSet.toArray(libs); 2836 return libs; 2837 } 2838 } 2839 return null; 2840 } 2841 2842 /** 2843 * @hide 2844 */ 2845 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2846 synchronized (mPackages) { 2847 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2848 if (lib != null && lib.apk != null) { 2849 return mPackages.get(lib.apk); 2850 } 2851 } 2852 return null; 2853 } 2854 2855 @Override 2856 public FeatureInfo[] getSystemAvailableFeatures() { 2857 Collection<FeatureInfo> featSet; 2858 synchronized (mPackages) { 2859 featSet = mAvailableFeatures.values(); 2860 int size = featSet.size(); 2861 if (size > 0) { 2862 FeatureInfo[] features = new FeatureInfo[size+1]; 2863 featSet.toArray(features); 2864 FeatureInfo fi = new FeatureInfo(); 2865 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2866 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2867 features[size] = fi; 2868 return features; 2869 } 2870 } 2871 return null; 2872 } 2873 2874 @Override 2875 public boolean hasSystemFeature(String name) { 2876 synchronized (mPackages) { 2877 return mAvailableFeatures.containsKey(name); 2878 } 2879 } 2880 2881 private void checkValidCaller(int uid, int userId) { 2882 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2883 return; 2884 2885 throw new SecurityException("Caller uid=" + uid 2886 + " is not privileged to communicate with user=" + userId); 2887 } 2888 2889 @Override 2890 public int checkPermission(String permName, String pkgName, int userId) { 2891 if (!sUserManager.exists(userId)) { 2892 return PackageManager.PERMISSION_DENIED; 2893 } 2894 2895 synchronized (mPackages) { 2896 final PackageParser.Package p = mPackages.get(pkgName); 2897 if (p != null && p.mExtras != null) { 2898 final PackageSetting ps = (PackageSetting) p.mExtras; 2899 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2900 return PackageManager.PERMISSION_GRANTED; 2901 } 2902 } 2903 } 2904 2905 return PackageManager.PERMISSION_DENIED; 2906 } 2907 2908 @Override 2909 public int checkUidPermission(String permName, int uid) { 2910 final int userId = UserHandle.getUserId(uid); 2911 2912 if (!sUserManager.exists(userId)) { 2913 return PackageManager.PERMISSION_DENIED; 2914 } 2915 2916 synchronized (mPackages) { 2917 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2918 if (obj != null) { 2919 final SettingBase ps = (SettingBase) obj; 2920 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2921 return PackageManager.PERMISSION_GRANTED; 2922 } 2923 } else { 2924 ArraySet<String> perms = mSystemPermissions.get(uid); 2925 if (perms != null && perms.contains(permName)) { 2926 return PackageManager.PERMISSION_GRANTED; 2927 } 2928 } 2929 } 2930 2931 return PackageManager.PERMISSION_DENIED; 2932 } 2933 2934 /** 2935 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2936 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2937 * @param checkShell TODO(yamasani): 2938 * @param message the message to log on security exception 2939 */ 2940 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2941 boolean checkShell, String message) { 2942 if (userId < 0) { 2943 throw new IllegalArgumentException("Invalid userId " + userId); 2944 } 2945 if (checkShell) { 2946 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2947 } 2948 if (userId == UserHandle.getUserId(callingUid)) return; 2949 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2950 if (requireFullPermission) { 2951 mContext.enforceCallingOrSelfPermission( 2952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2953 } else { 2954 try { 2955 mContext.enforceCallingOrSelfPermission( 2956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2957 } catch (SecurityException se) { 2958 mContext.enforceCallingOrSelfPermission( 2959 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2960 } 2961 } 2962 } 2963 } 2964 2965 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2966 if (callingUid == Process.SHELL_UID) { 2967 if (userHandle >= 0 2968 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2969 throw new SecurityException("Shell does not have permission to access user " 2970 + userHandle); 2971 } else if (userHandle < 0) { 2972 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2973 + Debug.getCallers(3)); 2974 } 2975 } 2976 } 2977 2978 private BasePermission findPermissionTreeLP(String permName) { 2979 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2980 if (permName.startsWith(bp.name) && 2981 permName.length() > bp.name.length() && 2982 permName.charAt(bp.name.length()) == '.') { 2983 return bp; 2984 } 2985 } 2986 return null; 2987 } 2988 2989 private BasePermission checkPermissionTreeLP(String permName) { 2990 if (permName != null) { 2991 BasePermission bp = findPermissionTreeLP(permName); 2992 if (bp != null) { 2993 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2994 return bp; 2995 } 2996 throw new SecurityException("Calling uid " 2997 + Binder.getCallingUid() 2998 + " is not allowed to add to permission tree " 2999 + bp.name + " owned by uid " + bp.uid); 3000 } 3001 } 3002 throw new SecurityException("No permission tree found for " + permName); 3003 } 3004 3005 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3006 if (s1 == null) { 3007 return s2 == null; 3008 } 3009 if (s2 == null) { 3010 return false; 3011 } 3012 if (s1.getClass() != s2.getClass()) { 3013 return false; 3014 } 3015 return s1.equals(s2); 3016 } 3017 3018 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3019 if (pi1.icon != pi2.icon) return false; 3020 if (pi1.logo != pi2.logo) return false; 3021 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3022 if (!compareStrings(pi1.name, pi2.name)) return false; 3023 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3024 // We'll take care of setting this one. 3025 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3026 // These are not currently stored in settings. 3027 //if (!compareStrings(pi1.group, pi2.group)) return false; 3028 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3029 //if (pi1.labelRes != pi2.labelRes) return false; 3030 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3031 return true; 3032 } 3033 3034 int permissionInfoFootprint(PermissionInfo info) { 3035 int size = info.name.length(); 3036 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3037 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3038 return size; 3039 } 3040 3041 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3042 int size = 0; 3043 for (BasePermission perm : mSettings.mPermissions.values()) { 3044 if (perm.uid == tree.uid) { 3045 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3046 } 3047 } 3048 return size; 3049 } 3050 3051 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3052 // We calculate the max size of permissions defined by this uid and throw 3053 // if that plus the size of 'info' would exceed our stated maximum. 3054 if (tree.uid != Process.SYSTEM_UID) { 3055 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3056 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3057 throw new SecurityException("Permission tree size cap exceeded"); 3058 } 3059 } 3060 } 3061 3062 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3063 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3064 throw new SecurityException("Label must be specified in permission"); 3065 } 3066 BasePermission tree = checkPermissionTreeLP(info.name); 3067 BasePermission bp = mSettings.mPermissions.get(info.name); 3068 boolean added = bp == null; 3069 boolean changed = true; 3070 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3071 if (added) { 3072 enforcePermissionCapLocked(info, tree); 3073 bp = new BasePermission(info.name, tree.sourcePackage, 3074 BasePermission.TYPE_DYNAMIC); 3075 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3076 throw new SecurityException( 3077 "Not allowed to modify non-dynamic permission " 3078 + info.name); 3079 } else { 3080 if (bp.protectionLevel == fixedLevel 3081 && bp.perm.owner.equals(tree.perm.owner) 3082 && bp.uid == tree.uid 3083 && comparePermissionInfos(bp.perm.info, info)) { 3084 changed = false; 3085 } 3086 } 3087 bp.protectionLevel = fixedLevel; 3088 info = new PermissionInfo(info); 3089 info.protectionLevel = fixedLevel; 3090 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3091 bp.perm.info.packageName = tree.perm.info.packageName; 3092 bp.uid = tree.uid; 3093 if (added) { 3094 mSettings.mPermissions.put(info.name, bp); 3095 } 3096 if (changed) { 3097 if (!async) { 3098 mSettings.writeLPr(); 3099 } else { 3100 scheduleWriteSettingsLocked(); 3101 } 3102 } 3103 return added; 3104 } 3105 3106 @Override 3107 public boolean addPermission(PermissionInfo info) { 3108 synchronized (mPackages) { 3109 return addPermissionLocked(info, false); 3110 } 3111 } 3112 3113 @Override 3114 public boolean addPermissionAsync(PermissionInfo info) { 3115 synchronized (mPackages) { 3116 return addPermissionLocked(info, true); 3117 } 3118 } 3119 3120 @Override 3121 public void removePermission(String name) { 3122 synchronized (mPackages) { 3123 checkPermissionTreeLP(name); 3124 BasePermission bp = mSettings.mPermissions.get(name); 3125 if (bp != null) { 3126 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3127 throw new SecurityException( 3128 "Not allowed to modify non-dynamic permission " 3129 + name); 3130 } 3131 mSettings.mPermissions.remove(name); 3132 mSettings.writeLPr(); 3133 } 3134 } 3135 } 3136 3137 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3138 BasePermission bp) { 3139 int index = pkg.requestedPermissions.indexOf(bp.name); 3140 if (index == -1) { 3141 throw new SecurityException("Package " + pkg.packageName 3142 + " has not requested permission " + bp.name); 3143 } 3144 if (!bp.isRuntime()) { 3145 throw new SecurityException("Permission " + bp.name 3146 + " is not a changeable permission type"); 3147 } 3148 } 3149 3150 @Override 3151 public void grantRuntimePermission(String packageName, String name, int userId) { 3152 if (!sUserManager.exists(userId)) { 3153 Log.e(TAG, "No such user:" + userId); 3154 return; 3155 } 3156 3157 mContext.enforceCallingOrSelfPermission( 3158 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3159 "grantRuntimePermission"); 3160 3161 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3162 "grantRuntimePermission"); 3163 3164 boolean gidsChanged = false; 3165 final SettingBase sb; 3166 3167 synchronized (mPackages) { 3168 final PackageParser.Package pkg = mPackages.get(packageName); 3169 if (pkg == null) { 3170 throw new IllegalArgumentException("Unknown package: " + packageName); 3171 } 3172 3173 final BasePermission bp = mSettings.mPermissions.get(name); 3174 if (bp == null) { 3175 throw new IllegalArgumentException("Unknown permission: " + name); 3176 } 3177 3178 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3179 3180 sb = (SettingBase) pkg.mExtras; 3181 if (sb == null) { 3182 throw new IllegalArgumentException("Unknown package: " + packageName); 3183 } 3184 3185 final PermissionsState permissionsState = sb.getPermissionsState(); 3186 3187 final int flags = permissionsState.getPermissionFlags(name, userId); 3188 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3189 throw new SecurityException("Cannot grant system fixed permission: " 3190 + name + " for package: " + packageName); 3191 } 3192 3193 final int result = permissionsState.grantRuntimePermission(bp, userId); 3194 switch (result) { 3195 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3196 return; 3197 } 3198 3199 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3200 gidsChanged = true; 3201 } 3202 break; 3203 } 3204 3205 // Not critical if that is lost - app has to request again. 3206 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3207 } 3208 3209 if (gidsChanged) { 3210 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3211 } 3212 } 3213 3214 @Override 3215 public void revokeRuntimePermission(String packageName, String name, int userId) { 3216 if (!sUserManager.exists(userId)) { 3217 Log.e(TAG, "No such user:" + userId); 3218 return; 3219 } 3220 3221 mContext.enforceCallingOrSelfPermission( 3222 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3223 "revokeRuntimePermission"); 3224 3225 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3226 "revokeRuntimePermission"); 3227 3228 final SettingBase sb; 3229 3230 synchronized (mPackages) { 3231 final PackageParser.Package pkg = mPackages.get(packageName); 3232 if (pkg == null) { 3233 throw new IllegalArgumentException("Unknown package: " + packageName); 3234 } 3235 3236 final BasePermission bp = mSettings.mPermissions.get(name); 3237 if (bp == null) { 3238 throw new IllegalArgumentException("Unknown permission: " + name); 3239 } 3240 3241 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3242 3243 sb = (SettingBase) pkg.mExtras; 3244 if (sb == null) { 3245 throw new IllegalArgumentException("Unknown package: " + packageName); 3246 } 3247 3248 final PermissionsState permissionsState = sb.getPermissionsState(); 3249 3250 final int flags = permissionsState.getPermissionFlags(name, userId); 3251 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3252 throw new SecurityException("Cannot revoke system fixed permission: " 3253 + name + " for package: " + packageName); 3254 } 3255 3256 if (permissionsState.revokeRuntimePermission(bp, userId) == 3257 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3258 return; 3259 } 3260 3261 // Critical, after this call app should never have the permission. 3262 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3263 } 3264 3265 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3266 } 3267 3268 @Override 3269 public int getPermissionFlags(String name, String packageName, int userId) { 3270 if (!sUserManager.exists(userId)) { 3271 return 0; 3272 } 3273 3274 mContext.enforceCallingOrSelfPermission( 3275 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3276 "getPermissionFlags"); 3277 3278 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3279 "getPermissionFlags"); 3280 3281 synchronized (mPackages) { 3282 final PackageParser.Package pkg = mPackages.get(packageName); 3283 if (pkg == null) { 3284 throw new IllegalArgumentException("Unknown package: " + packageName); 3285 } 3286 3287 final BasePermission bp = mSettings.mPermissions.get(name); 3288 if (bp == null) { 3289 throw new IllegalArgumentException("Unknown permission: " + name); 3290 } 3291 3292 SettingBase sb = (SettingBase) pkg.mExtras; 3293 if (sb == null) { 3294 throw new IllegalArgumentException("Unknown package: " + packageName); 3295 } 3296 3297 PermissionsState permissionsState = sb.getPermissionsState(); 3298 return permissionsState.getPermissionFlags(name, userId); 3299 } 3300 } 3301 3302 @Override 3303 public void updatePermissionFlags(String name, String packageName, int flagMask, 3304 int flagValues, int userId) { 3305 if (!sUserManager.exists(userId)) { 3306 return; 3307 } 3308 3309 mContext.enforceCallingOrSelfPermission( 3310 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3311 "updatePermissionFlags"); 3312 3313 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3314 "updatePermissionFlags"); 3315 3316 // Only the system can change policy flags. 3317 if (getCallingUid() != Process.SYSTEM_UID) { 3318 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3319 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3320 } 3321 3322 // Only the package manager can change system flags. 3323 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3324 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3325 3326 synchronized (mPackages) { 3327 final PackageParser.Package pkg = mPackages.get(packageName); 3328 if (pkg == null) { 3329 throw new IllegalArgumentException("Unknown package: " + packageName); 3330 } 3331 3332 final BasePermission bp = mSettings.mPermissions.get(name); 3333 if (bp == null) { 3334 throw new IllegalArgumentException("Unknown permission: " + name); 3335 } 3336 3337 SettingBase sb = (SettingBase) pkg.mExtras; 3338 if (sb == null) { 3339 throw new IllegalArgumentException("Unknown package: " + packageName); 3340 } 3341 3342 PermissionsState permissionsState = sb.getPermissionsState(); 3343 3344 // Only the package manager can change flags for system component permissions. 3345 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3346 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3347 return; 3348 } 3349 3350 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3351 // Install and runtime permissions are stored in different places, 3352 // so figure out what permission changed and persist the change. 3353 if (permissionsState.getInstallPermissionState(name) != null) { 3354 scheduleWriteSettingsLocked(); 3355 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3356 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3357 } 3358 } 3359 } 3360 } 3361 3362 @Override 3363 public boolean isProtectedBroadcast(String actionName) { 3364 synchronized (mPackages) { 3365 return mProtectedBroadcasts.contains(actionName); 3366 } 3367 } 3368 3369 @Override 3370 public int checkSignatures(String pkg1, String pkg2) { 3371 synchronized (mPackages) { 3372 final PackageParser.Package p1 = mPackages.get(pkg1); 3373 final PackageParser.Package p2 = mPackages.get(pkg2); 3374 if (p1 == null || p1.mExtras == null 3375 || p2 == null || p2.mExtras == null) { 3376 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3377 } 3378 return compareSignatures(p1.mSignatures, p2.mSignatures); 3379 } 3380 } 3381 3382 @Override 3383 public int checkUidSignatures(int uid1, int uid2) { 3384 // Map to base uids. 3385 uid1 = UserHandle.getAppId(uid1); 3386 uid2 = UserHandle.getAppId(uid2); 3387 // reader 3388 synchronized (mPackages) { 3389 Signature[] s1; 3390 Signature[] s2; 3391 Object obj = mSettings.getUserIdLPr(uid1); 3392 if (obj != null) { 3393 if (obj instanceof SharedUserSetting) { 3394 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3395 } else if (obj instanceof PackageSetting) { 3396 s1 = ((PackageSetting)obj).signatures.mSignatures; 3397 } else { 3398 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3399 } 3400 } else { 3401 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3402 } 3403 obj = mSettings.getUserIdLPr(uid2); 3404 if (obj != null) { 3405 if (obj instanceof SharedUserSetting) { 3406 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3407 } else if (obj instanceof PackageSetting) { 3408 s2 = ((PackageSetting)obj).signatures.mSignatures; 3409 } else { 3410 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3411 } 3412 } else { 3413 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3414 } 3415 return compareSignatures(s1, s2); 3416 } 3417 } 3418 3419 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3420 final long identity = Binder.clearCallingIdentity(); 3421 try { 3422 if (sb instanceof SharedUserSetting) { 3423 SharedUserSetting sus = (SharedUserSetting) sb; 3424 final int packageCount = sus.packages.size(); 3425 for (int i = 0; i < packageCount; i++) { 3426 PackageSetting susPs = sus.packages.valueAt(i); 3427 if (userId == UserHandle.USER_ALL) { 3428 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3429 } else { 3430 final int uid = UserHandle.getUid(userId, susPs.appId); 3431 killUid(uid, reason); 3432 } 3433 } 3434 } else if (sb instanceof PackageSetting) { 3435 PackageSetting ps = (PackageSetting) sb; 3436 if (userId == UserHandle.USER_ALL) { 3437 killApplication(ps.pkg.packageName, ps.appId, reason); 3438 } else { 3439 final int uid = UserHandle.getUid(userId, ps.appId); 3440 killUid(uid, reason); 3441 } 3442 } 3443 } finally { 3444 Binder.restoreCallingIdentity(identity); 3445 } 3446 } 3447 3448 private static void killUid(int uid, String reason) { 3449 IActivityManager am = ActivityManagerNative.getDefault(); 3450 if (am != null) { 3451 try { 3452 am.killUid(uid, reason); 3453 } catch (RemoteException e) { 3454 /* ignore - same process */ 3455 } 3456 } 3457 } 3458 3459 /** 3460 * Compares two sets of signatures. Returns: 3461 * <br /> 3462 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3463 * <br /> 3464 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3465 * <br /> 3466 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3467 * <br /> 3468 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3469 * <br /> 3470 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3471 */ 3472 static int compareSignatures(Signature[] s1, Signature[] s2) { 3473 if (s1 == null) { 3474 return s2 == null 3475 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3476 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3477 } 3478 3479 if (s2 == null) { 3480 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3481 } 3482 3483 if (s1.length != s2.length) { 3484 return PackageManager.SIGNATURE_NO_MATCH; 3485 } 3486 3487 // Since both signature sets are of size 1, we can compare without HashSets. 3488 if (s1.length == 1) { 3489 return s1[0].equals(s2[0]) ? 3490 PackageManager.SIGNATURE_MATCH : 3491 PackageManager.SIGNATURE_NO_MATCH; 3492 } 3493 3494 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3495 for (Signature sig : s1) { 3496 set1.add(sig); 3497 } 3498 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3499 for (Signature sig : s2) { 3500 set2.add(sig); 3501 } 3502 // Make sure s2 contains all signatures in s1. 3503 if (set1.equals(set2)) { 3504 return PackageManager.SIGNATURE_MATCH; 3505 } 3506 return PackageManager.SIGNATURE_NO_MATCH; 3507 } 3508 3509 /** 3510 * If the database version for this type of package (internal storage or 3511 * external storage) is less than the version where package signatures 3512 * were updated, return true. 3513 */ 3514 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3515 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3516 DatabaseVersion.SIGNATURE_END_ENTITY)) 3517 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3518 DatabaseVersion.SIGNATURE_END_ENTITY)); 3519 } 3520 3521 /** 3522 * Used for backward compatibility to make sure any packages with 3523 * certificate chains get upgraded to the new style. {@code existingSigs} 3524 * will be in the old format (since they were stored on disk from before the 3525 * system upgrade) and {@code scannedSigs} will be in the newer format. 3526 */ 3527 private int compareSignaturesCompat(PackageSignatures existingSigs, 3528 PackageParser.Package scannedPkg) { 3529 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3530 return PackageManager.SIGNATURE_NO_MATCH; 3531 } 3532 3533 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3534 for (Signature sig : existingSigs.mSignatures) { 3535 existingSet.add(sig); 3536 } 3537 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3538 for (Signature sig : scannedPkg.mSignatures) { 3539 try { 3540 Signature[] chainSignatures = sig.getChainSignatures(); 3541 for (Signature chainSig : chainSignatures) { 3542 scannedCompatSet.add(chainSig); 3543 } 3544 } catch (CertificateEncodingException e) { 3545 scannedCompatSet.add(sig); 3546 } 3547 } 3548 /* 3549 * Make sure the expanded scanned set contains all signatures in the 3550 * existing one. 3551 */ 3552 if (scannedCompatSet.equals(existingSet)) { 3553 // Migrate the old signatures to the new scheme. 3554 existingSigs.assignSignatures(scannedPkg.mSignatures); 3555 // The new KeySets will be re-added later in the scanning process. 3556 synchronized (mPackages) { 3557 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3558 } 3559 return PackageManager.SIGNATURE_MATCH; 3560 } 3561 return PackageManager.SIGNATURE_NO_MATCH; 3562 } 3563 3564 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3565 if (isExternal(scannedPkg)) { 3566 return mSettings.isExternalDatabaseVersionOlderThan( 3567 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3568 } else { 3569 return mSettings.isInternalDatabaseVersionOlderThan( 3570 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3571 } 3572 } 3573 3574 private int compareSignaturesRecover(PackageSignatures existingSigs, 3575 PackageParser.Package scannedPkg) { 3576 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3577 return PackageManager.SIGNATURE_NO_MATCH; 3578 } 3579 3580 String msg = null; 3581 try { 3582 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3583 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3584 + scannedPkg.packageName); 3585 return PackageManager.SIGNATURE_MATCH; 3586 } 3587 } catch (CertificateException e) { 3588 msg = e.getMessage(); 3589 } 3590 3591 logCriticalInfo(Log.INFO, 3592 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3593 return PackageManager.SIGNATURE_NO_MATCH; 3594 } 3595 3596 @Override 3597 public String[] getPackagesForUid(int uid) { 3598 uid = UserHandle.getAppId(uid); 3599 // reader 3600 synchronized (mPackages) { 3601 Object obj = mSettings.getUserIdLPr(uid); 3602 if (obj instanceof SharedUserSetting) { 3603 final SharedUserSetting sus = (SharedUserSetting) obj; 3604 final int N = sus.packages.size(); 3605 final String[] res = new String[N]; 3606 final Iterator<PackageSetting> it = sus.packages.iterator(); 3607 int i = 0; 3608 while (it.hasNext()) { 3609 res[i++] = it.next().name; 3610 } 3611 return res; 3612 } else if (obj instanceof PackageSetting) { 3613 final PackageSetting ps = (PackageSetting) obj; 3614 return new String[] { ps.name }; 3615 } 3616 } 3617 return null; 3618 } 3619 3620 @Override 3621 public String getNameForUid(int uid) { 3622 // reader 3623 synchronized (mPackages) { 3624 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3625 if (obj instanceof SharedUserSetting) { 3626 final SharedUserSetting sus = (SharedUserSetting) obj; 3627 return sus.name + ":" + sus.userId; 3628 } else if (obj instanceof PackageSetting) { 3629 final PackageSetting ps = (PackageSetting) obj; 3630 return ps.name; 3631 } 3632 } 3633 return null; 3634 } 3635 3636 @Override 3637 public int getUidForSharedUser(String sharedUserName) { 3638 if(sharedUserName == null) { 3639 return -1; 3640 } 3641 // reader 3642 synchronized (mPackages) { 3643 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3644 if (suid == null) { 3645 return -1; 3646 } 3647 return suid.userId; 3648 } 3649 } 3650 3651 @Override 3652 public int getFlagsForUid(int uid) { 3653 synchronized (mPackages) { 3654 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3655 if (obj instanceof SharedUserSetting) { 3656 final SharedUserSetting sus = (SharedUserSetting) obj; 3657 return sus.pkgFlags; 3658 } else if (obj instanceof PackageSetting) { 3659 final PackageSetting ps = (PackageSetting) obj; 3660 return ps.pkgFlags; 3661 } 3662 } 3663 return 0; 3664 } 3665 3666 @Override 3667 public int getPrivateFlagsForUid(int uid) { 3668 synchronized (mPackages) { 3669 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3670 if (obj instanceof SharedUserSetting) { 3671 final SharedUserSetting sus = (SharedUserSetting) obj; 3672 return sus.pkgPrivateFlags; 3673 } else if (obj instanceof PackageSetting) { 3674 final PackageSetting ps = (PackageSetting) obj; 3675 return ps.pkgPrivateFlags; 3676 } 3677 } 3678 return 0; 3679 } 3680 3681 @Override 3682 public boolean isUidPrivileged(int uid) { 3683 uid = UserHandle.getAppId(uid); 3684 // reader 3685 synchronized (mPackages) { 3686 Object obj = mSettings.getUserIdLPr(uid); 3687 if (obj instanceof SharedUserSetting) { 3688 final SharedUserSetting sus = (SharedUserSetting) obj; 3689 final Iterator<PackageSetting> it = sus.packages.iterator(); 3690 while (it.hasNext()) { 3691 if (it.next().isPrivileged()) { 3692 return true; 3693 } 3694 } 3695 } else if (obj instanceof PackageSetting) { 3696 final PackageSetting ps = (PackageSetting) obj; 3697 return ps.isPrivileged(); 3698 } 3699 } 3700 return false; 3701 } 3702 3703 @Override 3704 public String[] getAppOpPermissionPackages(String permissionName) { 3705 synchronized (mPackages) { 3706 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3707 if (pkgs == null) { 3708 return null; 3709 } 3710 return pkgs.toArray(new String[pkgs.size()]); 3711 } 3712 } 3713 3714 @Override 3715 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3716 int flags, int userId) { 3717 if (!sUserManager.exists(userId)) return null; 3718 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3719 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3720 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3721 } 3722 3723 @Override 3724 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3725 IntentFilter filter, int match, ComponentName activity) { 3726 final int userId = UserHandle.getCallingUserId(); 3727 if (DEBUG_PREFERRED) { 3728 Log.v(TAG, "setLastChosenActivity intent=" + intent 3729 + " resolvedType=" + resolvedType 3730 + " flags=" + flags 3731 + " filter=" + filter 3732 + " match=" + match 3733 + " activity=" + activity); 3734 filter.dump(new PrintStreamPrinter(System.out), " "); 3735 } 3736 intent.setComponent(null); 3737 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3738 // Find any earlier preferred or last chosen entries and nuke them 3739 findPreferredActivity(intent, resolvedType, 3740 flags, query, 0, false, true, false, userId); 3741 // Add the new activity as the last chosen for this filter 3742 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3743 "Setting last chosen"); 3744 } 3745 3746 @Override 3747 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3748 final int userId = UserHandle.getCallingUserId(); 3749 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3750 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3751 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3752 false, false, false, userId); 3753 } 3754 3755 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3756 int flags, List<ResolveInfo> query, int userId) { 3757 if (query != null) { 3758 final int N = query.size(); 3759 if (N == 1) { 3760 return query.get(0); 3761 } else if (N > 1) { 3762 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3763 // If there is more than one activity with the same priority, 3764 // then let the user decide between them. 3765 ResolveInfo r0 = query.get(0); 3766 ResolveInfo r1 = query.get(1); 3767 if (DEBUG_INTENT_MATCHING || debug) { 3768 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3769 + r1.activityInfo.name + "=" + r1.priority); 3770 } 3771 // If the first activity has a higher priority, or a different 3772 // default, then it is always desireable to pick it. 3773 if (r0.priority != r1.priority 3774 || r0.preferredOrder != r1.preferredOrder 3775 || r0.isDefault != r1.isDefault) { 3776 return query.get(0); 3777 } 3778 // If we have saved a preference for a preferred activity for 3779 // this Intent, use that. 3780 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3781 flags, query, r0.priority, true, false, debug, userId); 3782 if (ri != null) { 3783 return ri; 3784 } 3785 if (userId != 0) { 3786 ri = new ResolveInfo(mResolveInfo); 3787 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3788 ri.activityInfo.applicationInfo = new ApplicationInfo( 3789 ri.activityInfo.applicationInfo); 3790 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3791 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3792 return ri; 3793 } 3794 return mResolveInfo; 3795 } 3796 } 3797 return null; 3798 } 3799 3800 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3801 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3802 final int N = query.size(); 3803 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3804 .get(userId); 3805 // Get the list of persistent preferred activities that handle the intent 3806 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3807 List<PersistentPreferredActivity> pprefs = ppir != null 3808 ? ppir.queryIntent(intent, resolvedType, 3809 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3810 : null; 3811 if (pprefs != null && pprefs.size() > 0) { 3812 final int M = pprefs.size(); 3813 for (int i=0; i<M; i++) { 3814 final PersistentPreferredActivity ppa = pprefs.get(i); 3815 if (DEBUG_PREFERRED || debug) { 3816 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3817 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3818 + "\n component=" + ppa.mComponent); 3819 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3820 } 3821 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3822 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3823 if (DEBUG_PREFERRED || debug) { 3824 Slog.v(TAG, "Found persistent preferred activity:"); 3825 if (ai != null) { 3826 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3827 } else { 3828 Slog.v(TAG, " null"); 3829 } 3830 } 3831 if (ai == null) { 3832 // This previously registered persistent preferred activity 3833 // component is no longer known. Ignore it and do NOT remove it. 3834 continue; 3835 } 3836 for (int j=0; j<N; j++) { 3837 final ResolveInfo ri = query.get(j); 3838 if (!ri.activityInfo.applicationInfo.packageName 3839 .equals(ai.applicationInfo.packageName)) { 3840 continue; 3841 } 3842 if (!ri.activityInfo.name.equals(ai.name)) { 3843 continue; 3844 } 3845 // Found a persistent preference that can handle the intent. 3846 if (DEBUG_PREFERRED || debug) { 3847 Slog.v(TAG, "Returning persistent preferred activity: " + 3848 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3849 } 3850 return ri; 3851 } 3852 } 3853 } 3854 return null; 3855 } 3856 3857 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3858 List<ResolveInfo> query, int priority, boolean always, 3859 boolean removeMatches, boolean debug, int userId) { 3860 if (!sUserManager.exists(userId)) return null; 3861 // writer 3862 synchronized (mPackages) { 3863 if (intent.getSelector() != null) { 3864 intent = intent.getSelector(); 3865 } 3866 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3867 3868 // Try to find a matching persistent preferred activity. 3869 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3870 debug, userId); 3871 3872 // If a persistent preferred activity matched, use it. 3873 if (pri != null) { 3874 return pri; 3875 } 3876 3877 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3878 // Get the list of preferred activities that handle the intent 3879 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3880 List<PreferredActivity> prefs = pir != null 3881 ? pir.queryIntent(intent, resolvedType, 3882 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3883 : null; 3884 if (prefs != null && prefs.size() > 0) { 3885 boolean changed = false; 3886 try { 3887 // First figure out how good the original match set is. 3888 // We will only allow preferred activities that came 3889 // from the same match quality. 3890 int match = 0; 3891 3892 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3893 3894 final int N = query.size(); 3895 for (int j=0; j<N; j++) { 3896 final ResolveInfo ri = query.get(j); 3897 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3898 + ": 0x" + Integer.toHexString(match)); 3899 if (ri.match > match) { 3900 match = ri.match; 3901 } 3902 } 3903 3904 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3905 + Integer.toHexString(match)); 3906 3907 match &= IntentFilter.MATCH_CATEGORY_MASK; 3908 final int M = prefs.size(); 3909 for (int i=0; i<M; i++) { 3910 final PreferredActivity pa = prefs.get(i); 3911 if (DEBUG_PREFERRED || debug) { 3912 Slog.v(TAG, "Checking PreferredActivity ds=" 3913 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3914 + "\n component=" + pa.mPref.mComponent); 3915 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3916 } 3917 if (pa.mPref.mMatch != match) { 3918 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3919 + Integer.toHexString(pa.mPref.mMatch)); 3920 continue; 3921 } 3922 // If it's not an "always" type preferred activity and that's what we're 3923 // looking for, skip it. 3924 if (always && !pa.mPref.mAlways) { 3925 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3926 continue; 3927 } 3928 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3929 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3930 if (DEBUG_PREFERRED || debug) { 3931 Slog.v(TAG, "Found preferred activity:"); 3932 if (ai != null) { 3933 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3934 } else { 3935 Slog.v(TAG, " null"); 3936 } 3937 } 3938 if (ai == null) { 3939 // This previously registered preferred activity 3940 // component is no longer known. Most likely an update 3941 // to the app was installed and in the new version this 3942 // component no longer exists. Clean it up by removing 3943 // it from the preferred activities list, and skip it. 3944 Slog.w(TAG, "Removing dangling preferred activity: " 3945 + pa.mPref.mComponent); 3946 pir.removeFilter(pa); 3947 changed = true; 3948 continue; 3949 } 3950 for (int j=0; j<N; j++) { 3951 final ResolveInfo ri = query.get(j); 3952 if (!ri.activityInfo.applicationInfo.packageName 3953 .equals(ai.applicationInfo.packageName)) { 3954 continue; 3955 } 3956 if (!ri.activityInfo.name.equals(ai.name)) { 3957 continue; 3958 } 3959 3960 if (removeMatches) { 3961 pir.removeFilter(pa); 3962 changed = true; 3963 if (DEBUG_PREFERRED) { 3964 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3965 } 3966 break; 3967 } 3968 3969 // Okay we found a previously set preferred or last chosen app. 3970 // If the result set is different from when this 3971 // was created, we need to clear it and re-ask the 3972 // user their preference, if we're looking for an "always" type entry. 3973 if (always && !pa.mPref.sameSet(query)) { 3974 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3975 + intent + " type " + resolvedType); 3976 if (DEBUG_PREFERRED) { 3977 Slog.v(TAG, "Removing preferred activity since set changed " 3978 + pa.mPref.mComponent); 3979 } 3980 pir.removeFilter(pa); 3981 // Re-add the filter as a "last chosen" entry (!always) 3982 PreferredActivity lastChosen = new PreferredActivity( 3983 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3984 pir.addFilter(lastChosen); 3985 changed = true; 3986 return null; 3987 } 3988 3989 // Yay! Either the set matched or we're looking for the last chosen 3990 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3991 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3992 return ri; 3993 } 3994 } 3995 } finally { 3996 if (changed) { 3997 if (DEBUG_PREFERRED) { 3998 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3999 } 4000 scheduleWritePackageRestrictionsLocked(userId); 4001 } 4002 } 4003 } 4004 } 4005 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4006 return null; 4007 } 4008 4009 /* 4010 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4011 */ 4012 @Override 4013 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4014 int targetUserId) { 4015 mContext.enforceCallingOrSelfPermission( 4016 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4017 List<CrossProfileIntentFilter> matches = 4018 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4019 if (matches != null) { 4020 int size = matches.size(); 4021 for (int i = 0; i < size; i++) { 4022 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4023 } 4024 } 4025 return false; 4026 } 4027 4028 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4029 String resolvedType, int userId) { 4030 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4031 if (resolver != null) { 4032 return resolver.queryIntent(intent, resolvedType, false, userId); 4033 } 4034 return null; 4035 } 4036 4037 @Override 4038 public List<ResolveInfo> queryIntentActivities(Intent intent, 4039 String resolvedType, int flags, int userId) { 4040 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4041 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4042 ComponentName comp = intent.getComponent(); 4043 if (comp == null) { 4044 if (intent.getSelector() != null) { 4045 intent = intent.getSelector(); 4046 comp = intent.getComponent(); 4047 } 4048 } 4049 4050 if (comp != null) { 4051 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4052 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4053 if (ai != null) { 4054 final ResolveInfo ri = new ResolveInfo(); 4055 ri.activityInfo = ai; 4056 list.add(ri); 4057 } 4058 return list; 4059 } 4060 4061 // reader 4062 synchronized (mPackages) { 4063 final String pkgName = intent.getPackage(); 4064 if (pkgName == null) { 4065 List<CrossProfileIntentFilter> matchingFilters = 4066 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4067 // Check for results that need to skip the current profile. 4068 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4069 resolvedType, flags, userId); 4070 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4071 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4072 result.add(resolveInfo); 4073 return filterIfNotPrimaryUser(result, userId); 4074 } 4075 4076 // Check for results in the current profile. 4077 List<ResolveInfo> result = mActivities.queryIntent( 4078 intent, resolvedType, flags, userId); 4079 4080 // Check for cross profile results. 4081 resolveInfo = queryCrossProfileIntents( 4082 matchingFilters, intent, resolvedType, flags, userId); 4083 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4084 result.add(resolveInfo); 4085 Collections.sort(result, mResolvePrioritySorter); 4086 } 4087 result = filterIfNotPrimaryUser(result, userId); 4088 if (result.size() > 1 && hasWebURI(intent)) { 4089 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4090 } 4091 return result; 4092 } 4093 final PackageParser.Package pkg = mPackages.get(pkgName); 4094 if (pkg != null) { 4095 return filterIfNotPrimaryUser( 4096 mActivities.queryIntentForPackage( 4097 intent, resolvedType, flags, pkg.activities, userId), 4098 userId); 4099 } 4100 return new ArrayList<ResolveInfo>(); 4101 } 4102 } 4103 4104 private boolean isUserEnabled(int userId) { 4105 long callingId = Binder.clearCallingIdentity(); 4106 try { 4107 UserInfo userInfo = sUserManager.getUserInfo(userId); 4108 return userInfo != null && userInfo.isEnabled(); 4109 } finally { 4110 Binder.restoreCallingIdentity(callingId); 4111 } 4112 } 4113 4114 /** 4115 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4116 * 4117 * @return filtered list 4118 */ 4119 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4120 if (userId == UserHandle.USER_OWNER) { 4121 return resolveInfos; 4122 } 4123 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4124 ResolveInfo info = resolveInfos.get(i); 4125 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4126 resolveInfos.remove(i); 4127 } 4128 } 4129 return resolveInfos; 4130 } 4131 4132 private static boolean hasWebURI(Intent intent) { 4133 if (intent.getData() == null) { 4134 return false; 4135 } 4136 final String scheme = intent.getScheme(); 4137 if (TextUtils.isEmpty(scheme)) { 4138 return false; 4139 } 4140 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4141 } 4142 4143 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4144 int flags, List<ResolveInfo> candidates) { 4145 if (DEBUG_PREFERRED) { 4146 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4147 candidates.size()); 4148 } 4149 4150 final int userId = UserHandle.getCallingUserId(); 4151 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4152 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4153 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4154 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4155 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4156 4157 synchronized (mPackages) { 4158 final int count = candidates.size(); 4159 // First, try to use the domain prefered App. Partition the candidates into four lists: 4160 // one for the final results, one for the "do not use ever", one for "undefined status" 4161 // and finally one for "Browser App type". 4162 for (int n=0; n<count; n++) { 4163 ResolveInfo info = candidates.get(n); 4164 String packageName = info.activityInfo.packageName; 4165 PackageSetting ps = mSettings.mPackages.get(packageName); 4166 if (ps != null) { 4167 // Add to the special match all list (Browser use case) 4168 if (info.handleAllWebDataURI) { 4169 matchAllList.add(info); 4170 continue; 4171 } 4172 // Try to get the status from User settings first 4173 int status = getDomainVerificationStatusLPr(ps, userId); 4174 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4175 alwaysList.add(info); 4176 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4177 neverList.add(info); 4178 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4179 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4180 undefinedList.add(info); 4181 } 4182 } 4183 } 4184 // First try to add the "always" if there is any 4185 if (alwaysList.size() > 0) { 4186 result.addAll(alwaysList); 4187 } else { 4188 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4189 result.addAll(undefinedList); 4190 // Also add Browsers (all of them or only the default one) 4191 if ((flags & MATCH_ALL) != 0) { 4192 result.addAll(matchAllList); 4193 } else { 4194 // Try to add the Default Browser if we can 4195 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4196 UserHandle.myUserId()); 4197 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4198 boolean defaultBrowserFound = false; 4199 final int browserCount = matchAllList.size(); 4200 for (int n=0; n<browserCount; n++) { 4201 ResolveInfo browser = matchAllList.get(n); 4202 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4203 result.add(browser); 4204 defaultBrowserFound = true; 4205 break; 4206 } 4207 } 4208 if (!defaultBrowserFound) { 4209 result.addAll(matchAllList); 4210 } 4211 } else { 4212 result.addAll(matchAllList); 4213 } 4214 } 4215 4216 // If there is nothing selected, add all candidates and remove the ones that the User 4217 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4218 if (result.size() == 0) { 4219 result.addAll(candidates); 4220 result.removeAll(neverList); 4221 } 4222 } 4223 } 4224 if (DEBUG_PREFERRED) { 4225 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4226 result.size()); 4227 } 4228 return result; 4229 } 4230 4231 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4232 int status = ps.getDomainVerificationStatusForUser(userId); 4233 // if none available, get the master status 4234 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4235 if (ps.getIntentFilterVerificationInfo() != null) { 4236 status = ps.getIntentFilterVerificationInfo().getStatus(); 4237 } 4238 } 4239 return status; 4240 } 4241 4242 private ResolveInfo querySkipCurrentProfileIntents( 4243 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4244 int flags, int sourceUserId) { 4245 if (matchingFilters != null) { 4246 int size = matchingFilters.size(); 4247 for (int i = 0; i < size; i ++) { 4248 CrossProfileIntentFilter filter = matchingFilters.get(i); 4249 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4250 // Checking if there are activities in the target user that can handle the 4251 // intent. 4252 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4253 flags, sourceUserId); 4254 if (resolveInfo != null) { 4255 return resolveInfo; 4256 } 4257 } 4258 } 4259 } 4260 return null; 4261 } 4262 4263 // Return matching ResolveInfo if any for skip current profile intent filters. 4264 private ResolveInfo queryCrossProfileIntents( 4265 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4266 int flags, int sourceUserId) { 4267 if (matchingFilters != null) { 4268 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4269 // match the same intent. For performance reasons, it is better not to 4270 // run queryIntent twice for the same userId 4271 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4272 int size = matchingFilters.size(); 4273 for (int i = 0; i < size; i++) { 4274 CrossProfileIntentFilter filter = matchingFilters.get(i); 4275 int targetUserId = filter.getTargetUserId(); 4276 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4277 && !alreadyTriedUserIds.get(targetUserId)) { 4278 // Checking if there are activities in the target user that can handle the 4279 // intent. 4280 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4281 flags, sourceUserId); 4282 if (resolveInfo != null) return resolveInfo; 4283 alreadyTriedUserIds.put(targetUserId, true); 4284 } 4285 } 4286 } 4287 return null; 4288 } 4289 4290 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4291 String resolvedType, int flags, int sourceUserId) { 4292 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4293 resolvedType, flags, filter.getTargetUserId()); 4294 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4295 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4296 } 4297 return null; 4298 } 4299 4300 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4301 int sourceUserId, int targetUserId) { 4302 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4303 String className; 4304 if (targetUserId == UserHandle.USER_OWNER) { 4305 className = FORWARD_INTENT_TO_USER_OWNER; 4306 } else { 4307 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4308 } 4309 ComponentName forwardingActivityComponentName = new ComponentName( 4310 mAndroidApplication.packageName, className); 4311 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4312 sourceUserId); 4313 if (targetUserId == UserHandle.USER_OWNER) { 4314 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4315 forwardingResolveInfo.noResourceId = true; 4316 } 4317 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4318 forwardingResolveInfo.priority = 0; 4319 forwardingResolveInfo.preferredOrder = 0; 4320 forwardingResolveInfo.match = 0; 4321 forwardingResolveInfo.isDefault = true; 4322 forwardingResolveInfo.filter = filter; 4323 forwardingResolveInfo.targetUserId = targetUserId; 4324 return forwardingResolveInfo; 4325 } 4326 4327 @Override 4328 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4329 Intent[] specifics, String[] specificTypes, Intent intent, 4330 String resolvedType, int flags, int userId) { 4331 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4332 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4333 false, "query intent activity options"); 4334 final String resultsAction = intent.getAction(); 4335 4336 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4337 | PackageManager.GET_RESOLVED_FILTER, userId); 4338 4339 if (DEBUG_INTENT_MATCHING) { 4340 Log.v(TAG, "Query " + intent + ": " + results); 4341 } 4342 4343 int specificsPos = 0; 4344 int N; 4345 4346 // todo: note that the algorithm used here is O(N^2). This 4347 // isn't a problem in our current environment, but if we start running 4348 // into situations where we have more than 5 or 10 matches then this 4349 // should probably be changed to something smarter... 4350 4351 // First we go through and resolve each of the specific items 4352 // that were supplied, taking care of removing any corresponding 4353 // duplicate items in the generic resolve list. 4354 if (specifics != null) { 4355 for (int i=0; i<specifics.length; i++) { 4356 final Intent sintent = specifics[i]; 4357 if (sintent == null) { 4358 continue; 4359 } 4360 4361 if (DEBUG_INTENT_MATCHING) { 4362 Log.v(TAG, "Specific #" + i + ": " + sintent); 4363 } 4364 4365 String action = sintent.getAction(); 4366 if (resultsAction != null && resultsAction.equals(action)) { 4367 // If this action was explicitly requested, then don't 4368 // remove things that have it. 4369 action = null; 4370 } 4371 4372 ResolveInfo ri = null; 4373 ActivityInfo ai = null; 4374 4375 ComponentName comp = sintent.getComponent(); 4376 if (comp == null) { 4377 ri = resolveIntent( 4378 sintent, 4379 specificTypes != null ? specificTypes[i] : null, 4380 flags, userId); 4381 if (ri == null) { 4382 continue; 4383 } 4384 if (ri == mResolveInfo) { 4385 // ACK! Must do something better with this. 4386 } 4387 ai = ri.activityInfo; 4388 comp = new ComponentName(ai.applicationInfo.packageName, 4389 ai.name); 4390 } else { 4391 ai = getActivityInfo(comp, flags, userId); 4392 if (ai == null) { 4393 continue; 4394 } 4395 } 4396 4397 // Look for any generic query activities that are duplicates 4398 // of this specific one, and remove them from the results. 4399 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4400 N = results.size(); 4401 int j; 4402 for (j=specificsPos; j<N; j++) { 4403 ResolveInfo sri = results.get(j); 4404 if ((sri.activityInfo.name.equals(comp.getClassName()) 4405 && sri.activityInfo.applicationInfo.packageName.equals( 4406 comp.getPackageName())) 4407 || (action != null && sri.filter.matchAction(action))) { 4408 results.remove(j); 4409 if (DEBUG_INTENT_MATCHING) Log.v( 4410 TAG, "Removing duplicate item from " + j 4411 + " due to specific " + specificsPos); 4412 if (ri == null) { 4413 ri = sri; 4414 } 4415 j--; 4416 N--; 4417 } 4418 } 4419 4420 // Add this specific item to its proper place. 4421 if (ri == null) { 4422 ri = new ResolveInfo(); 4423 ri.activityInfo = ai; 4424 } 4425 results.add(specificsPos, ri); 4426 ri.specificIndex = i; 4427 specificsPos++; 4428 } 4429 } 4430 4431 // Now we go through the remaining generic results and remove any 4432 // duplicate actions that are found here. 4433 N = results.size(); 4434 for (int i=specificsPos; i<N-1; i++) { 4435 final ResolveInfo rii = results.get(i); 4436 if (rii.filter == null) { 4437 continue; 4438 } 4439 4440 // Iterate over all of the actions of this result's intent 4441 // filter... typically this should be just one. 4442 final Iterator<String> it = rii.filter.actionsIterator(); 4443 if (it == null) { 4444 continue; 4445 } 4446 while (it.hasNext()) { 4447 final String action = it.next(); 4448 if (resultsAction != null && resultsAction.equals(action)) { 4449 // If this action was explicitly requested, then don't 4450 // remove things that have it. 4451 continue; 4452 } 4453 for (int j=i+1; j<N; j++) { 4454 final ResolveInfo rij = results.get(j); 4455 if (rij.filter != null && rij.filter.hasAction(action)) { 4456 results.remove(j); 4457 if (DEBUG_INTENT_MATCHING) Log.v( 4458 TAG, "Removing duplicate item from " + j 4459 + " due to action " + action + " at " + i); 4460 j--; 4461 N--; 4462 } 4463 } 4464 } 4465 4466 // If the caller didn't request filter information, drop it now 4467 // so we don't have to marshall/unmarshall it. 4468 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4469 rii.filter = null; 4470 } 4471 } 4472 4473 // Filter out the caller activity if so requested. 4474 if (caller != null) { 4475 N = results.size(); 4476 for (int i=0; i<N; i++) { 4477 ActivityInfo ainfo = results.get(i).activityInfo; 4478 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4479 && caller.getClassName().equals(ainfo.name)) { 4480 results.remove(i); 4481 break; 4482 } 4483 } 4484 } 4485 4486 // If the caller didn't request filter information, 4487 // drop them now so we don't have to 4488 // marshall/unmarshall it. 4489 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4490 N = results.size(); 4491 for (int i=0; i<N; i++) { 4492 results.get(i).filter = null; 4493 } 4494 } 4495 4496 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4497 return results; 4498 } 4499 4500 @Override 4501 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4502 int userId) { 4503 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4504 ComponentName comp = intent.getComponent(); 4505 if (comp == null) { 4506 if (intent.getSelector() != null) { 4507 intent = intent.getSelector(); 4508 comp = intent.getComponent(); 4509 } 4510 } 4511 if (comp != null) { 4512 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4513 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4514 if (ai != null) { 4515 ResolveInfo ri = new ResolveInfo(); 4516 ri.activityInfo = ai; 4517 list.add(ri); 4518 } 4519 return list; 4520 } 4521 4522 // reader 4523 synchronized (mPackages) { 4524 String pkgName = intent.getPackage(); 4525 if (pkgName == null) { 4526 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4527 } 4528 final PackageParser.Package pkg = mPackages.get(pkgName); 4529 if (pkg != null) { 4530 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4531 userId); 4532 } 4533 return null; 4534 } 4535 } 4536 4537 @Override 4538 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4539 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4540 if (!sUserManager.exists(userId)) return null; 4541 if (query != null) { 4542 if (query.size() >= 1) { 4543 // If there is more than one service with the same priority, 4544 // just arbitrarily pick the first one. 4545 return query.get(0); 4546 } 4547 } 4548 return null; 4549 } 4550 4551 @Override 4552 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4553 int userId) { 4554 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4555 ComponentName comp = intent.getComponent(); 4556 if (comp == null) { 4557 if (intent.getSelector() != null) { 4558 intent = intent.getSelector(); 4559 comp = intent.getComponent(); 4560 } 4561 } 4562 if (comp != null) { 4563 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4564 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4565 if (si != null) { 4566 final ResolveInfo ri = new ResolveInfo(); 4567 ri.serviceInfo = si; 4568 list.add(ri); 4569 } 4570 return list; 4571 } 4572 4573 // reader 4574 synchronized (mPackages) { 4575 String pkgName = intent.getPackage(); 4576 if (pkgName == null) { 4577 return mServices.queryIntent(intent, resolvedType, flags, userId); 4578 } 4579 final PackageParser.Package pkg = mPackages.get(pkgName); 4580 if (pkg != null) { 4581 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4582 userId); 4583 } 4584 return null; 4585 } 4586 } 4587 4588 @Override 4589 public List<ResolveInfo> queryIntentContentProviders( 4590 Intent intent, String resolvedType, int flags, int userId) { 4591 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4592 ComponentName comp = intent.getComponent(); 4593 if (comp == null) { 4594 if (intent.getSelector() != null) { 4595 intent = intent.getSelector(); 4596 comp = intent.getComponent(); 4597 } 4598 } 4599 if (comp != null) { 4600 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4601 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4602 if (pi != null) { 4603 final ResolveInfo ri = new ResolveInfo(); 4604 ri.providerInfo = pi; 4605 list.add(ri); 4606 } 4607 return list; 4608 } 4609 4610 // reader 4611 synchronized (mPackages) { 4612 String pkgName = intent.getPackage(); 4613 if (pkgName == null) { 4614 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4615 } 4616 final PackageParser.Package pkg = mPackages.get(pkgName); 4617 if (pkg != null) { 4618 return mProviders.queryIntentForPackage( 4619 intent, resolvedType, flags, pkg.providers, userId); 4620 } 4621 return null; 4622 } 4623 } 4624 4625 @Override 4626 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4627 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4628 4629 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4630 4631 // writer 4632 synchronized (mPackages) { 4633 ArrayList<PackageInfo> list; 4634 if (listUninstalled) { 4635 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4636 for (PackageSetting ps : mSettings.mPackages.values()) { 4637 PackageInfo pi; 4638 if (ps.pkg != null) { 4639 pi = generatePackageInfo(ps.pkg, flags, userId); 4640 } else { 4641 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4642 } 4643 if (pi != null) { 4644 list.add(pi); 4645 } 4646 } 4647 } else { 4648 list = new ArrayList<PackageInfo>(mPackages.size()); 4649 for (PackageParser.Package p : mPackages.values()) { 4650 PackageInfo pi = generatePackageInfo(p, flags, userId); 4651 if (pi != null) { 4652 list.add(pi); 4653 } 4654 } 4655 } 4656 4657 return new ParceledListSlice<PackageInfo>(list); 4658 } 4659 } 4660 4661 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4662 String[] permissions, boolean[] tmp, int flags, int userId) { 4663 int numMatch = 0; 4664 final PermissionsState permissionsState = ps.getPermissionsState(); 4665 for (int i=0; i<permissions.length; i++) { 4666 final String permission = permissions[i]; 4667 if (permissionsState.hasPermission(permission, userId)) { 4668 tmp[i] = true; 4669 numMatch++; 4670 } else { 4671 tmp[i] = false; 4672 } 4673 } 4674 if (numMatch == 0) { 4675 return; 4676 } 4677 PackageInfo pi; 4678 if (ps.pkg != null) { 4679 pi = generatePackageInfo(ps.pkg, flags, userId); 4680 } else { 4681 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4682 } 4683 // The above might return null in cases of uninstalled apps or install-state 4684 // skew across users/profiles. 4685 if (pi != null) { 4686 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4687 if (numMatch == permissions.length) { 4688 pi.requestedPermissions = permissions; 4689 } else { 4690 pi.requestedPermissions = new String[numMatch]; 4691 numMatch = 0; 4692 for (int i=0; i<permissions.length; i++) { 4693 if (tmp[i]) { 4694 pi.requestedPermissions[numMatch] = permissions[i]; 4695 numMatch++; 4696 } 4697 } 4698 } 4699 } 4700 list.add(pi); 4701 } 4702 } 4703 4704 @Override 4705 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4706 String[] permissions, int flags, int userId) { 4707 if (!sUserManager.exists(userId)) return null; 4708 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4709 4710 // writer 4711 synchronized (mPackages) { 4712 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4713 boolean[] tmpBools = new boolean[permissions.length]; 4714 if (listUninstalled) { 4715 for (PackageSetting ps : mSettings.mPackages.values()) { 4716 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4717 } 4718 } else { 4719 for (PackageParser.Package pkg : mPackages.values()) { 4720 PackageSetting ps = (PackageSetting)pkg.mExtras; 4721 if (ps != null) { 4722 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4723 userId); 4724 } 4725 } 4726 } 4727 4728 return new ParceledListSlice<PackageInfo>(list); 4729 } 4730 } 4731 4732 @Override 4733 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4734 if (!sUserManager.exists(userId)) return null; 4735 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4736 4737 // writer 4738 synchronized (mPackages) { 4739 ArrayList<ApplicationInfo> list; 4740 if (listUninstalled) { 4741 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4742 for (PackageSetting ps : mSettings.mPackages.values()) { 4743 ApplicationInfo ai; 4744 if (ps.pkg != null) { 4745 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4746 ps.readUserState(userId), userId); 4747 } else { 4748 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4749 } 4750 if (ai != null) { 4751 list.add(ai); 4752 } 4753 } 4754 } else { 4755 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4756 for (PackageParser.Package p : mPackages.values()) { 4757 if (p.mExtras != null) { 4758 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4759 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4760 if (ai != null) { 4761 list.add(ai); 4762 } 4763 } 4764 } 4765 } 4766 4767 return new ParceledListSlice<ApplicationInfo>(list); 4768 } 4769 } 4770 4771 public List<ApplicationInfo> getPersistentApplications(int flags) { 4772 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4773 4774 // reader 4775 synchronized (mPackages) { 4776 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4777 final int userId = UserHandle.getCallingUserId(); 4778 while (i.hasNext()) { 4779 final PackageParser.Package p = i.next(); 4780 if (p.applicationInfo != null 4781 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4782 && (!mSafeMode || isSystemApp(p))) { 4783 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4784 if (ps != null) { 4785 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4786 ps.readUserState(userId), userId); 4787 if (ai != null) { 4788 finalList.add(ai); 4789 } 4790 } 4791 } 4792 } 4793 } 4794 4795 return finalList; 4796 } 4797 4798 @Override 4799 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4800 if (!sUserManager.exists(userId)) return null; 4801 // reader 4802 synchronized (mPackages) { 4803 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4804 PackageSetting ps = provider != null 4805 ? mSettings.mPackages.get(provider.owner.packageName) 4806 : null; 4807 return ps != null 4808 && mSettings.isEnabledLPr(provider.info, flags, userId) 4809 && (!mSafeMode || (provider.info.applicationInfo.flags 4810 &ApplicationInfo.FLAG_SYSTEM) != 0) 4811 ? PackageParser.generateProviderInfo(provider, flags, 4812 ps.readUserState(userId), userId) 4813 : null; 4814 } 4815 } 4816 4817 /** 4818 * @deprecated 4819 */ 4820 @Deprecated 4821 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4822 // reader 4823 synchronized (mPackages) { 4824 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4825 .entrySet().iterator(); 4826 final int userId = UserHandle.getCallingUserId(); 4827 while (i.hasNext()) { 4828 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4829 PackageParser.Provider p = entry.getValue(); 4830 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4831 4832 if (ps != null && p.syncable 4833 && (!mSafeMode || (p.info.applicationInfo.flags 4834 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4835 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4836 ps.readUserState(userId), userId); 4837 if (info != null) { 4838 outNames.add(entry.getKey()); 4839 outInfo.add(info); 4840 } 4841 } 4842 } 4843 } 4844 } 4845 4846 @Override 4847 public List<ProviderInfo> queryContentProviders(String processName, 4848 int uid, int flags) { 4849 ArrayList<ProviderInfo> finalList = null; 4850 // reader 4851 synchronized (mPackages) { 4852 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4853 final int userId = processName != null ? 4854 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4855 while (i.hasNext()) { 4856 final PackageParser.Provider p = i.next(); 4857 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4858 if (ps != null && p.info.authority != null 4859 && (processName == null 4860 || (p.info.processName.equals(processName) 4861 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4862 && mSettings.isEnabledLPr(p.info, flags, userId) 4863 && (!mSafeMode 4864 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4865 if (finalList == null) { 4866 finalList = new ArrayList<ProviderInfo>(3); 4867 } 4868 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4869 ps.readUserState(userId), userId); 4870 if (info != null) { 4871 finalList.add(info); 4872 } 4873 } 4874 } 4875 } 4876 4877 if (finalList != null) { 4878 Collections.sort(finalList, mProviderInitOrderSorter); 4879 } 4880 4881 return finalList; 4882 } 4883 4884 @Override 4885 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4886 int flags) { 4887 // reader 4888 synchronized (mPackages) { 4889 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4890 return PackageParser.generateInstrumentationInfo(i, flags); 4891 } 4892 } 4893 4894 @Override 4895 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4896 int flags) { 4897 ArrayList<InstrumentationInfo> finalList = 4898 new ArrayList<InstrumentationInfo>(); 4899 4900 // reader 4901 synchronized (mPackages) { 4902 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4903 while (i.hasNext()) { 4904 final PackageParser.Instrumentation p = i.next(); 4905 if (targetPackage == null 4906 || targetPackage.equals(p.info.targetPackage)) { 4907 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4908 flags); 4909 if (ii != null) { 4910 finalList.add(ii); 4911 } 4912 } 4913 } 4914 } 4915 4916 return finalList; 4917 } 4918 4919 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4920 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4921 if (overlays == null) { 4922 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4923 return; 4924 } 4925 for (PackageParser.Package opkg : overlays.values()) { 4926 // Not much to do if idmap fails: we already logged the error 4927 // and we certainly don't want to abort installation of pkg simply 4928 // because an overlay didn't fit properly. For these reasons, 4929 // ignore the return value of createIdmapForPackagePairLI. 4930 createIdmapForPackagePairLI(pkg, opkg); 4931 } 4932 } 4933 4934 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4935 PackageParser.Package opkg) { 4936 if (!opkg.mTrustedOverlay) { 4937 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4938 opkg.baseCodePath + ": overlay not trusted"); 4939 return false; 4940 } 4941 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4942 if (overlaySet == null) { 4943 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4944 opkg.baseCodePath + " but target package has no known overlays"); 4945 return false; 4946 } 4947 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4948 // TODO: generate idmap for split APKs 4949 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4950 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4951 + opkg.baseCodePath); 4952 return false; 4953 } 4954 PackageParser.Package[] overlayArray = 4955 overlaySet.values().toArray(new PackageParser.Package[0]); 4956 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4957 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4958 return p1.mOverlayPriority - p2.mOverlayPriority; 4959 } 4960 }; 4961 Arrays.sort(overlayArray, cmp); 4962 4963 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4964 int i = 0; 4965 for (PackageParser.Package p : overlayArray) { 4966 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4967 } 4968 return true; 4969 } 4970 4971 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4972 final File[] files = dir.listFiles(); 4973 if (ArrayUtils.isEmpty(files)) { 4974 Log.d(TAG, "No files in app dir " + dir); 4975 return; 4976 } 4977 4978 if (DEBUG_PACKAGE_SCANNING) { 4979 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4980 + " flags=0x" + Integer.toHexString(parseFlags)); 4981 } 4982 4983 for (File file : files) { 4984 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4985 && !PackageInstallerService.isStageName(file.getName()); 4986 if (!isPackage) { 4987 // Ignore entries which are not packages 4988 continue; 4989 } 4990 try { 4991 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4992 scanFlags, currentTime, null); 4993 } catch (PackageManagerException e) { 4994 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4995 4996 // Delete invalid userdata apps 4997 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4998 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4999 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5000 if (file.isDirectory()) { 5001 mInstaller.rmPackageDir(file.getAbsolutePath()); 5002 } else { 5003 file.delete(); 5004 } 5005 } 5006 } 5007 } 5008 } 5009 5010 private static File getSettingsProblemFile() { 5011 File dataDir = Environment.getDataDirectory(); 5012 File systemDir = new File(dataDir, "system"); 5013 File fname = new File(systemDir, "uiderrors.txt"); 5014 return fname; 5015 } 5016 5017 static void reportSettingsProblem(int priority, String msg) { 5018 logCriticalInfo(priority, msg); 5019 } 5020 5021 static void logCriticalInfo(int priority, String msg) { 5022 Slog.println(priority, TAG, msg); 5023 EventLogTags.writePmCriticalInfo(msg); 5024 try { 5025 File fname = getSettingsProblemFile(); 5026 FileOutputStream out = new FileOutputStream(fname, true); 5027 PrintWriter pw = new FastPrintWriter(out); 5028 SimpleDateFormat formatter = new SimpleDateFormat(); 5029 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5030 pw.println(dateString + ": " + msg); 5031 pw.close(); 5032 FileUtils.setPermissions( 5033 fname.toString(), 5034 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5035 -1, -1); 5036 } catch (java.io.IOException e) { 5037 } 5038 } 5039 5040 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5041 PackageParser.Package pkg, File srcFile, int parseFlags) 5042 throws PackageManagerException { 5043 if (ps != null 5044 && ps.codePath.equals(srcFile) 5045 && ps.timeStamp == srcFile.lastModified() 5046 && !isCompatSignatureUpdateNeeded(pkg) 5047 && !isRecoverSignatureUpdateNeeded(pkg)) { 5048 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5049 if (ps.signatures.mSignatures != null 5050 && ps.signatures.mSignatures.length != 0 5051 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5052 // Optimization: reuse the existing cached certificates 5053 // if the package appears to be unchanged. 5054 pkg.mSignatures = ps.signatures.mSignatures; 5055 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5056 synchronized (mPackages) { 5057 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5058 } 5059 return; 5060 } 5061 5062 Slog.w(TAG, "PackageSetting for " + ps.name 5063 + " is missing signatures. Collecting certs again to recover them."); 5064 } else { 5065 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5066 } 5067 5068 try { 5069 pp.collectCertificates(pkg, parseFlags); 5070 pp.collectManifestDigest(pkg); 5071 } catch (PackageParserException e) { 5072 throw PackageManagerException.from(e); 5073 } 5074 } 5075 5076 /* 5077 * Scan a package and return the newly parsed package. 5078 * Returns null in case of errors and the error code is stored in mLastScanError 5079 */ 5080 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5081 long currentTime, UserHandle user) throws PackageManagerException { 5082 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5083 parseFlags |= mDefParseFlags; 5084 PackageParser pp = new PackageParser(); 5085 pp.setSeparateProcesses(mSeparateProcesses); 5086 pp.setOnlyCoreApps(mOnlyCore); 5087 pp.setDisplayMetrics(mMetrics); 5088 5089 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5090 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5091 } 5092 5093 final PackageParser.Package pkg; 5094 try { 5095 pkg = pp.parsePackage(scanFile, parseFlags); 5096 } catch (PackageParserException e) { 5097 throw PackageManagerException.from(e); 5098 } 5099 5100 PackageSetting ps = null; 5101 PackageSetting updatedPkg; 5102 // reader 5103 synchronized (mPackages) { 5104 // Look to see if we already know about this package. 5105 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5106 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5107 // This package has been renamed to its original name. Let's 5108 // use that. 5109 ps = mSettings.peekPackageLPr(oldName); 5110 } 5111 // If there was no original package, see one for the real package name. 5112 if (ps == null) { 5113 ps = mSettings.peekPackageLPr(pkg.packageName); 5114 } 5115 // Check to see if this package could be hiding/updating a system 5116 // package. Must look for it either under the original or real 5117 // package name depending on our state. 5118 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5119 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5120 } 5121 boolean updatedPkgBetter = false; 5122 // First check if this is a system package that may involve an update 5123 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5124 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5125 // it needs to drop FLAG_PRIVILEGED. 5126 if (locationIsPrivileged(scanFile)) { 5127 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5128 } else { 5129 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5130 } 5131 5132 if (ps != null && !ps.codePath.equals(scanFile)) { 5133 // The path has changed from what was last scanned... check the 5134 // version of the new path against what we have stored to determine 5135 // what to do. 5136 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5137 if (pkg.mVersionCode <= ps.versionCode) { 5138 // The system package has been updated and the code path does not match 5139 // Ignore entry. Skip it. 5140 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5141 + " ignored: updated version " + ps.versionCode 5142 + " better than this " + pkg.mVersionCode); 5143 if (!updatedPkg.codePath.equals(scanFile)) { 5144 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5145 + ps.name + " changing from " + updatedPkg.codePathString 5146 + " to " + scanFile); 5147 updatedPkg.codePath = scanFile; 5148 updatedPkg.codePathString = scanFile.toString(); 5149 updatedPkg.resourcePath = scanFile; 5150 updatedPkg.resourcePathString = scanFile.toString(); 5151 } 5152 updatedPkg.pkg = pkg; 5153 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5154 } else { 5155 // The current app on the system partition is better than 5156 // what we have updated to on the data partition; switch 5157 // back to the system partition version. 5158 // At this point, its safely assumed that package installation for 5159 // apps in system partition will go through. If not there won't be a working 5160 // version of the app 5161 // writer 5162 synchronized (mPackages) { 5163 // Just remove the loaded entries from package lists. 5164 mPackages.remove(ps.name); 5165 } 5166 5167 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5168 + " reverting from " + ps.codePathString 5169 + ": new version " + pkg.mVersionCode 5170 + " better than installed " + ps.versionCode); 5171 5172 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5173 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5174 synchronized (mInstallLock) { 5175 args.cleanUpResourcesLI(); 5176 } 5177 synchronized (mPackages) { 5178 mSettings.enableSystemPackageLPw(ps.name); 5179 } 5180 updatedPkgBetter = true; 5181 } 5182 } 5183 } 5184 5185 if (updatedPkg != null) { 5186 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5187 // initially 5188 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5189 5190 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5191 // flag set initially 5192 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5193 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5194 } 5195 } 5196 5197 // Verify certificates against what was last scanned 5198 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5199 5200 /* 5201 * A new system app appeared, but we already had a non-system one of the 5202 * same name installed earlier. 5203 */ 5204 boolean shouldHideSystemApp = false; 5205 if (updatedPkg == null && ps != null 5206 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5207 /* 5208 * Check to make sure the signatures match first. If they don't, 5209 * wipe the installed application and its data. 5210 */ 5211 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5212 != PackageManager.SIGNATURE_MATCH) { 5213 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5214 + " signatures don't match existing userdata copy; removing"); 5215 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5216 ps = null; 5217 } else { 5218 /* 5219 * If the newly-added system app is an older version than the 5220 * already installed version, hide it. It will be scanned later 5221 * and re-added like an update. 5222 */ 5223 if (pkg.mVersionCode <= ps.versionCode) { 5224 shouldHideSystemApp = true; 5225 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5226 + " but new version " + pkg.mVersionCode + " better than installed " 5227 + ps.versionCode + "; hiding system"); 5228 } else { 5229 /* 5230 * The newly found system app is a newer version that the 5231 * one previously installed. Simply remove the 5232 * already-installed application and replace it with our own 5233 * while keeping the application data. 5234 */ 5235 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5236 + " reverting from " + ps.codePathString + ": new version " 5237 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5238 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5239 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5240 synchronized (mInstallLock) { 5241 args.cleanUpResourcesLI(); 5242 } 5243 } 5244 } 5245 } 5246 5247 // The apk is forward locked (not public) if its code and resources 5248 // are kept in different files. (except for app in either system or 5249 // vendor path). 5250 // TODO grab this value from PackageSettings 5251 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5252 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5253 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5254 } 5255 } 5256 5257 // TODO: extend to support forward-locked splits 5258 String resourcePath = null; 5259 String baseResourcePath = null; 5260 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5261 if (ps != null && ps.resourcePathString != null) { 5262 resourcePath = ps.resourcePathString; 5263 baseResourcePath = ps.resourcePathString; 5264 } else { 5265 // Should not happen at all. Just log an error. 5266 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5267 } 5268 } else { 5269 resourcePath = pkg.codePath; 5270 baseResourcePath = pkg.baseCodePath; 5271 } 5272 5273 // Set application objects path explicitly. 5274 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5275 pkg.applicationInfo.setCodePath(pkg.codePath); 5276 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5277 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5278 pkg.applicationInfo.setResourcePath(resourcePath); 5279 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5280 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5281 5282 // Note that we invoke the following method only if we are about to unpack an application 5283 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5284 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5285 5286 /* 5287 * If the system app should be overridden by a previously installed 5288 * data, hide the system app now and let the /data/app scan pick it up 5289 * again. 5290 */ 5291 if (shouldHideSystemApp) { 5292 synchronized (mPackages) { 5293 /* 5294 * We have to grant systems permissions before we hide, because 5295 * grantPermissions will assume the package update is trying to 5296 * expand its permissions. 5297 */ 5298 grantPermissionsLPw(pkg, true, pkg.packageName); 5299 mSettings.disableSystemPackageLPw(pkg.packageName); 5300 } 5301 } 5302 5303 return scannedPkg; 5304 } 5305 5306 private static String fixProcessName(String defProcessName, 5307 String processName, int uid) { 5308 if (processName == null) { 5309 return defProcessName; 5310 } 5311 return processName; 5312 } 5313 5314 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5315 throws PackageManagerException { 5316 if (pkgSetting.signatures.mSignatures != null) { 5317 // Already existing package. Make sure signatures match 5318 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5319 == PackageManager.SIGNATURE_MATCH; 5320 if (!match) { 5321 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5322 == PackageManager.SIGNATURE_MATCH; 5323 } 5324 if (!match) { 5325 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5326 == PackageManager.SIGNATURE_MATCH; 5327 } 5328 if (!match) { 5329 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5330 + pkg.packageName + " signatures do not match the " 5331 + "previously installed version; ignoring!"); 5332 } 5333 } 5334 5335 // Check for shared user signatures 5336 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5337 // Already existing package. Make sure signatures match 5338 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5339 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5340 if (!match) { 5341 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5342 == PackageManager.SIGNATURE_MATCH; 5343 } 5344 if (!match) { 5345 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5346 == PackageManager.SIGNATURE_MATCH; 5347 } 5348 if (!match) { 5349 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5350 "Package " + pkg.packageName 5351 + " has no signatures that match those in shared user " 5352 + pkgSetting.sharedUser.name + "; ignoring!"); 5353 } 5354 } 5355 } 5356 5357 /** 5358 * Enforces that only the system UID or root's UID can call a method exposed 5359 * via Binder. 5360 * 5361 * @param message used as message if SecurityException is thrown 5362 * @throws SecurityException if the caller is not system or root 5363 */ 5364 private static final void enforceSystemOrRoot(String message) { 5365 final int uid = Binder.getCallingUid(); 5366 if (uid != Process.SYSTEM_UID && uid != 0) { 5367 throw new SecurityException(message); 5368 } 5369 } 5370 5371 @Override 5372 public void performBootDexOpt() { 5373 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5374 5375 // Before everything else, see whether we need to fstrim. 5376 try { 5377 IMountService ms = PackageHelper.getMountService(); 5378 if (ms != null) { 5379 final boolean isUpgrade = isUpgrade(); 5380 boolean doTrim = isUpgrade; 5381 if (doTrim) { 5382 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5383 } else { 5384 final long interval = android.provider.Settings.Global.getLong( 5385 mContext.getContentResolver(), 5386 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5387 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5388 if (interval > 0) { 5389 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5390 if (timeSinceLast > interval) { 5391 doTrim = true; 5392 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5393 + "; running immediately"); 5394 } 5395 } 5396 } 5397 if (doTrim) { 5398 if (!isFirstBoot()) { 5399 try { 5400 ActivityManagerNative.getDefault().showBootMessage( 5401 mContext.getResources().getString( 5402 R.string.android_upgrading_fstrim), true); 5403 } catch (RemoteException e) { 5404 } 5405 } 5406 ms.runMaintenance(); 5407 } 5408 } else { 5409 Slog.e(TAG, "Mount service unavailable!"); 5410 } 5411 } catch (RemoteException e) { 5412 // Can't happen; MountService is local 5413 } 5414 5415 final ArraySet<PackageParser.Package> pkgs; 5416 synchronized (mPackages) { 5417 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5418 } 5419 5420 if (pkgs != null) { 5421 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5422 // in case the device runs out of space. 5423 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5424 // Give priority to core apps. 5425 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5426 PackageParser.Package pkg = it.next(); 5427 if (pkg.coreApp) { 5428 if (DEBUG_DEXOPT) { 5429 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5430 } 5431 sortedPkgs.add(pkg); 5432 it.remove(); 5433 } 5434 } 5435 // Give priority to system apps that listen for pre boot complete. 5436 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5437 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5438 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5439 PackageParser.Package pkg = it.next(); 5440 if (pkgNames.contains(pkg.packageName)) { 5441 if (DEBUG_DEXOPT) { 5442 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5443 } 5444 sortedPkgs.add(pkg); 5445 it.remove(); 5446 } 5447 } 5448 // Give priority to system apps. 5449 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5450 PackageParser.Package pkg = it.next(); 5451 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5452 if (DEBUG_DEXOPT) { 5453 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5454 } 5455 sortedPkgs.add(pkg); 5456 it.remove(); 5457 } 5458 } 5459 // Give priority to updated system apps. 5460 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5461 PackageParser.Package pkg = it.next(); 5462 if (pkg.isUpdatedSystemApp()) { 5463 if (DEBUG_DEXOPT) { 5464 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5465 } 5466 sortedPkgs.add(pkg); 5467 it.remove(); 5468 } 5469 } 5470 // Give priority to apps that listen for boot complete. 5471 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5472 pkgNames = getPackageNamesForIntent(intent); 5473 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5474 PackageParser.Package pkg = it.next(); 5475 if (pkgNames.contains(pkg.packageName)) { 5476 if (DEBUG_DEXOPT) { 5477 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5478 } 5479 sortedPkgs.add(pkg); 5480 it.remove(); 5481 } 5482 } 5483 // Filter out packages that aren't recently used. 5484 filterRecentlyUsedApps(pkgs); 5485 // Add all remaining apps. 5486 for (PackageParser.Package pkg : pkgs) { 5487 if (DEBUG_DEXOPT) { 5488 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5489 } 5490 sortedPkgs.add(pkg); 5491 } 5492 5493 // If we want to be lazy, filter everything that wasn't recently used. 5494 if (mLazyDexOpt) { 5495 filterRecentlyUsedApps(sortedPkgs); 5496 } 5497 5498 int i = 0; 5499 int total = sortedPkgs.size(); 5500 File dataDir = Environment.getDataDirectory(); 5501 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5502 if (lowThreshold == 0) { 5503 throw new IllegalStateException("Invalid low memory threshold"); 5504 } 5505 for (PackageParser.Package pkg : sortedPkgs) { 5506 long usableSpace = dataDir.getUsableSpace(); 5507 if (usableSpace < lowThreshold) { 5508 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5509 break; 5510 } 5511 performBootDexOpt(pkg, ++i, total); 5512 } 5513 } 5514 } 5515 5516 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5517 // Filter out packages that aren't recently used. 5518 // 5519 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5520 // should do a full dexopt. 5521 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5522 int total = pkgs.size(); 5523 int skipped = 0; 5524 long now = System.currentTimeMillis(); 5525 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5526 PackageParser.Package pkg = i.next(); 5527 long then = pkg.mLastPackageUsageTimeInMills; 5528 if (then + mDexOptLRUThresholdInMills < now) { 5529 if (DEBUG_DEXOPT) { 5530 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5531 ((then == 0) ? "never" : new Date(then))); 5532 } 5533 i.remove(); 5534 skipped++; 5535 } 5536 } 5537 if (DEBUG_DEXOPT) { 5538 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5539 } 5540 } 5541 } 5542 5543 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5544 List<ResolveInfo> ris = null; 5545 try { 5546 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5547 intent, null, 0, UserHandle.USER_OWNER); 5548 } catch (RemoteException e) { 5549 } 5550 ArraySet<String> pkgNames = new ArraySet<String>(); 5551 if (ris != null) { 5552 for (ResolveInfo ri : ris) { 5553 pkgNames.add(ri.activityInfo.packageName); 5554 } 5555 } 5556 return pkgNames; 5557 } 5558 5559 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5560 if (DEBUG_DEXOPT) { 5561 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5562 } 5563 if (!isFirstBoot()) { 5564 try { 5565 ActivityManagerNative.getDefault().showBootMessage( 5566 mContext.getResources().getString(R.string.android_upgrading_apk, 5567 curr, total), true); 5568 } catch (RemoteException e) { 5569 } 5570 } 5571 PackageParser.Package p = pkg; 5572 synchronized (mInstallLock) { 5573 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5574 false /* force dex */, false /* defer */, true /* include dependencies */); 5575 } 5576 } 5577 5578 @Override 5579 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5580 return performDexOpt(packageName, instructionSet, false); 5581 } 5582 5583 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5584 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5585 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5586 if (!dexopt && !updateUsage) { 5587 // We aren't going to dexopt or update usage, so bail early. 5588 return false; 5589 } 5590 PackageParser.Package p; 5591 final String targetInstructionSet; 5592 synchronized (mPackages) { 5593 p = mPackages.get(packageName); 5594 if (p == null) { 5595 return false; 5596 } 5597 if (updateUsage) { 5598 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5599 } 5600 mPackageUsage.write(false); 5601 if (!dexopt) { 5602 // We aren't going to dexopt, so bail early. 5603 return false; 5604 } 5605 5606 targetInstructionSet = instructionSet != null ? instructionSet : 5607 getPrimaryInstructionSet(p.applicationInfo); 5608 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5609 return false; 5610 } 5611 } 5612 5613 synchronized (mInstallLock) { 5614 final String[] instructionSets = new String[] { targetInstructionSet }; 5615 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5616 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5617 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5618 } 5619 } 5620 5621 public ArraySet<String> getPackagesThatNeedDexOpt() { 5622 ArraySet<String> pkgs = null; 5623 synchronized (mPackages) { 5624 for (PackageParser.Package p : mPackages.values()) { 5625 if (DEBUG_DEXOPT) { 5626 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5627 } 5628 if (!p.mDexOptPerformed.isEmpty()) { 5629 continue; 5630 } 5631 if (pkgs == null) { 5632 pkgs = new ArraySet<String>(); 5633 } 5634 pkgs.add(p.packageName); 5635 } 5636 } 5637 return pkgs; 5638 } 5639 5640 public void shutdown() { 5641 mPackageUsage.write(true); 5642 } 5643 5644 @Override 5645 public void forceDexOpt(String packageName) { 5646 enforceSystemOrRoot("forceDexOpt"); 5647 5648 PackageParser.Package pkg; 5649 synchronized (mPackages) { 5650 pkg = mPackages.get(packageName); 5651 if (pkg == null) { 5652 throw new IllegalArgumentException("Missing package: " + packageName); 5653 } 5654 } 5655 5656 synchronized (mInstallLock) { 5657 final String[] instructionSets = new String[] { 5658 getPrimaryInstructionSet(pkg.applicationInfo) }; 5659 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5660 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5661 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5662 throw new IllegalStateException("Failed to dexopt: " + res); 5663 } 5664 } 5665 } 5666 5667 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5668 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5669 Slog.w(TAG, "Unable to update from " + oldPkg.name 5670 + " to " + newPkg.packageName 5671 + ": old package not in system partition"); 5672 return false; 5673 } else if (mPackages.get(oldPkg.name) != null) { 5674 Slog.w(TAG, "Unable to update from " + oldPkg.name 5675 + " to " + newPkg.packageName 5676 + ": old package still exists"); 5677 return false; 5678 } 5679 return true; 5680 } 5681 5682 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5683 int[] users = sUserManager.getUserIds(); 5684 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5685 if (res < 0) { 5686 return res; 5687 } 5688 for (int user : users) { 5689 if (user != 0) { 5690 res = mInstaller.createUserData(volumeUuid, packageName, 5691 UserHandle.getUid(user, uid), user, seinfo); 5692 if (res < 0) { 5693 return res; 5694 } 5695 } 5696 } 5697 return res; 5698 } 5699 5700 private int removeDataDirsLI(String volumeUuid, String packageName) { 5701 int[] users = sUserManager.getUserIds(); 5702 int res = 0; 5703 for (int user : users) { 5704 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5705 if (resInner < 0) { 5706 res = resInner; 5707 } 5708 } 5709 5710 return res; 5711 } 5712 5713 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5714 int[] users = sUserManager.getUserIds(); 5715 int res = 0; 5716 for (int user : users) { 5717 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5718 if (resInner < 0) { 5719 res = resInner; 5720 } 5721 } 5722 return res; 5723 } 5724 5725 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5726 PackageParser.Package changingLib) { 5727 if (file.path != null) { 5728 usesLibraryFiles.add(file.path); 5729 return; 5730 } 5731 PackageParser.Package p = mPackages.get(file.apk); 5732 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5733 // If we are doing this while in the middle of updating a library apk, 5734 // then we need to make sure to use that new apk for determining the 5735 // dependencies here. (We haven't yet finished committing the new apk 5736 // to the package manager state.) 5737 if (p == null || p.packageName.equals(changingLib.packageName)) { 5738 p = changingLib; 5739 } 5740 } 5741 if (p != null) { 5742 usesLibraryFiles.addAll(p.getAllCodePaths()); 5743 } 5744 } 5745 5746 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5747 PackageParser.Package changingLib) throws PackageManagerException { 5748 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5749 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5750 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5751 for (int i=0; i<N; i++) { 5752 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5753 if (file == null) { 5754 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5755 "Package " + pkg.packageName + " requires unavailable shared library " 5756 + pkg.usesLibraries.get(i) + "; failing!"); 5757 } 5758 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5759 } 5760 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5761 for (int i=0; i<N; i++) { 5762 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5763 if (file == null) { 5764 Slog.w(TAG, "Package " + pkg.packageName 5765 + " desires unavailable shared library " 5766 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5767 } else { 5768 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5769 } 5770 } 5771 N = usesLibraryFiles.size(); 5772 if (N > 0) { 5773 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5774 } else { 5775 pkg.usesLibraryFiles = null; 5776 } 5777 } 5778 } 5779 5780 private static boolean hasString(List<String> list, List<String> which) { 5781 if (list == null) { 5782 return false; 5783 } 5784 for (int i=list.size()-1; i>=0; i--) { 5785 for (int j=which.size()-1; j>=0; j--) { 5786 if (which.get(j).equals(list.get(i))) { 5787 return true; 5788 } 5789 } 5790 } 5791 return false; 5792 } 5793 5794 private void updateAllSharedLibrariesLPw() { 5795 for (PackageParser.Package pkg : mPackages.values()) { 5796 try { 5797 updateSharedLibrariesLPw(pkg, null); 5798 } catch (PackageManagerException e) { 5799 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5800 } 5801 } 5802 } 5803 5804 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5805 PackageParser.Package changingPkg) { 5806 ArrayList<PackageParser.Package> res = null; 5807 for (PackageParser.Package pkg : mPackages.values()) { 5808 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5809 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5810 if (res == null) { 5811 res = new ArrayList<PackageParser.Package>(); 5812 } 5813 res.add(pkg); 5814 try { 5815 updateSharedLibrariesLPw(pkg, changingPkg); 5816 } catch (PackageManagerException e) { 5817 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5818 } 5819 } 5820 } 5821 return res; 5822 } 5823 5824 /** 5825 * Derive the value of the {@code cpuAbiOverride} based on the provided 5826 * value and an optional stored value from the package settings. 5827 */ 5828 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5829 String cpuAbiOverride = null; 5830 5831 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5832 cpuAbiOverride = null; 5833 } else if (abiOverride != null) { 5834 cpuAbiOverride = abiOverride; 5835 } else if (settings != null) { 5836 cpuAbiOverride = settings.cpuAbiOverrideString; 5837 } 5838 5839 return cpuAbiOverride; 5840 } 5841 5842 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5843 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5844 boolean success = false; 5845 try { 5846 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5847 currentTime, user); 5848 success = true; 5849 return res; 5850 } finally { 5851 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5852 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5853 } 5854 } 5855 } 5856 5857 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5858 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5859 final File scanFile = new File(pkg.codePath); 5860 if (pkg.applicationInfo.getCodePath() == null || 5861 pkg.applicationInfo.getResourcePath() == null) { 5862 // Bail out. The resource and code paths haven't been set. 5863 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5864 "Code and resource paths haven't been set correctly"); 5865 } 5866 5867 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5868 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5869 } else { 5870 // Only allow system apps to be flagged as core apps. 5871 pkg.coreApp = false; 5872 } 5873 5874 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5875 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5876 } 5877 5878 if (mCustomResolverComponentName != null && 5879 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5880 setUpCustomResolverActivity(pkg); 5881 } 5882 5883 if (pkg.packageName.equals("android")) { 5884 synchronized (mPackages) { 5885 if (mAndroidApplication != null) { 5886 Slog.w(TAG, "*************************************************"); 5887 Slog.w(TAG, "Core android package being redefined. Skipping."); 5888 Slog.w(TAG, " file=" + scanFile); 5889 Slog.w(TAG, "*************************************************"); 5890 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5891 "Core android package being redefined. Skipping."); 5892 } 5893 5894 // Set up information for our fall-back user intent resolution activity. 5895 mPlatformPackage = pkg; 5896 pkg.mVersionCode = mSdkVersion; 5897 mAndroidApplication = pkg.applicationInfo; 5898 5899 if (!mResolverReplaced) { 5900 mResolveActivity.applicationInfo = mAndroidApplication; 5901 mResolveActivity.name = ResolverActivity.class.getName(); 5902 mResolveActivity.packageName = mAndroidApplication.packageName; 5903 mResolveActivity.processName = "system:ui"; 5904 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5905 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5906 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5907 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5908 mResolveActivity.exported = true; 5909 mResolveActivity.enabled = true; 5910 mResolveInfo.activityInfo = mResolveActivity; 5911 mResolveInfo.priority = 0; 5912 mResolveInfo.preferredOrder = 0; 5913 mResolveInfo.match = 0; 5914 mResolveComponentName = new ComponentName( 5915 mAndroidApplication.packageName, mResolveActivity.name); 5916 } 5917 } 5918 } 5919 5920 if (DEBUG_PACKAGE_SCANNING) { 5921 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5922 Log.d(TAG, "Scanning package " + pkg.packageName); 5923 } 5924 5925 if (mPackages.containsKey(pkg.packageName) 5926 || mSharedLibraries.containsKey(pkg.packageName)) { 5927 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5928 "Application package " + pkg.packageName 5929 + " already installed. Skipping duplicate."); 5930 } 5931 5932 // If we're only installing presumed-existing packages, require that the 5933 // scanned APK is both already known and at the path previously established 5934 // for it. Previously unknown packages we pick up normally, but if we have an 5935 // a priori expectation about this package's install presence, enforce it. 5936 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5937 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5938 if (known != null) { 5939 if (DEBUG_PACKAGE_SCANNING) { 5940 Log.d(TAG, "Examining " + pkg.codePath 5941 + " and requiring known paths " + known.codePathString 5942 + " & " + known.resourcePathString); 5943 } 5944 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5945 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5946 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5947 "Application package " + pkg.packageName 5948 + " found at " + pkg.applicationInfo.getCodePath() 5949 + " but expected at " + known.codePathString + "; ignoring."); 5950 } 5951 } 5952 } 5953 5954 // Initialize package source and resource directories 5955 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5956 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5957 5958 SharedUserSetting suid = null; 5959 PackageSetting pkgSetting = null; 5960 5961 if (!isSystemApp(pkg)) { 5962 // Only system apps can use these features. 5963 pkg.mOriginalPackages = null; 5964 pkg.mRealPackage = null; 5965 pkg.mAdoptPermissions = null; 5966 } 5967 5968 // writer 5969 synchronized (mPackages) { 5970 if (pkg.mSharedUserId != null) { 5971 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5972 if (suid == null) { 5973 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5974 "Creating application package " + pkg.packageName 5975 + " for shared user failed"); 5976 } 5977 if (DEBUG_PACKAGE_SCANNING) { 5978 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5979 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5980 + "): packages=" + suid.packages); 5981 } 5982 } 5983 5984 // Check if we are renaming from an original package name. 5985 PackageSetting origPackage = null; 5986 String realName = null; 5987 if (pkg.mOriginalPackages != null) { 5988 // This package may need to be renamed to a previously 5989 // installed name. Let's check on that... 5990 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5991 if (pkg.mOriginalPackages.contains(renamed)) { 5992 // This package had originally been installed as the 5993 // original name, and we have already taken care of 5994 // transitioning to the new one. Just update the new 5995 // one to continue using the old name. 5996 realName = pkg.mRealPackage; 5997 if (!pkg.packageName.equals(renamed)) { 5998 // Callers into this function may have already taken 5999 // care of renaming the package; only do it here if 6000 // it is not already done. 6001 pkg.setPackageName(renamed); 6002 } 6003 6004 } else { 6005 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6006 if ((origPackage = mSettings.peekPackageLPr( 6007 pkg.mOriginalPackages.get(i))) != null) { 6008 // We do have the package already installed under its 6009 // original name... should we use it? 6010 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6011 // New package is not compatible with original. 6012 origPackage = null; 6013 continue; 6014 } else if (origPackage.sharedUser != null) { 6015 // Make sure uid is compatible between packages. 6016 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6017 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6018 + " to " + pkg.packageName + ": old uid " 6019 + origPackage.sharedUser.name 6020 + " differs from " + pkg.mSharedUserId); 6021 origPackage = null; 6022 continue; 6023 } 6024 } else { 6025 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6026 + pkg.packageName + " to old name " + origPackage.name); 6027 } 6028 break; 6029 } 6030 } 6031 } 6032 } 6033 6034 if (mTransferedPackages.contains(pkg.packageName)) { 6035 Slog.w(TAG, "Package " + pkg.packageName 6036 + " was transferred to another, but its .apk remains"); 6037 } 6038 6039 // Just create the setting, don't add it yet. For already existing packages 6040 // the PkgSetting exists already and doesn't have to be created. 6041 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6042 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6043 pkg.applicationInfo.primaryCpuAbi, 6044 pkg.applicationInfo.secondaryCpuAbi, 6045 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6046 user, false); 6047 if (pkgSetting == null) { 6048 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6049 "Creating application package " + pkg.packageName + " failed"); 6050 } 6051 6052 if (pkgSetting.origPackage != null) { 6053 // If we are first transitioning from an original package, 6054 // fix up the new package's name now. We need to do this after 6055 // looking up the package under its new name, so getPackageLP 6056 // can take care of fiddling things correctly. 6057 pkg.setPackageName(origPackage.name); 6058 6059 // File a report about this. 6060 String msg = "New package " + pkgSetting.realName 6061 + " renamed to replace old package " + pkgSetting.name; 6062 reportSettingsProblem(Log.WARN, msg); 6063 6064 // Make a note of it. 6065 mTransferedPackages.add(origPackage.name); 6066 6067 // No longer need to retain this. 6068 pkgSetting.origPackage = null; 6069 } 6070 6071 if (realName != null) { 6072 // Make a note of it. 6073 mTransferedPackages.add(pkg.packageName); 6074 } 6075 6076 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6077 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6078 } 6079 6080 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6081 // Check all shared libraries and map to their actual file path. 6082 // We only do this here for apps not on a system dir, because those 6083 // are the only ones that can fail an install due to this. We 6084 // will take care of the system apps by updating all of their 6085 // library paths after the scan is done. 6086 updateSharedLibrariesLPw(pkg, null); 6087 } 6088 6089 if (mFoundPolicyFile) { 6090 SELinuxMMAC.assignSeinfoValue(pkg); 6091 } 6092 6093 pkg.applicationInfo.uid = pkgSetting.appId; 6094 pkg.mExtras = pkgSetting; 6095 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 6096 try { 6097 verifySignaturesLP(pkgSetting, pkg); 6098 // We just determined the app is signed correctly, so bring 6099 // over the latest parsed certs. 6100 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6101 } catch (PackageManagerException e) { 6102 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6103 throw e; 6104 } 6105 // The signature has changed, but this package is in the system 6106 // image... let's recover! 6107 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6108 // However... if this package is part of a shared user, but it 6109 // doesn't match the signature of the shared user, let's fail. 6110 // What this means is that you can't change the signatures 6111 // associated with an overall shared user, which doesn't seem all 6112 // that unreasonable. 6113 if (pkgSetting.sharedUser != null) { 6114 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6115 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6116 throw new PackageManagerException( 6117 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6118 "Signature mismatch for shared user : " 6119 + pkgSetting.sharedUser); 6120 } 6121 } 6122 // File a report about this. 6123 String msg = "System package " + pkg.packageName 6124 + " signature changed; retaining data."; 6125 reportSettingsProblem(Log.WARN, msg); 6126 } 6127 } else { 6128 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6129 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6130 + pkg.packageName + " upgrade keys do not match the " 6131 + "previously installed version"); 6132 } else { 6133 // We just determined the app is signed correctly, so bring 6134 // over the latest parsed certs. 6135 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6136 } 6137 } 6138 // Verify that this new package doesn't have any content providers 6139 // that conflict with existing packages. Only do this if the 6140 // package isn't already installed, since we don't want to break 6141 // things that are installed. 6142 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6143 final int N = pkg.providers.size(); 6144 int i; 6145 for (i=0; i<N; i++) { 6146 PackageParser.Provider p = pkg.providers.get(i); 6147 if (p.info.authority != null) { 6148 String names[] = p.info.authority.split(";"); 6149 for (int j = 0; j < names.length; j++) { 6150 if (mProvidersByAuthority.containsKey(names[j])) { 6151 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6152 final String otherPackageName = 6153 ((other != null && other.getComponentName() != null) ? 6154 other.getComponentName().getPackageName() : "?"); 6155 throw new PackageManagerException( 6156 INSTALL_FAILED_CONFLICTING_PROVIDER, 6157 "Can't install because provider name " + names[j] 6158 + " (in package " + pkg.applicationInfo.packageName 6159 + ") is already used by " + otherPackageName); 6160 } 6161 } 6162 } 6163 } 6164 } 6165 6166 if (pkg.mAdoptPermissions != null) { 6167 // This package wants to adopt ownership of permissions from 6168 // another package. 6169 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6170 final String origName = pkg.mAdoptPermissions.get(i); 6171 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6172 if (orig != null) { 6173 if (verifyPackageUpdateLPr(orig, pkg)) { 6174 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6175 + pkg.packageName); 6176 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6177 } 6178 } 6179 } 6180 } 6181 } 6182 6183 final String pkgName = pkg.packageName; 6184 6185 final long scanFileTime = scanFile.lastModified(); 6186 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6187 pkg.applicationInfo.processName = fixProcessName( 6188 pkg.applicationInfo.packageName, 6189 pkg.applicationInfo.processName, 6190 pkg.applicationInfo.uid); 6191 6192 File dataPath; 6193 if (mPlatformPackage == pkg) { 6194 // The system package is special. 6195 dataPath = new File(Environment.getDataDirectory(), "system"); 6196 6197 pkg.applicationInfo.dataDir = dataPath.getPath(); 6198 6199 } else { 6200 // This is a normal package, need to make its data directory. 6201 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6202 UserHandle.USER_OWNER); 6203 6204 boolean uidError = false; 6205 if (dataPath.exists()) { 6206 int currentUid = 0; 6207 try { 6208 StructStat stat = Os.stat(dataPath.getPath()); 6209 currentUid = stat.st_uid; 6210 } catch (ErrnoException e) { 6211 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6212 } 6213 6214 // If we have mismatched owners for the data path, we have a problem. 6215 if (currentUid != pkg.applicationInfo.uid) { 6216 boolean recovered = false; 6217 if (currentUid == 0) { 6218 // The directory somehow became owned by root. Wow. 6219 // This is probably because the system was stopped while 6220 // installd was in the middle of messing with its libs 6221 // directory. Ask installd to fix that. 6222 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6223 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6224 if (ret >= 0) { 6225 recovered = true; 6226 String msg = "Package " + pkg.packageName 6227 + " unexpectedly changed to uid 0; recovered to " + 6228 + pkg.applicationInfo.uid; 6229 reportSettingsProblem(Log.WARN, msg); 6230 } 6231 } 6232 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6233 || (scanFlags&SCAN_BOOTING) != 0)) { 6234 // If this is a system app, we can at least delete its 6235 // current data so the application will still work. 6236 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6237 if (ret >= 0) { 6238 // TODO: Kill the processes first 6239 // Old data gone! 6240 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6241 ? "System package " : "Third party package "; 6242 String msg = prefix + pkg.packageName 6243 + " has changed from uid: " 6244 + currentUid + " to " 6245 + pkg.applicationInfo.uid + "; old data erased"; 6246 reportSettingsProblem(Log.WARN, msg); 6247 recovered = true; 6248 6249 // And now re-install the app. 6250 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6251 pkg.applicationInfo.seinfo); 6252 if (ret == -1) { 6253 // Ack should not happen! 6254 msg = prefix + pkg.packageName 6255 + " could not have data directory re-created after delete."; 6256 reportSettingsProblem(Log.WARN, msg); 6257 throw new PackageManagerException( 6258 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6259 } 6260 } 6261 if (!recovered) { 6262 mHasSystemUidErrors = true; 6263 } 6264 } else if (!recovered) { 6265 // If we allow this install to proceed, we will be broken. 6266 // Abort, abort! 6267 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6268 "scanPackageLI"); 6269 } 6270 if (!recovered) { 6271 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6272 + pkg.applicationInfo.uid + "/fs_" 6273 + currentUid; 6274 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6275 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6276 String msg = "Package " + pkg.packageName 6277 + " has mismatched uid: " 6278 + currentUid + " on disk, " 6279 + pkg.applicationInfo.uid + " in settings"; 6280 // writer 6281 synchronized (mPackages) { 6282 mSettings.mReadMessages.append(msg); 6283 mSettings.mReadMessages.append('\n'); 6284 uidError = true; 6285 if (!pkgSetting.uidError) { 6286 reportSettingsProblem(Log.ERROR, msg); 6287 } 6288 } 6289 } 6290 } 6291 pkg.applicationInfo.dataDir = dataPath.getPath(); 6292 if (mShouldRestoreconData) { 6293 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6294 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6295 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6296 } 6297 } else { 6298 if (DEBUG_PACKAGE_SCANNING) { 6299 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6300 Log.v(TAG, "Want this data dir: " + dataPath); 6301 } 6302 //invoke installer to do the actual installation 6303 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6304 pkg.applicationInfo.seinfo); 6305 if (ret < 0) { 6306 // Error from installer 6307 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6308 "Unable to create data dirs [errorCode=" + ret + "]"); 6309 } 6310 6311 if (dataPath.exists()) { 6312 pkg.applicationInfo.dataDir = dataPath.getPath(); 6313 } else { 6314 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6315 pkg.applicationInfo.dataDir = null; 6316 } 6317 } 6318 6319 pkgSetting.uidError = uidError; 6320 } 6321 6322 final String path = scanFile.getPath(); 6323 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6324 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6325 setBundledAppAbisAndRoots(pkg, pkgSetting); 6326 6327 // If we haven't found any native libraries for the app, check if it has 6328 // renderscript code. We'll need to force the app to 32 bit if it has 6329 // renderscript bitcode. 6330 if (pkg.applicationInfo.primaryCpuAbi == null 6331 && pkg.applicationInfo.secondaryCpuAbi == null 6332 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6333 NativeLibraryHelper.Handle handle = null; 6334 try { 6335 handle = NativeLibraryHelper.Handle.create(scanFile); 6336 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6337 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6338 } 6339 } catch (IOException ioe) { 6340 Slog.w(TAG, "Error scanning system app : " + ioe); 6341 } finally { 6342 IoUtils.closeQuietly(handle); 6343 } 6344 } 6345 6346 setNativeLibraryPaths(pkg); 6347 } else { 6348 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6349 deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6350 } else { 6351 if ((scanFlags & SCAN_MOVE) != 0) { 6352 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6353 // but we already have this packages package info in the PackageSetting. We just 6354 // use that and derive the native library path based on the new codepath. 6355 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6356 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6357 } 6358 6359 // Set native library paths again. For moves, the path will be updated based on the 6360 // ABIs we've determined above. For non-moves, the path will be updated based on the 6361 // ABIs we determined during compilation, but the path will depend on the final 6362 // package path (after the rename away from the stage path). 6363 setNativeLibraryPaths(pkg); 6364 } 6365 6366 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6367 final int[] userIds = sUserManager.getUserIds(); 6368 synchronized (mInstallLock) { 6369 // Create a native library symlink only if we have native libraries 6370 // and if the native libraries are 32 bit libraries. We do not provide 6371 // this symlink for 64 bit libraries. 6372 if (pkg.applicationInfo.primaryCpuAbi != null && 6373 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6374 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6375 for (int userId : userIds) { 6376 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6377 nativeLibPath, userId) < 0) { 6378 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6379 "Failed linking native library dir (user=" + userId + ")"); 6380 } 6381 } 6382 } 6383 } 6384 } 6385 6386 // This is a special case for the "system" package, where the ABI is 6387 // dictated by the zygote configuration (and init.rc). We should keep track 6388 // of this ABI so that we can deal with "normal" applications that run under 6389 // the same UID correctly. 6390 if (mPlatformPackage == pkg) { 6391 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6392 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6393 } 6394 6395 // If there's a mismatch between the abi-override in the package setting 6396 // and the abiOverride specified for the install. Warn about this because we 6397 // would've already compiled the app without taking the package setting into 6398 // account. 6399 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6400 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6401 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6402 " for package: " + pkg.packageName); 6403 } 6404 } 6405 6406 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6407 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6408 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6409 6410 // Copy the derived override back to the parsed package, so that we can 6411 // update the package settings accordingly. 6412 pkg.cpuAbiOverride = cpuAbiOverride; 6413 6414 if (DEBUG_ABI_SELECTION) { 6415 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6416 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6417 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6418 } 6419 6420 // Push the derived path down into PackageSettings so we know what to 6421 // clean up at uninstall time. 6422 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6423 6424 if (DEBUG_ABI_SELECTION) { 6425 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6426 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6427 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6428 } 6429 6430 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6431 // We don't do this here during boot because we can do it all 6432 // at once after scanning all existing packages. 6433 // 6434 // We also do this *before* we perform dexopt on this package, so that 6435 // we can avoid redundant dexopts, and also to make sure we've got the 6436 // code and package path correct. 6437 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6438 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6439 } 6440 6441 if ((scanFlags & SCAN_NO_DEX) == 0) { 6442 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6443 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6444 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6445 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6446 } 6447 } 6448 if (mFactoryTest && pkg.requestedPermissions.contains( 6449 android.Manifest.permission.FACTORY_TEST)) { 6450 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6451 } 6452 6453 ArrayList<PackageParser.Package> clientLibPkgs = null; 6454 6455 // writer 6456 synchronized (mPackages) { 6457 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6458 // Only system apps can add new shared libraries. 6459 if (pkg.libraryNames != null) { 6460 for (int i=0; i<pkg.libraryNames.size(); i++) { 6461 String name = pkg.libraryNames.get(i); 6462 boolean allowed = false; 6463 if (pkg.isUpdatedSystemApp()) { 6464 // New library entries can only be added through the 6465 // system image. This is important to get rid of a lot 6466 // of nasty edge cases: for example if we allowed a non- 6467 // system update of the app to add a library, then uninstalling 6468 // the update would make the library go away, and assumptions 6469 // we made such as through app install filtering would now 6470 // have allowed apps on the device which aren't compatible 6471 // with it. Better to just have the restriction here, be 6472 // conservative, and create many fewer cases that can negatively 6473 // impact the user experience. 6474 final PackageSetting sysPs = mSettings 6475 .getDisabledSystemPkgLPr(pkg.packageName); 6476 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6477 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6478 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6479 allowed = true; 6480 allowed = true; 6481 break; 6482 } 6483 } 6484 } 6485 } else { 6486 allowed = true; 6487 } 6488 if (allowed) { 6489 if (!mSharedLibraries.containsKey(name)) { 6490 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6491 } else if (!name.equals(pkg.packageName)) { 6492 Slog.w(TAG, "Package " + pkg.packageName + " library " 6493 + name + " already exists; skipping"); 6494 } 6495 } else { 6496 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6497 + name + " that is not declared on system image; skipping"); 6498 } 6499 } 6500 if ((scanFlags&SCAN_BOOTING) == 0) { 6501 // If we are not booting, we need to update any applications 6502 // that are clients of our shared library. If we are booting, 6503 // this will all be done once the scan is complete. 6504 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6505 } 6506 } 6507 } 6508 } 6509 6510 // We also need to dexopt any apps that are dependent on this library. Note that 6511 // if these fail, we should abort the install since installing the library will 6512 // result in some apps being broken. 6513 if (clientLibPkgs != null) { 6514 if ((scanFlags & SCAN_NO_DEX) == 0) { 6515 for (int i = 0; i < clientLibPkgs.size(); i++) { 6516 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6517 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6518 null /* instruction sets */, forceDex, 6519 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6520 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6521 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6522 "scanPackageLI failed to dexopt clientLibPkgs"); 6523 } 6524 } 6525 } 6526 } 6527 6528 // Also need to kill any apps that are dependent on the library. 6529 if (clientLibPkgs != null) { 6530 for (int i=0; i<clientLibPkgs.size(); i++) { 6531 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6532 killApplication(clientPkg.applicationInfo.packageName, 6533 clientPkg.applicationInfo.uid, "update lib"); 6534 } 6535 } 6536 6537 // writer 6538 synchronized (mPackages) { 6539 // We don't expect installation to fail beyond this point 6540 6541 // Add the new setting to mSettings 6542 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6543 // Add the new setting to mPackages 6544 mPackages.put(pkg.applicationInfo.packageName, pkg); 6545 // Make sure we don't accidentally delete its data. 6546 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6547 while (iter.hasNext()) { 6548 PackageCleanItem item = iter.next(); 6549 if (pkgName.equals(item.packageName)) { 6550 iter.remove(); 6551 } 6552 } 6553 6554 // Take care of first install / last update times. 6555 if (currentTime != 0) { 6556 if (pkgSetting.firstInstallTime == 0) { 6557 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6558 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6559 pkgSetting.lastUpdateTime = currentTime; 6560 } 6561 } else if (pkgSetting.firstInstallTime == 0) { 6562 // We need *something*. Take time time stamp of the file. 6563 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6564 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6565 if (scanFileTime != pkgSetting.timeStamp) { 6566 // A package on the system image has changed; consider this 6567 // to be an update. 6568 pkgSetting.lastUpdateTime = scanFileTime; 6569 } 6570 } 6571 6572 // Add the package's KeySets to the global KeySetManagerService 6573 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6574 try { 6575 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6576 if (pkg.mKeySetMapping != null) { 6577 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6578 if (pkg.mUpgradeKeySets != null) { 6579 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6580 } 6581 } 6582 } catch (NullPointerException e) { 6583 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6584 } catch (IllegalArgumentException e) { 6585 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6586 } 6587 6588 int N = pkg.providers.size(); 6589 StringBuilder r = null; 6590 int i; 6591 for (i=0; i<N; i++) { 6592 PackageParser.Provider p = pkg.providers.get(i); 6593 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6594 p.info.processName, pkg.applicationInfo.uid); 6595 mProviders.addProvider(p); 6596 p.syncable = p.info.isSyncable; 6597 if (p.info.authority != null) { 6598 String names[] = p.info.authority.split(";"); 6599 p.info.authority = null; 6600 for (int j = 0; j < names.length; j++) { 6601 if (j == 1 && p.syncable) { 6602 // We only want the first authority for a provider to possibly be 6603 // syncable, so if we already added this provider using a different 6604 // authority clear the syncable flag. We copy the provider before 6605 // changing it because the mProviders object contains a reference 6606 // to a provider that we don't want to change. 6607 // Only do this for the second authority since the resulting provider 6608 // object can be the same for all future authorities for this provider. 6609 p = new PackageParser.Provider(p); 6610 p.syncable = false; 6611 } 6612 if (!mProvidersByAuthority.containsKey(names[j])) { 6613 mProvidersByAuthority.put(names[j], p); 6614 if (p.info.authority == null) { 6615 p.info.authority = names[j]; 6616 } else { 6617 p.info.authority = p.info.authority + ";" + names[j]; 6618 } 6619 if (DEBUG_PACKAGE_SCANNING) { 6620 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6621 Log.d(TAG, "Registered content provider: " + names[j] 6622 + ", className = " + p.info.name + ", isSyncable = " 6623 + p.info.isSyncable); 6624 } 6625 } else { 6626 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6627 Slog.w(TAG, "Skipping provider name " + names[j] + 6628 " (in package " + pkg.applicationInfo.packageName + 6629 "): name already used by " 6630 + ((other != null && other.getComponentName() != null) 6631 ? other.getComponentName().getPackageName() : "?")); 6632 } 6633 } 6634 } 6635 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6636 if (r == null) { 6637 r = new StringBuilder(256); 6638 } else { 6639 r.append(' '); 6640 } 6641 r.append(p.info.name); 6642 } 6643 } 6644 if (r != null) { 6645 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6646 } 6647 6648 N = pkg.services.size(); 6649 r = null; 6650 for (i=0; i<N; i++) { 6651 PackageParser.Service s = pkg.services.get(i); 6652 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6653 s.info.processName, pkg.applicationInfo.uid); 6654 mServices.addService(s); 6655 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6656 if (r == null) { 6657 r = new StringBuilder(256); 6658 } else { 6659 r.append(' '); 6660 } 6661 r.append(s.info.name); 6662 } 6663 } 6664 if (r != null) { 6665 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6666 } 6667 6668 N = pkg.receivers.size(); 6669 r = null; 6670 for (i=0; i<N; i++) { 6671 PackageParser.Activity a = pkg.receivers.get(i); 6672 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6673 a.info.processName, pkg.applicationInfo.uid); 6674 mReceivers.addActivity(a, "receiver"); 6675 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6676 if (r == null) { 6677 r = new StringBuilder(256); 6678 } else { 6679 r.append(' '); 6680 } 6681 r.append(a.info.name); 6682 } 6683 } 6684 if (r != null) { 6685 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6686 } 6687 6688 N = pkg.activities.size(); 6689 r = null; 6690 for (i=0; i<N; i++) { 6691 PackageParser.Activity a = pkg.activities.get(i); 6692 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6693 a.info.processName, pkg.applicationInfo.uid); 6694 mActivities.addActivity(a, "activity"); 6695 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6696 if (r == null) { 6697 r = new StringBuilder(256); 6698 } else { 6699 r.append(' '); 6700 } 6701 r.append(a.info.name); 6702 } 6703 } 6704 if (r != null) { 6705 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6706 } 6707 6708 N = pkg.permissionGroups.size(); 6709 r = null; 6710 for (i=0; i<N; i++) { 6711 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6712 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6713 if (cur == null) { 6714 mPermissionGroups.put(pg.info.name, pg); 6715 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6716 if (r == null) { 6717 r = new StringBuilder(256); 6718 } else { 6719 r.append(' '); 6720 } 6721 r.append(pg.info.name); 6722 } 6723 } else { 6724 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6725 + pg.info.packageName + " ignored: original from " 6726 + cur.info.packageName); 6727 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6728 if (r == null) { 6729 r = new StringBuilder(256); 6730 } else { 6731 r.append(' '); 6732 } 6733 r.append("DUP:"); 6734 r.append(pg.info.name); 6735 } 6736 } 6737 } 6738 if (r != null) { 6739 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6740 } 6741 6742 N = pkg.permissions.size(); 6743 r = null; 6744 for (i=0; i<N; i++) { 6745 PackageParser.Permission p = pkg.permissions.get(i); 6746 6747 // Now that permission groups have a special meaning, we ignore permission 6748 // groups for legacy apps to prevent unexpected behavior. In particular, 6749 // permissions for one app being granted to someone just becuase they happen 6750 // to be in a group defined by another app (before this had no implications). 6751 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6752 p.group = mPermissionGroups.get(p.info.group); 6753 // Warn for a permission in an unknown group. 6754 if (p.info.group != null && p.group == null) { 6755 Slog.w(TAG, "Permission " + p.info.name + " from package " 6756 + p.info.packageName + " in an unknown group " + p.info.group); 6757 } 6758 } 6759 6760 ArrayMap<String, BasePermission> permissionMap = 6761 p.tree ? mSettings.mPermissionTrees 6762 : mSettings.mPermissions; 6763 BasePermission bp = permissionMap.get(p.info.name); 6764 6765 // Allow system apps to redefine non-system permissions 6766 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6767 final boolean currentOwnerIsSystem = (bp.perm != null 6768 && isSystemApp(bp.perm.owner)); 6769 if (isSystemApp(p.owner)) { 6770 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6771 // It's a built-in permission and no owner, take ownership now 6772 bp.packageSetting = pkgSetting; 6773 bp.perm = p; 6774 bp.uid = pkg.applicationInfo.uid; 6775 bp.sourcePackage = p.info.packageName; 6776 } else if (!currentOwnerIsSystem) { 6777 String msg = "New decl " + p.owner + " of permission " 6778 + p.info.name + " is system; overriding " + bp.sourcePackage; 6779 reportSettingsProblem(Log.WARN, msg); 6780 bp = null; 6781 } 6782 } 6783 } 6784 6785 if (bp == null) { 6786 bp = new BasePermission(p.info.name, p.info.packageName, 6787 BasePermission.TYPE_NORMAL); 6788 permissionMap.put(p.info.name, bp); 6789 } 6790 6791 if (bp.perm == null) { 6792 if (bp.sourcePackage == null 6793 || bp.sourcePackage.equals(p.info.packageName)) { 6794 BasePermission tree = findPermissionTreeLP(p.info.name); 6795 if (tree == null 6796 || tree.sourcePackage.equals(p.info.packageName)) { 6797 bp.packageSetting = pkgSetting; 6798 bp.perm = p; 6799 bp.uid = pkg.applicationInfo.uid; 6800 bp.sourcePackage = p.info.packageName; 6801 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6802 if (r == null) { 6803 r = new StringBuilder(256); 6804 } else { 6805 r.append(' '); 6806 } 6807 r.append(p.info.name); 6808 } 6809 } else { 6810 Slog.w(TAG, "Permission " + p.info.name + " from package " 6811 + p.info.packageName + " ignored: base tree " 6812 + tree.name + " is from package " 6813 + tree.sourcePackage); 6814 } 6815 } else { 6816 Slog.w(TAG, "Permission " + p.info.name + " from package " 6817 + p.info.packageName + " ignored: original from " 6818 + bp.sourcePackage); 6819 } 6820 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6821 if (r == null) { 6822 r = new StringBuilder(256); 6823 } else { 6824 r.append(' '); 6825 } 6826 r.append("DUP:"); 6827 r.append(p.info.name); 6828 } 6829 if (bp.perm == p) { 6830 bp.protectionLevel = p.info.protectionLevel; 6831 } 6832 } 6833 6834 if (r != null) { 6835 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6836 } 6837 6838 N = pkg.instrumentation.size(); 6839 r = null; 6840 for (i=0; i<N; i++) { 6841 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6842 a.info.packageName = pkg.applicationInfo.packageName; 6843 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6844 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6845 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6846 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6847 a.info.dataDir = pkg.applicationInfo.dataDir; 6848 6849 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6850 // need other information about the application, like the ABI and what not ? 6851 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6852 mInstrumentation.put(a.getComponentName(), a); 6853 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6854 if (r == null) { 6855 r = new StringBuilder(256); 6856 } else { 6857 r.append(' '); 6858 } 6859 r.append(a.info.name); 6860 } 6861 } 6862 if (r != null) { 6863 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6864 } 6865 6866 if (pkg.protectedBroadcasts != null) { 6867 N = pkg.protectedBroadcasts.size(); 6868 for (i=0; i<N; i++) { 6869 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6870 } 6871 } 6872 6873 pkgSetting.setTimeStamp(scanFileTime); 6874 6875 // Create idmap files for pairs of (packages, overlay packages). 6876 // Note: "android", ie framework-res.apk, is handled by native layers. 6877 if (pkg.mOverlayTarget != null) { 6878 // This is an overlay package. 6879 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6880 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6881 mOverlays.put(pkg.mOverlayTarget, 6882 new ArrayMap<String, PackageParser.Package>()); 6883 } 6884 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6885 map.put(pkg.packageName, pkg); 6886 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6887 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6888 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6889 "scanPackageLI failed to createIdmap"); 6890 } 6891 } 6892 } else if (mOverlays.containsKey(pkg.packageName) && 6893 !pkg.packageName.equals("android")) { 6894 // This is a regular package, with one or more known overlay packages. 6895 createIdmapsForPackageLI(pkg); 6896 } 6897 } 6898 6899 return pkg; 6900 } 6901 6902 /** 6903 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6904 * is derived purely on the basis of the contents of {@code scanFile} and 6905 * {@code cpuAbiOverride}. 6906 * 6907 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6908 */ 6909 public void deriveNonSystemPackageAbi(PackageParser.Package pkg, File scanFile, 6910 String cpuAbiOverride, boolean extractLibs) 6911 throws PackageManagerException { 6912 // TODO: We can probably be smarter about this stuff. For installed apps, 6913 // we can calculate this information at install time once and for all. For 6914 // system apps, we can probably assume that this information doesn't change 6915 // after the first boot scan. As things stand, we do lots of unnecessary work. 6916 6917 // Give ourselves some initial paths; we'll come back for another 6918 // pass once we've determined ABI below. 6919 setNativeLibraryPaths(pkg); 6920 6921 // We would never need to extract libs for forward-locked and external packages, 6922 // since the container service will do it for us. 6923 if (pkg.isForwardLocked() || isExternal(pkg)) { 6924 extractLibs = false; 6925 } 6926 6927 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6928 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6929 6930 NativeLibraryHelper.Handle handle = null; 6931 try { 6932 handle = NativeLibraryHelper.Handle.create(scanFile); 6933 // TODO(multiArch): This can be null for apps that didn't go through the 6934 // usual installation process. We can calculate it again, like we 6935 // do during install time. 6936 // 6937 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6938 // unnecessary. 6939 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6940 6941 // Null out the abis so that they can be recalculated. 6942 pkg.applicationInfo.primaryCpuAbi = null; 6943 pkg.applicationInfo.secondaryCpuAbi = null; 6944 if (isMultiArch(pkg.applicationInfo)) { 6945 // Warn if we've set an abiOverride for multi-lib packages.. 6946 // By definition, we need to copy both 32 and 64 bit libraries for 6947 // such packages. 6948 if (pkg.cpuAbiOverride != null 6949 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6950 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6951 } 6952 6953 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6954 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6955 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6956 if (extractLibs) { 6957 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6958 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6959 useIsaSpecificSubdirs); 6960 } else { 6961 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6962 } 6963 } 6964 6965 maybeThrowExceptionForMultiArchCopy( 6966 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6967 6968 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6969 if (extractLibs) { 6970 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6971 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6972 useIsaSpecificSubdirs); 6973 } else { 6974 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6975 } 6976 } 6977 6978 maybeThrowExceptionForMultiArchCopy( 6979 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6980 6981 if (abi64 >= 0) { 6982 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6983 } 6984 6985 if (abi32 >= 0) { 6986 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6987 if (abi64 >= 0) { 6988 pkg.applicationInfo.secondaryCpuAbi = abi; 6989 } else { 6990 pkg.applicationInfo.primaryCpuAbi = abi; 6991 } 6992 } 6993 } else { 6994 String[] abiList = (cpuAbiOverride != null) ? 6995 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6996 6997 // Enable gross and lame hacks for apps that are built with old 6998 // SDK tools. We must scan their APKs for renderscript bitcode and 6999 // not launch them if it's present. Don't bother checking on devices 7000 // that don't have 64 bit support. 7001 boolean needsRenderScriptOverride = false; 7002 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7003 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7004 abiList = Build.SUPPORTED_32_BIT_ABIS; 7005 needsRenderScriptOverride = true; 7006 } 7007 7008 final int copyRet; 7009 if (extractLibs) { 7010 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7011 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7012 } else { 7013 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7014 } 7015 7016 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7017 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7018 "Error unpackaging native libs for app, errorCode=" + copyRet); 7019 } 7020 7021 if (copyRet >= 0) { 7022 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7023 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7024 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7025 } else if (needsRenderScriptOverride) { 7026 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7027 } 7028 } 7029 } catch (IOException ioe) { 7030 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7031 } finally { 7032 IoUtils.closeQuietly(handle); 7033 } 7034 7035 // Now that we've calculated the ABIs and determined if it's an internal app, 7036 // we will go ahead and populate the nativeLibraryPath. 7037 setNativeLibraryPaths(pkg); 7038 } 7039 7040 /** 7041 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7042 * i.e, so that all packages can be run inside a single process if required. 7043 * 7044 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7045 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7046 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7047 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7048 * updating a package that belongs to a shared user. 7049 * 7050 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7051 * adds unnecessary complexity. 7052 */ 7053 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7054 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7055 String requiredInstructionSet = null; 7056 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7057 requiredInstructionSet = VMRuntime.getInstructionSet( 7058 scannedPackage.applicationInfo.primaryCpuAbi); 7059 } 7060 7061 PackageSetting requirer = null; 7062 for (PackageSetting ps : packagesForUser) { 7063 // If packagesForUser contains scannedPackage, we skip it. This will happen 7064 // when scannedPackage is an update of an existing package. Without this check, 7065 // we will never be able to change the ABI of any package belonging to a shared 7066 // user, even if it's compatible with other packages. 7067 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7068 if (ps.primaryCpuAbiString == null) { 7069 continue; 7070 } 7071 7072 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7073 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7074 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7075 // this but there's not much we can do. 7076 String errorMessage = "Instruction set mismatch, " 7077 + ((requirer == null) ? "[caller]" : requirer) 7078 + " requires " + requiredInstructionSet + " whereas " + ps 7079 + " requires " + instructionSet; 7080 Slog.w(TAG, errorMessage); 7081 } 7082 7083 if (requiredInstructionSet == null) { 7084 requiredInstructionSet = instructionSet; 7085 requirer = ps; 7086 } 7087 } 7088 } 7089 7090 if (requiredInstructionSet != null) { 7091 String adjustedAbi; 7092 if (requirer != null) { 7093 // requirer != null implies that either scannedPackage was null or that scannedPackage 7094 // did not require an ABI, in which case we have to adjust scannedPackage to match 7095 // the ABI of the set (which is the same as requirer's ABI) 7096 adjustedAbi = requirer.primaryCpuAbiString; 7097 if (scannedPackage != null) { 7098 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7099 } 7100 } else { 7101 // requirer == null implies that we're updating all ABIs in the set to 7102 // match scannedPackage. 7103 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7104 } 7105 7106 for (PackageSetting ps : packagesForUser) { 7107 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7108 if (ps.primaryCpuAbiString != null) { 7109 continue; 7110 } 7111 7112 ps.primaryCpuAbiString = adjustedAbi; 7113 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7114 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7115 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7116 7117 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7118 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7119 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7120 ps.primaryCpuAbiString = null; 7121 ps.pkg.applicationInfo.primaryCpuAbi = null; 7122 return; 7123 } else { 7124 mInstaller.rmdex(ps.codePathString, 7125 getDexCodeInstructionSet(getPreferredInstructionSet())); 7126 } 7127 } 7128 } 7129 } 7130 } 7131 } 7132 7133 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7134 synchronized (mPackages) { 7135 mResolverReplaced = true; 7136 // Set up information for custom user intent resolution activity. 7137 mResolveActivity.applicationInfo = pkg.applicationInfo; 7138 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7139 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7140 mResolveActivity.processName = pkg.applicationInfo.packageName; 7141 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7142 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7143 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7144 mResolveActivity.theme = 0; 7145 mResolveActivity.exported = true; 7146 mResolveActivity.enabled = true; 7147 mResolveInfo.activityInfo = mResolveActivity; 7148 mResolveInfo.priority = 0; 7149 mResolveInfo.preferredOrder = 0; 7150 mResolveInfo.match = 0; 7151 mResolveComponentName = mCustomResolverComponentName; 7152 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7153 mResolveComponentName); 7154 } 7155 } 7156 7157 private static String calculateBundledApkRoot(final String codePathString) { 7158 final File codePath = new File(codePathString); 7159 final File codeRoot; 7160 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7161 codeRoot = Environment.getRootDirectory(); 7162 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7163 codeRoot = Environment.getOemDirectory(); 7164 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7165 codeRoot = Environment.getVendorDirectory(); 7166 } else { 7167 // Unrecognized code path; take its top real segment as the apk root: 7168 // e.g. /something/app/blah.apk => /something 7169 try { 7170 File f = codePath.getCanonicalFile(); 7171 File parent = f.getParentFile(); // non-null because codePath is a file 7172 File tmp; 7173 while ((tmp = parent.getParentFile()) != null) { 7174 f = parent; 7175 parent = tmp; 7176 } 7177 codeRoot = f; 7178 Slog.w(TAG, "Unrecognized code path " 7179 + codePath + " - using " + codeRoot); 7180 } catch (IOException e) { 7181 // Can't canonicalize the code path -- shenanigans? 7182 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7183 return Environment.getRootDirectory().getPath(); 7184 } 7185 } 7186 return codeRoot.getPath(); 7187 } 7188 7189 /** 7190 * Derive and set the location of native libraries for the given package, 7191 * which varies depending on where and how the package was installed. 7192 */ 7193 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7194 final ApplicationInfo info = pkg.applicationInfo; 7195 final String codePath = pkg.codePath; 7196 final File codeFile = new File(codePath); 7197 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7198 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7199 7200 info.nativeLibraryRootDir = null; 7201 info.nativeLibraryRootRequiresIsa = false; 7202 info.nativeLibraryDir = null; 7203 info.secondaryNativeLibraryDir = null; 7204 7205 if (isApkFile(codeFile)) { 7206 // Monolithic install 7207 if (bundledApp) { 7208 // If "/system/lib64/apkname" exists, assume that is the per-package 7209 // native library directory to use; otherwise use "/system/lib/apkname". 7210 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7211 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7212 getPrimaryInstructionSet(info)); 7213 7214 // This is a bundled system app so choose the path based on the ABI. 7215 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7216 // is just the default path. 7217 final String apkName = deriveCodePathName(codePath); 7218 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7219 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7220 apkName).getAbsolutePath(); 7221 7222 if (info.secondaryCpuAbi != null) { 7223 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7224 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7225 secondaryLibDir, apkName).getAbsolutePath(); 7226 } 7227 } else if (asecApp) { 7228 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7229 .getAbsolutePath(); 7230 } else { 7231 final String apkName = deriveCodePathName(codePath); 7232 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7233 .getAbsolutePath(); 7234 } 7235 7236 info.nativeLibraryRootRequiresIsa = false; 7237 info.nativeLibraryDir = info.nativeLibraryRootDir; 7238 } else { 7239 // Cluster install 7240 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7241 info.nativeLibraryRootRequiresIsa = true; 7242 7243 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7244 getPrimaryInstructionSet(info)).getAbsolutePath(); 7245 7246 if (info.secondaryCpuAbi != null) { 7247 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7248 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7249 } 7250 } 7251 } 7252 7253 /** 7254 * Calculate the abis and roots for a bundled app. These can uniquely 7255 * be determined from the contents of the system partition, i.e whether 7256 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7257 * of this information, and instead assume that the system was built 7258 * sensibly. 7259 */ 7260 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7261 PackageSetting pkgSetting) { 7262 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7263 7264 // If "/system/lib64/apkname" exists, assume that is the per-package 7265 // native library directory to use; otherwise use "/system/lib/apkname". 7266 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7267 setBundledAppAbi(pkg, apkRoot, apkName); 7268 // pkgSetting might be null during rescan following uninstall of updates 7269 // to a bundled app, so accommodate that possibility. The settings in 7270 // that case will be established later from the parsed package. 7271 // 7272 // If the settings aren't null, sync them up with what we've just derived. 7273 // note that apkRoot isn't stored in the package settings. 7274 if (pkgSetting != null) { 7275 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7276 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7277 } 7278 } 7279 7280 /** 7281 * Deduces the ABI of a bundled app and sets the relevant fields on the 7282 * parsed pkg object. 7283 * 7284 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7285 * under which system libraries are installed. 7286 * @param apkName the name of the installed package. 7287 */ 7288 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7289 final File codeFile = new File(pkg.codePath); 7290 7291 final boolean has64BitLibs; 7292 final boolean has32BitLibs; 7293 if (isApkFile(codeFile)) { 7294 // Monolithic install 7295 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7296 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7297 } else { 7298 // Cluster install 7299 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7300 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7301 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7302 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7303 has64BitLibs = (new File(rootDir, isa)).exists(); 7304 } else { 7305 has64BitLibs = false; 7306 } 7307 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7308 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7309 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7310 has32BitLibs = (new File(rootDir, isa)).exists(); 7311 } else { 7312 has32BitLibs = false; 7313 } 7314 } 7315 7316 if (has64BitLibs && !has32BitLibs) { 7317 // The package has 64 bit libs, but not 32 bit libs. Its primary 7318 // ABI should be 64 bit. We can safely assume here that the bundled 7319 // native libraries correspond to the most preferred ABI in the list. 7320 7321 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7322 pkg.applicationInfo.secondaryCpuAbi = null; 7323 } else if (has32BitLibs && !has64BitLibs) { 7324 // The package has 32 bit libs but not 64 bit libs. Its primary 7325 // ABI should be 32 bit. 7326 7327 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7328 pkg.applicationInfo.secondaryCpuAbi = null; 7329 } else if (has32BitLibs && has64BitLibs) { 7330 // The application has both 64 and 32 bit bundled libraries. We check 7331 // here that the app declares multiArch support, and warn if it doesn't. 7332 // 7333 // We will be lenient here and record both ABIs. The primary will be the 7334 // ABI that's higher on the list, i.e, a device that's configured to prefer 7335 // 64 bit apps will see a 64 bit primary ABI, 7336 7337 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7338 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7339 } 7340 7341 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7342 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7343 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7344 } else { 7345 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7346 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7347 } 7348 } else { 7349 pkg.applicationInfo.primaryCpuAbi = null; 7350 pkg.applicationInfo.secondaryCpuAbi = null; 7351 } 7352 } 7353 7354 private void killApplication(String pkgName, int appId, String reason) { 7355 // Request the ActivityManager to kill the process(only for existing packages) 7356 // so that we do not end up in a confused state while the user is still using the older 7357 // version of the application while the new one gets installed. 7358 IActivityManager am = ActivityManagerNative.getDefault(); 7359 if (am != null) { 7360 try { 7361 am.killApplicationWithAppId(pkgName, appId, reason); 7362 } catch (RemoteException e) { 7363 } 7364 } 7365 } 7366 7367 void removePackageLI(PackageSetting ps, boolean chatty) { 7368 if (DEBUG_INSTALL) { 7369 if (chatty) 7370 Log.d(TAG, "Removing package " + ps.name); 7371 } 7372 7373 // writer 7374 synchronized (mPackages) { 7375 mPackages.remove(ps.name); 7376 final PackageParser.Package pkg = ps.pkg; 7377 if (pkg != null) { 7378 cleanPackageDataStructuresLILPw(pkg, chatty); 7379 } 7380 } 7381 } 7382 7383 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7384 if (DEBUG_INSTALL) { 7385 if (chatty) 7386 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7387 } 7388 7389 // writer 7390 synchronized (mPackages) { 7391 mPackages.remove(pkg.applicationInfo.packageName); 7392 cleanPackageDataStructuresLILPw(pkg, chatty); 7393 } 7394 } 7395 7396 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7397 int N = pkg.providers.size(); 7398 StringBuilder r = null; 7399 int i; 7400 for (i=0; i<N; i++) { 7401 PackageParser.Provider p = pkg.providers.get(i); 7402 mProviders.removeProvider(p); 7403 if (p.info.authority == null) { 7404 7405 /* There was another ContentProvider with this authority when 7406 * this app was installed so this authority is null, 7407 * Ignore it as we don't have to unregister the provider. 7408 */ 7409 continue; 7410 } 7411 String names[] = p.info.authority.split(";"); 7412 for (int j = 0; j < names.length; j++) { 7413 if (mProvidersByAuthority.get(names[j]) == p) { 7414 mProvidersByAuthority.remove(names[j]); 7415 if (DEBUG_REMOVE) { 7416 if (chatty) 7417 Log.d(TAG, "Unregistered content provider: " + names[j] 7418 + ", className = " + p.info.name + ", isSyncable = " 7419 + p.info.isSyncable); 7420 } 7421 } 7422 } 7423 if (DEBUG_REMOVE && chatty) { 7424 if (r == null) { 7425 r = new StringBuilder(256); 7426 } else { 7427 r.append(' '); 7428 } 7429 r.append(p.info.name); 7430 } 7431 } 7432 if (r != null) { 7433 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7434 } 7435 7436 N = pkg.services.size(); 7437 r = null; 7438 for (i=0; i<N; i++) { 7439 PackageParser.Service s = pkg.services.get(i); 7440 mServices.removeService(s); 7441 if (chatty) { 7442 if (r == null) { 7443 r = new StringBuilder(256); 7444 } else { 7445 r.append(' '); 7446 } 7447 r.append(s.info.name); 7448 } 7449 } 7450 if (r != null) { 7451 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7452 } 7453 7454 N = pkg.receivers.size(); 7455 r = null; 7456 for (i=0; i<N; i++) { 7457 PackageParser.Activity a = pkg.receivers.get(i); 7458 mReceivers.removeActivity(a, "receiver"); 7459 if (DEBUG_REMOVE && chatty) { 7460 if (r == null) { 7461 r = new StringBuilder(256); 7462 } else { 7463 r.append(' '); 7464 } 7465 r.append(a.info.name); 7466 } 7467 } 7468 if (r != null) { 7469 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7470 } 7471 7472 N = pkg.activities.size(); 7473 r = null; 7474 for (i=0; i<N; i++) { 7475 PackageParser.Activity a = pkg.activities.get(i); 7476 mActivities.removeActivity(a, "activity"); 7477 if (DEBUG_REMOVE && chatty) { 7478 if (r == null) { 7479 r = new StringBuilder(256); 7480 } else { 7481 r.append(' '); 7482 } 7483 r.append(a.info.name); 7484 } 7485 } 7486 if (r != null) { 7487 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7488 } 7489 7490 N = pkg.permissions.size(); 7491 r = null; 7492 for (i=0; i<N; i++) { 7493 PackageParser.Permission p = pkg.permissions.get(i); 7494 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7495 if (bp == null) { 7496 bp = mSettings.mPermissionTrees.get(p.info.name); 7497 } 7498 if (bp != null && bp.perm == p) { 7499 bp.perm = null; 7500 if (DEBUG_REMOVE && chatty) { 7501 if (r == null) { 7502 r = new StringBuilder(256); 7503 } else { 7504 r.append(' '); 7505 } 7506 r.append(p.info.name); 7507 } 7508 } 7509 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7510 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7511 if (appOpPerms != null) { 7512 appOpPerms.remove(pkg.packageName); 7513 } 7514 } 7515 } 7516 if (r != null) { 7517 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7518 } 7519 7520 N = pkg.requestedPermissions.size(); 7521 r = null; 7522 for (i=0; i<N; i++) { 7523 String perm = pkg.requestedPermissions.get(i); 7524 BasePermission bp = mSettings.mPermissions.get(perm); 7525 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7526 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7527 if (appOpPerms != null) { 7528 appOpPerms.remove(pkg.packageName); 7529 if (appOpPerms.isEmpty()) { 7530 mAppOpPermissionPackages.remove(perm); 7531 } 7532 } 7533 } 7534 } 7535 if (r != null) { 7536 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7537 } 7538 7539 N = pkg.instrumentation.size(); 7540 r = null; 7541 for (i=0; i<N; i++) { 7542 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7543 mInstrumentation.remove(a.getComponentName()); 7544 if (DEBUG_REMOVE && chatty) { 7545 if (r == null) { 7546 r = new StringBuilder(256); 7547 } else { 7548 r.append(' '); 7549 } 7550 r.append(a.info.name); 7551 } 7552 } 7553 if (r != null) { 7554 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7555 } 7556 7557 r = null; 7558 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7559 // Only system apps can hold shared libraries. 7560 if (pkg.libraryNames != null) { 7561 for (i=0; i<pkg.libraryNames.size(); i++) { 7562 String name = pkg.libraryNames.get(i); 7563 SharedLibraryEntry cur = mSharedLibraries.get(name); 7564 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7565 mSharedLibraries.remove(name); 7566 if (DEBUG_REMOVE && chatty) { 7567 if (r == null) { 7568 r = new StringBuilder(256); 7569 } else { 7570 r.append(' '); 7571 } 7572 r.append(name); 7573 } 7574 } 7575 } 7576 } 7577 } 7578 if (r != null) { 7579 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7580 } 7581 } 7582 7583 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7584 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7585 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7586 return true; 7587 } 7588 } 7589 return false; 7590 } 7591 7592 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7593 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7594 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7595 7596 private void updatePermissionsLPw(String changingPkg, 7597 PackageParser.Package pkgInfo, int flags) { 7598 // Make sure there are no dangling permission trees. 7599 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7600 while (it.hasNext()) { 7601 final BasePermission bp = it.next(); 7602 if (bp.packageSetting == null) { 7603 // We may not yet have parsed the package, so just see if 7604 // we still know about its settings. 7605 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7606 } 7607 if (bp.packageSetting == null) { 7608 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7609 + " from package " + bp.sourcePackage); 7610 it.remove(); 7611 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7612 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7613 Slog.i(TAG, "Removing old permission tree: " + bp.name 7614 + " from package " + bp.sourcePackage); 7615 flags |= UPDATE_PERMISSIONS_ALL; 7616 it.remove(); 7617 } 7618 } 7619 } 7620 7621 // Make sure all dynamic permissions have been assigned to a package, 7622 // and make sure there are no dangling permissions. 7623 it = mSettings.mPermissions.values().iterator(); 7624 while (it.hasNext()) { 7625 final BasePermission bp = it.next(); 7626 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7627 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7628 + bp.name + " pkg=" + bp.sourcePackage 7629 + " info=" + bp.pendingInfo); 7630 if (bp.packageSetting == null && bp.pendingInfo != null) { 7631 final BasePermission tree = findPermissionTreeLP(bp.name); 7632 if (tree != null && tree.perm != null) { 7633 bp.packageSetting = tree.packageSetting; 7634 bp.perm = new PackageParser.Permission(tree.perm.owner, 7635 new PermissionInfo(bp.pendingInfo)); 7636 bp.perm.info.packageName = tree.perm.info.packageName; 7637 bp.perm.info.name = bp.name; 7638 bp.uid = tree.uid; 7639 } 7640 } 7641 } 7642 if (bp.packageSetting == null) { 7643 // We may not yet have parsed the package, so just see if 7644 // we still know about its settings. 7645 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7646 } 7647 if (bp.packageSetting == null) { 7648 Slog.w(TAG, "Removing dangling permission: " + bp.name 7649 + " from package " + bp.sourcePackage); 7650 it.remove(); 7651 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7652 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7653 Slog.i(TAG, "Removing old permission: " + bp.name 7654 + " from package " + bp.sourcePackage); 7655 flags |= UPDATE_PERMISSIONS_ALL; 7656 it.remove(); 7657 } 7658 } 7659 } 7660 7661 // Now update the permissions for all packages, in particular 7662 // replace the granted permissions of the system packages. 7663 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7664 for (PackageParser.Package pkg : mPackages.values()) { 7665 if (pkg != pkgInfo) { 7666 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7667 changingPkg); 7668 } 7669 } 7670 } 7671 7672 if (pkgInfo != null) { 7673 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7674 } 7675 } 7676 7677 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7678 String packageOfInterest) { 7679 // IMPORTANT: There are two types of permissions: install and runtime. 7680 // Install time permissions are granted when the app is installed to 7681 // all device users and users added in the future. Runtime permissions 7682 // are granted at runtime explicitly to specific users. Normal and signature 7683 // protected permissions are install time permissions. Dangerous permissions 7684 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7685 // otherwise they are runtime permissions. This function does not manage 7686 // runtime permissions except for the case an app targeting Lollipop MR1 7687 // being upgraded to target a newer SDK, in which case dangerous permissions 7688 // are transformed from install time to runtime ones. 7689 7690 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7691 if (ps == null) { 7692 return; 7693 } 7694 7695 PermissionsState permissionsState = ps.getPermissionsState(); 7696 PermissionsState origPermissions = permissionsState; 7697 7698 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7699 7700 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7701 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7702 7703 boolean changedInstallPermission = false; 7704 7705 if (replace) { 7706 ps.installPermissionsFixed = false; 7707 if (!ps.isSharedUser()) { 7708 origPermissions = new PermissionsState(permissionsState); 7709 permissionsState.reset(); 7710 } 7711 } 7712 7713 permissionsState.setGlobalGids(mGlobalGids); 7714 7715 final int N = pkg.requestedPermissions.size(); 7716 for (int i=0; i<N; i++) { 7717 final String name = pkg.requestedPermissions.get(i); 7718 final BasePermission bp = mSettings.mPermissions.get(name); 7719 7720 if (DEBUG_INSTALL) { 7721 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7722 } 7723 7724 if (bp == null || bp.packageSetting == null) { 7725 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7726 Slog.w(TAG, "Unknown permission " + name 7727 + " in package " + pkg.packageName); 7728 } 7729 continue; 7730 } 7731 7732 final String perm = bp.name; 7733 boolean allowedSig = false; 7734 int grant = GRANT_DENIED; 7735 7736 // Keep track of app op permissions. 7737 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7738 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7739 if (pkgs == null) { 7740 pkgs = new ArraySet<>(); 7741 mAppOpPermissionPackages.put(bp.name, pkgs); 7742 } 7743 pkgs.add(pkg.packageName); 7744 } 7745 7746 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7747 switch (level) { 7748 case PermissionInfo.PROTECTION_NORMAL: { 7749 // For all apps normal permissions are install time ones. 7750 grant = GRANT_INSTALL; 7751 } break; 7752 7753 case PermissionInfo.PROTECTION_DANGEROUS: { 7754 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7755 // For legacy apps dangerous permissions are install time ones. 7756 grant = GRANT_INSTALL_LEGACY; 7757 } else if (ps.isSystem()) { 7758 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7759 if (origPermissions.hasInstallPermission(bp.name)) { 7760 // If a system app had an install permission, then the app was 7761 // upgraded and we grant the permissions as runtime to all users. 7762 grant = GRANT_UPGRADE; 7763 upgradeUserIds = currentUserIds; 7764 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7765 // If users changed since the last permissions update for a 7766 // system app, we grant the permission as runtime to the new users. 7767 grant = GRANT_UPGRADE; 7768 upgradeUserIds = currentUserIds; 7769 for (int userId : updatedUserIds) { 7770 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7771 } 7772 } else { 7773 // Otherwise, we grant the permission as runtime if the app 7774 // already had it, i.e. we preserve runtime permissions. 7775 grant = GRANT_RUNTIME; 7776 } 7777 } else if (origPermissions.hasInstallPermission(bp.name)) { 7778 // For legacy apps that became modern, install becomes runtime. 7779 grant = GRANT_UPGRADE; 7780 upgradeUserIds = currentUserIds; 7781 } else if (replace) { 7782 // For upgraded modern apps keep runtime permissions unchanged. 7783 grant = GRANT_RUNTIME; 7784 } 7785 } break; 7786 7787 case PermissionInfo.PROTECTION_SIGNATURE: { 7788 // For all apps signature permissions are install time ones. 7789 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7790 if (allowedSig) { 7791 grant = GRANT_INSTALL; 7792 } 7793 } break; 7794 } 7795 7796 if (DEBUG_INSTALL) { 7797 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7798 } 7799 7800 if (grant != GRANT_DENIED) { 7801 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7802 // If this is an existing, non-system package, then 7803 // we can't add any new permissions to it. 7804 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7805 // Except... if this is a permission that was added 7806 // to the platform (note: need to only do this when 7807 // updating the platform). 7808 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7809 grant = GRANT_DENIED; 7810 } 7811 } 7812 } 7813 7814 switch (grant) { 7815 case GRANT_INSTALL: { 7816 // Revoke this as runtime permission to handle the case of 7817 // a runtime permssion being downgraded to an install one. 7818 for (int userId : UserManagerService.getInstance().getUserIds()) { 7819 if (origPermissions.getRuntimePermissionState( 7820 bp.name, userId) != null) { 7821 // Revoke the runtime permission and clear the flags. 7822 origPermissions.revokeRuntimePermission(bp, userId); 7823 origPermissions.updatePermissionFlags(bp, userId, 7824 PackageManager.MASK_PERMISSION_FLAGS, 0); 7825 // If we revoked a permission permission, we have to write. 7826 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7827 changedRuntimePermissionUserIds, userId); 7828 } 7829 } 7830 // Grant an install permission. 7831 if (permissionsState.grantInstallPermission(bp) != 7832 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7833 changedInstallPermission = true; 7834 } 7835 } break; 7836 7837 case GRANT_INSTALL_LEGACY: { 7838 // Grant an install permission. 7839 if (permissionsState.grantInstallPermission(bp) != 7840 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7841 changedInstallPermission = true; 7842 } 7843 } break; 7844 7845 case GRANT_RUNTIME: { 7846 // Grant previously granted runtime permissions. 7847 for (int userId : UserManagerService.getInstance().getUserIds()) { 7848 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7849 PermissionState permissionState = origPermissions 7850 .getRuntimePermissionState(bp.name, userId); 7851 final int flags = permissionState.getFlags(); 7852 if (permissionsState.grantRuntimePermission(bp, userId) == 7853 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7854 // If we cannot put the permission as it was, we have to write. 7855 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7856 changedRuntimePermissionUserIds, userId); 7857 } else { 7858 // System components not only get the permissions but 7859 // they are also fixed, so nothing can change that. 7860 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7861 ? flags 7862 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7863 // Propagate the permission flags. 7864 permissionsState.updatePermissionFlags(bp, userId, 7865 newFlags, newFlags); 7866 } 7867 } 7868 } 7869 } break; 7870 7871 case GRANT_UPGRADE: { 7872 // Grant runtime permissions for a previously held install permission. 7873 PermissionState permissionState = origPermissions 7874 .getInstallPermissionState(bp.name); 7875 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7876 7877 origPermissions.revokeInstallPermission(bp); 7878 // We will be transferring the permission flags, so clear them. 7879 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7880 PackageManager.MASK_PERMISSION_FLAGS, 0); 7881 7882 // If the permission is not to be promoted to runtime we ignore it and 7883 // also its other flags as they are not applicable to install permissions. 7884 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7885 for (int userId : upgradeUserIds) { 7886 if (permissionsState.grantRuntimePermission(bp, userId) != 7887 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7888 // System components not only get the permissions but 7889 // they are also fixed so nothing can change that. 7890 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7891 ? flags 7892 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7893 // Transfer the permission flags. 7894 permissionsState.updatePermissionFlags(bp, userId, 7895 newFlags, newFlags); 7896 // If we granted the permission, we have to write. 7897 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7898 changedRuntimePermissionUserIds, userId); 7899 } 7900 } 7901 } 7902 } break; 7903 7904 default: { 7905 if (packageOfInterest == null 7906 || packageOfInterest.equals(pkg.packageName)) { 7907 Slog.w(TAG, "Not granting permission " + perm 7908 + " to package " + pkg.packageName 7909 + " because it was previously installed without"); 7910 } 7911 } break; 7912 } 7913 } else { 7914 if (permissionsState.revokeInstallPermission(bp) != 7915 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7916 // Also drop the permission flags. 7917 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7918 PackageManager.MASK_PERMISSION_FLAGS, 0); 7919 changedInstallPermission = true; 7920 Slog.i(TAG, "Un-granting permission " + perm 7921 + " from package " + pkg.packageName 7922 + " (protectionLevel=" + bp.protectionLevel 7923 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7924 + ")"); 7925 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7926 // Don't print warning for app op permissions, since it is fine for them 7927 // not to be granted, there is a UI for the user to decide. 7928 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7929 Slog.w(TAG, "Not granting permission " + perm 7930 + " to package " + pkg.packageName 7931 + " (protectionLevel=" + bp.protectionLevel 7932 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7933 + ")"); 7934 } 7935 } 7936 } 7937 } 7938 7939 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7940 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7941 // This is the first that we have heard about this package, so the 7942 // permissions we have now selected are fixed until explicitly 7943 // changed. 7944 ps.installPermissionsFixed = true; 7945 } 7946 7947 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7948 7949 // Persist the runtime permissions state for users with changes. 7950 for (int userId : changedRuntimePermissionUserIds) { 7951 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7952 } 7953 } 7954 7955 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7956 boolean allowed = false; 7957 final int NP = PackageParser.NEW_PERMISSIONS.length; 7958 for (int ip=0; ip<NP; ip++) { 7959 final PackageParser.NewPermissionInfo npi 7960 = PackageParser.NEW_PERMISSIONS[ip]; 7961 if (npi.name.equals(perm) 7962 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7963 allowed = true; 7964 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7965 + pkg.packageName); 7966 break; 7967 } 7968 } 7969 return allowed; 7970 } 7971 7972 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7973 BasePermission bp, PermissionsState origPermissions) { 7974 boolean allowed; 7975 allowed = (compareSignatures( 7976 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7977 == PackageManager.SIGNATURE_MATCH) 7978 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7979 == PackageManager.SIGNATURE_MATCH); 7980 if (!allowed && (bp.protectionLevel 7981 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7982 if (isSystemApp(pkg)) { 7983 // For updated system applications, a system permission 7984 // is granted only if it had been defined by the original application. 7985 if (pkg.isUpdatedSystemApp()) { 7986 final PackageSetting sysPs = mSettings 7987 .getDisabledSystemPkgLPr(pkg.packageName); 7988 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7989 // If the original was granted this permission, we take 7990 // that grant decision as read and propagate it to the 7991 // update. 7992 if (sysPs.isPrivileged()) { 7993 allowed = true; 7994 } 7995 } else { 7996 // The system apk may have been updated with an older 7997 // version of the one on the data partition, but which 7998 // granted a new system permission that it didn't have 7999 // before. In this case we do want to allow the app to 8000 // now get the new permission if the ancestral apk is 8001 // privileged to get it. 8002 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8003 for (int j=0; 8004 j<sysPs.pkg.requestedPermissions.size(); j++) { 8005 if (perm.equals( 8006 sysPs.pkg.requestedPermissions.get(j))) { 8007 allowed = true; 8008 break; 8009 } 8010 } 8011 } 8012 } 8013 } else { 8014 allowed = isPrivilegedApp(pkg); 8015 } 8016 } 8017 } 8018 if (!allowed && (bp.protectionLevel 8019 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8020 // For development permissions, a development permission 8021 // is granted only if it was already granted. 8022 allowed = origPermissions.hasInstallPermission(perm); 8023 } 8024 return allowed; 8025 } 8026 8027 final class ActivityIntentResolver 8028 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8029 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8030 boolean defaultOnly, int userId) { 8031 if (!sUserManager.exists(userId)) return null; 8032 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8033 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8034 } 8035 8036 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8037 int userId) { 8038 if (!sUserManager.exists(userId)) return null; 8039 mFlags = flags; 8040 return super.queryIntent(intent, resolvedType, 8041 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8042 } 8043 8044 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8045 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8046 if (!sUserManager.exists(userId)) return null; 8047 if (packageActivities == null) { 8048 return null; 8049 } 8050 mFlags = flags; 8051 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8052 final int N = packageActivities.size(); 8053 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8054 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8055 8056 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8057 for (int i = 0; i < N; ++i) { 8058 intentFilters = packageActivities.get(i).intents; 8059 if (intentFilters != null && intentFilters.size() > 0) { 8060 PackageParser.ActivityIntentInfo[] array = 8061 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8062 intentFilters.toArray(array); 8063 listCut.add(array); 8064 } 8065 } 8066 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8067 } 8068 8069 public final void addActivity(PackageParser.Activity a, String type) { 8070 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8071 mActivities.put(a.getComponentName(), a); 8072 if (DEBUG_SHOW_INFO) 8073 Log.v( 8074 TAG, " " + type + " " + 8075 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8076 if (DEBUG_SHOW_INFO) 8077 Log.v(TAG, " Class=" + a.info.name); 8078 final int NI = a.intents.size(); 8079 for (int j=0; j<NI; j++) { 8080 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8081 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8082 intent.setPriority(0); 8083 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8084 + a.className + " with priority > 0, forcing to 0"); 8085 } 8086 if (DEBUG_SHOW_INFO) { 8087 Log.v(TAG, " IntentFilter:"); 8088 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8089 } 8090 if (!intent.debugCheck()) { 8091 Log.w(TAG, "==> For Activity " + a.info.name); 8092 } 8093 addFilter(intent); 8094 } 8095 } 8096 8097 public final void removeActivity(PackageParser.Activity a, String type) { 8098 mActivities.remove(a.getComponentName()); 8099 if (DEBUG_SHOW_INFO) { 8100 Log.v(TAG, " " + type + " " 8101 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8102 : a.info.name) + ":"); 8103 Log.v(TAG, " Class=" + a.info.name); 8104 } 8105 final int NI = a.intents.size(); 8106 for (int j=0; j<NI; j++) { 8107 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8108 if (DEBUG_SHOW_INFO) { 8109 Log.v(TAG, " IntentFilter:"); 8110 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8111 } 8112 removeFilter(intent); 8113 } 8114 } 8115 8116 @Override 8117 protected boolean allowFilterResult( 8118 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8119 ActivityInfo filterAi = filter.activity.info; 8120 for (int i=dest.size()-1; i>=0; i--) { 8121 ActivityInfo destAi = dest.get(i).activityInfo; 8122 if (destAi.name == filterAi.name 8123 && destAi.packageName == filterAi.packageName) { 8124 return false; 8125 } 8126 } 8127 return true; 8128 } 8129 8130 @Override 8131 protected ActivityIntentInfo[] newArray(int size) { 8132 return new ActivityIntentInfo[size]; 8133 } 8134 8135 @Override 8136 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8137 if (!sUserManager.exists(userId)) return true; 8138 PackageParser.Package p = filter.activity.owner; 8139 if (p != null) { 8140 PackageSetting ps = (PackageSetting)p.mExtras; 8141 if (ps != null) { 8142 // System apps are never considered stopped for purposes of 8143 // filtering, because there may be no way for the user to 8144 // actually re-launch them. 8145 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8146 && ps.getStopped(userId); 8147 } 8148 } 8149 return false; 8150 } 8151 8152 @Override 8153 protected boolean isPackageForFilter(String packageName, 8154 PackageParser.ActivityIntentInfo info) { 8155 return packageName.equals(info.activity.owner.packageName); 8156 } 8157 8158 @Override 8159 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8160 int match, int userId) { 8161 if (!sUserManager.exists(userId)) return null; 8162 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8163 return null; 8164 } 8165 final PackageParser.Activity activity = info.activity; 8166 if (mSafeMode && (activity.info.applicationInfo.flags 8167 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8168 return null; 8169 } 8170 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8171 if (ps == null) { 8172 return null; 8173 } 8174 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8175 ps.readUserState(userId), userId); 8176 if (ai == null) { 8177 return null; 8178 } 8179 final ResolveInfo res = new ResolveInfo(); 8180 res.activityInfo = ai; 8181 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8182 res.filter = info; 8183 } 8184 if (info != null) { 8185 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8186 } 8187 res.priority = info.getPriority(); 8188 res.preferredOrder = activity.owner.mPreferredOrder; 8189 //System.out.println("Result: " + res.activityInfo.className + 8190 // " = " + res.priority); 8191 res.match = match; 8192 res.isDefault = info.hasDefault; 8193 res.labelRes = info.labelRes; 8194 res.nonLocalizedLabel = info.nonLocalizedLabel; 8195 if (userNeedsBadging(userId)) { 8196 res.noResourceId = true; 8197 } else { 8198 res.icon = info.icon; 8199 } 8200 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8201 return res; 8202 } 8203 8204 @Override 8205 protected void sortResults(List<ResolveInfo> results) { 8206 Collections.sort(results, mResolvePrioritySorter); 8207 } 8208 8209 @Override 8210 protected void dumpFilter(PrintWriter out, String prefix, 8211 PackageParser.ActivityIntentInfo filter) { 8212 out.print(prefix); out.print( 8213 Integer.toHexString(System.identityHashCode(filter.activity))); 8214 out.print(' '); 8215 filter.activity.printComponentShortName(out); 8216 out.print(" filter "); 8217 out.println(Integer.toHexString(System.identityHashCode(filter))); 8218 } 8219 8220 @Override 8221 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8222 return filter.activity; 8223 } 8224 8225 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8226 PackageParser.Activity activity = (PackageParser.Activity)label; 8227 out.print(prefix); out.print( 8228 Integer.toHexString(System.identityHashCode(activity))); 8229 out.print(' '); 8230 activity.printComponentShortName(out); 8231 if (count > 1) { 8232 out.print(" ("); out.print(count); out.print(" filters)"); 8233 } 8234 out.println(); 8235 } 8236 8237// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8238// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8239// final List<ResolveInfo> retList = Lists.newArrayList(); 8240// while (i.hasNext()) { 8241// final ResolveInfo resolveInfo = i.next(); 8242// if (isEnabledLP(resolveInfo.activityInfo)) { 8243// retList.add(resolveInfo); 8244// } 8245// } 8246// return retList; 8247// } 8248 8249 // Keys are String (activity class name), values are Activity. 8250 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8251 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8252 private int mFlags; 8253 } 8254 8255 private final class ServiceIntentResolver 8256 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8257 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8258 boolean defaultOnly, int userId) { 8259 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8260 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8261 } 8262 8263 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8264 int userId) { 8265 if (!sUserManager.exists(userId)) return null; 8266 mFlags = flags; 8267 return super.queryIntent(intent, resolvedType, 8268 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8269 } 8270 8271 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8272 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8273 if (!sUserManager.exists(userId)) return null; 8274 if (packageServices == null) { 8275 return null; 8276 } 8277 mFlags = flags; 8278 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8279 final int N = packageServices.size(); 8280 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8281 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8282 8283 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8284 for (int i = 0; i < N; ++i) { 8285 intentFilters = packageServices.get(i).intents; 8286 if (intentFilters != null && intentFilters.size() > 0) { 8287 PackageParser.ServiceIntentInfo[] array = 8288 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8289 intentFilters.toArray(array); 8290 listCut.add(array); 8291 } 8292 } 8293 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8294 } 8295 8296 public final void addService(PackageParser.Service s) { 8297 mServices.put(s.getComponentName(), s); 8298 if (DEBUG_SHOW_INFO) { 8299 Log.v(TAG, " " 8300 + (s.info.nonLocalizedLabel != null 8301 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8302 Log.v(TAG, " Class=" + s.info.name); 8303 } 8304 final int NI = s.intents.size(); 8305 int j; 8306 for (j=0; j<NI; j++) { 8307 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8308 if (DEBUG_SHOW_INFO) { 8309 Log.v(TAG, " IntentFilter:"); 8310 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8311 } 8312 if (!intent.debugCheck()) { 8313 Log.w(TAG, "==> For Service " + s.info.name); 8314 } 8315 addFilter(intent); 8316 } 8317 } 8318 8319 public final void removeService(PackageParser.Service s) { 8320 mServices.remove(s.getComponentName()); 8321 if (DEBUG_SHOW_INFO) { 8322 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8323 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8324 Log.v(TAG, " Class=" + s.info.name); 8325 } 8326 final int NI = s.intents.size(); 8327 int j; 8328 for (j=0; j<NI; j++) { 8329 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8330 if (DEBUG_SHOW_INFO) { 8331 Log.v(TAG, " IntentFilter:"); 8332 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8333 } 8334 removeFilter(intent); 8335 } 8336 } 8337 8338 @Override 8339 protected boolean allowFilterResult( 8340 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8341 ServiceInfo filterSi = filter.service.info; 8342 for (int i=dest.size()-1; i>=0; i--) { 8343 ServiceInfo destAi = dest.get(i).serviceInfo; 8344 if (destAi.name == filterSi.name 8345 && destAi.packageName == filterSi.packageName) { 8346 return false; 8347 } 8348 } 8349 return true; 8350 } 8351 8352 @Override 8353 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8354 return new PackageParser.ServiceIntentInfo[size]; 8355 } 8356 8357 @Override 8358 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8359 if (!sUserManager.exists(userId)) return true; 8360 PackageParser.Package p = filter.service.owner; 8361 if (p != null) { 8362 PackageSetting ps = (PackageSetting)p.mExtras; 8363 if (ps != null) { 8364 // System apps are never considered stopped for purposes of 8365 // filtering, because there may be no way for the user to 8366 // actually re-launch them. 8367 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8368 && ps.getStopped(userId); 8369 } 8370 } 8371 return false; 8372 } 8373 8374 @Override 8375 protected boolean isPackageForFilter(String packageName, 8376 PackageParser.ServiceIntentInfo info) { 8377 return packageName.equals(info.service.owner.packageName); 8378 } 8379 8380 @Override 8381 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8382 int match, int userId) { 8383 if (!sUserManager.exists(userId)) return null; 8384 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8385 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8386 return null; 8387 } 8388 final PackageParser.Service service = info.service; 8389 if (mSafeMode && (service.info.applicationInfo.flags 8390 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8391 return null; 8392 } 8393 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8394 if (ps == null) { 8395 return null; 8396 } 8397 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8398 ps.readUserState(userId), userId); 8399 if (si == null) { 8400 return null; 8401 } 8402 final ResolveInfo res = new ResolveInfo(); 8403 res.serviceInfo = si; 8404 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8405 res.filter = filter; 8406 } 8407 res.priority = info.getPriority(); 8408 res.preferredOrder = service.owner.mPreferredOrder; 8409 res.match = match; 8410 res.isDefault = info.hasDefault; 8411 res.labelRes = info.labelRes; 8412 res.nonLocalizedLabel = info.nonLocalizedLabel; 8413 res.icon = info.icon; 8414 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8415 return res; 8416 } 8417 8418 @Override 8419 protected void sortResults(List<ResolveInfo> results) { 8420 Collections.sort(results, mResolvePrioritySorter); 8421 } 8422 8423 @Override 8424 protected void dumpFilter(PrintWriter out, String prefix, 8425 PackageParser.ServiceIntentInfo filter) { 8426 out.print(prefix); out.print( 8427 Integer.toHexString(System.identityHashCode(filter.service))); 8428 out.print(' '); 8429 filter.service.printComponentShortName(out); 8430 out.print(" filter "); 8431 out.println(Integer.toHexString(System.identityHashCode(filter))); 8432 } 8433 8434 @Override 8435 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8436 return filter.service; 8437 } 8438 8439 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8440 PackageParser.Service service = (PackageParser.Service)label; 8441 out.print(prefix); out.print( 8442 Integer.toHexString(System.identityHashCode(service))); 8443 out.print(' '); 8444 service.printComponentShortName(out); 8445 if (count > 1) { 8446 out.print(" ("); out.print(count); out.print(" filters)"); 8447 } 8448 out.println(); 8449 } 8450 8451// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8452// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8453// final List<ResolveInfo> retList = Lists.newArrayList(); 8454// while (i.hasNext()) { 8455// final ResolveInfo resolveInfo = (ResolveInfo) i; 8456// if (isEnabledLP(resolveInfo.serviceInfo)) { 8457// retList.add(resolveInfo); 8458// } 8459// } 8460// return retList; 8461// } 8462 8463 // Keys are String (activity class name), values are Activity. 8464 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8465 = new ArrayMap<ComponentName, PackageParser.Service>(); 8466 private int mFlags; 8467 }; 8468 8469 private final class ProviderIntentResolver 8470 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8471 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8472 boolean defaultOnly, int userId) { 8473 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8474 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8475 } 8476 8477 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8478 int userId) { 8479 if (!sUserManager.exists(userId)) 8480 return null; 8481 mFlags = flags; 8482 return super.queryIntent(intent, resolvedType, 8483 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8484 } 8485 8486 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8487 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8488 if (!sUserManager.exists(userId)) 8489 return null; 8490 if (packageProviders == null) { 8491 return null; 8492 } 8493 mFlags = flags; 8494 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8495 final int N = packageProviders.size(); 8496 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8497 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8498 8499 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8500 for (int i = 0; i < N; ++i) { 8501 intentFilters = packageProviders.get(i).intents; 8502 if (intentFilters != null && intentFilters.size() > 0) { 8503 PackageParser.ProviderIntentInfo[] array = 8504 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8505 intentFilters.toArray(array); 8506 listCut.add(array); 8507 } 8508 } 8509 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8510 } 8511 8512 public final void addProvider(PackageParser.Provider p) { 8513 if (mProviders.containsKey(p.getComponentName())) { 8514 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8515 return; 8516 } 8517 8518 mProviders.put(p.getComponentName(), p); 8519 if (DEBUG_SHOW_INFO) { 8520 Log.v(TAG, " " 8521 + (p.info.nonLocalizedLabel != null 8522 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8523 Log.v(TAG, " Class=" + p.info.name); 8524 } 8525 final int NI = p.intents.size(); 8526 int j; 8527 for (j = 0; j < NI; j++) { 8528 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8529 if (DEBUG_SHOW_INFO) { 8530 Log.v(TAG, " IntentFilter:"); 8531 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8532 } 8533 if (!intent.debugCheck()) { 8534 Log.w(TAG, "==> For Provider " + p.info.name); 8535 } 8536 addFilter(intent); 8537 } 8538 } 8539 8540 public final void removeProvider(PackageParser.Provider p) { 8541 mProviders.remove(p.getComponentName()); 8542 if (DEBUG_SHOW_INFO) { 8543 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8544 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8545 Log.v(TAG, " Class=" + p.info.name); 8546 } 8547 final int NI = p.intents.size(); 8548 int j; 8549 for (j = 0; j < NI; j++) { 8550 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8551 if (DEBUG_SHOW_INFO) { 8552 Log.v(TAG, " IntentFilter:"); 8553 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8554 } 8555 removeFilter(intent); 8556 } 8557 } 8558 8559 @Override 8560 protected boolean allowFilterResult( 8561 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8562 ProviderInfo filterPi = filter.provider.info; 8563 for (int i = dest.size() - 1; i >= 0; i--) { 8564 ProviderInfo destPi = dest.get(i).providerInfo; 8565 if (destPi.name == filterPi.name 8566 && destPi.packageName == filterPi.packageName) { 8567 return false; 8568 } 8569 } 8570 return true; 8571 } 8572 8573 @Override 8574 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8575 return new PackageParser.ProviderIntentInfo[size]; 8576 } 8577 8578 @Override 8579 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8580 if (!sUserManager.exists(userId)) 8581 return true; 8582 PackageParser.Package p = filter.provider.owner; 8583 if (p != null) { 8584 PackageSetting ps = (PackageSetting) p.mExtras; 8585 if (ps != null) { 8586 // System apps are never considered stopped for purposes of 8587 // filtering, because there may be no way for the user to 8588 // actually re-launch them. 8589 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8590 && ps.getStopped(userId); 8591 } 8592 } 8593 return false; 8594 } 8595 8596 @Override 8597 protected boolean isPackageForFilter(String packageName, 8598 PackageParser.ProviderIntentInfo info) { 8599 return packageName.equals(info.provider.owner.packageName); 8600 } 8601 8602 @Override 8603 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8604 int match, int userId) { 8605 if (!sUserManager.exists(userId)) 8606 return null; 8607 final PackageParser.ProviderIntentInfo info = filter; 8608 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8609 return null; 8610 } 8611 final PackageParser.Provider provider = info.provider; 8612 if (mSafeMode && (provider.info.applicationInfo.flags 8613 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8614 return null; 8615 } 8616 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8617 if (ps == null) { 8618 return null; 8619 } 8620 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8621 ps.readUserState(userId), userId); 8622 if (pi == null) { 8623 return null; 8624 } 8625 final ResolveInfo res = new ResolveInfo(); 8626 res.providerInfo = pi; 8627 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8628 res.filter = filter; 8629 } 8630 res.priority = info.getPriority(); 8631 res.preferredOrder = provider.owner.mPreferredOrder; 8632 res.match = match; 8633 res.isDefault = info.hasDefault; 8634 res.labelRes = info.labelRes; 8635 res.nonLocalizedLabel = info.nonLocalizedLabel; 8636 res.icon = info.icon; 8637 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8638 return res; 8639 } 8640 8641 @Override 8642 protected void sortResults(List<ResolveInfo> results) { 8643 Collections.sort(results, mResolvePrioritySorter); 8644 } 8645 8646 @Override 8647 protected void dumpFilter(PrintWriter out, String prefix, 8648 PackageParser.ProviderIntentInfo filter) { 8649 out.print(prefix); 8650 out.print( 8651 Integer.toHexString(System.identityHashCode(filter.provider))); 8652 out.print(' '); 8653 filter.provider.printComponentShortName(out); 8654 out.print(" filter "); 8655 out.println(Integer.toHexString(System.identityHashCode(filter))); 8656 } 8657 8658 @Override 8659 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8660 return filter.provider; 8661 } 8662 8663 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8664 PackageParser.Provider provider = (PackageParser.Provider)label; 8665 out.print(prefix); out.print( 8666 Integer.toHexString(System.identityHashCode(provider))); 8667 out.print(' '); 8668 provider.printComponentShortName(out); 8669 if (count > 1) { 8670 out.print(" ("); out.print(count); out.print(" filters)"); 8671 } 8672 out.println(); 8673 } 8674 8675 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8676 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8677 private int mFlags; 8678 }; 8679 8680 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8681 new Comparator<ResolveInfo>() { 8682 public int compare(ResolveInfo r1, ResolveInfo r2) { 8683 int v1 = r1.priority; 8684 int v2 = r2.priority; 8685 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8686 if (v1 != v2) { 8687 return (v1 > v2) ? -1 : 1; 8688 } 8689 v1 = r1.preferredOrder; 8690 v2 = r2.preferredOrder; 8691 if (v1 != v2) { 8692 return (v1 > v2) ? -1 : 1; 8693 } 8694 if (r1.isDefault != r2.isDefault) { 8695 return r1.isDefault ? -1 : 1; 8696 } 8697 v1 = r1.match; 8698 v2 = r2.match; 8699 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8700 if (v1 != v2) { 8701 return (v1 > v2) ? -1 : 1; 8702 } 8703 if (r1.system != r2.system) { 8704 return r1.system ? -1 : 1; 8705 } 8706 return 0; 8707 } 8708 }; 8709 8710 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8711 new Comparator<ProviderInfo>() { 8712 public int compare(ProviderInfo p1, ProviderInfo p2) { 8713 final int v1 = p1.initOrder; 8714 final int v2 = p2.initOrder; 8715 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8716 } 8717 }; 8718 8719 final void sendPackageBroadcast(final String action, final String pkg, 8720 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8721 final int[] userIds) { 8722 mHandler.post(new Runnable() { 8723 @Override 8724 public void run() { 8725 try { 8726 final IActivityManager am = ActivityManagerNative.getDefault(); 8727 if (am == null) return; 8728 final int[] resolvedUserIds; 8729 if (userIds == null) { 8730 resolvedUserIds = am.getRunningUserIds(); 8731 } else { 8732 resolvedUserIds = userIds; 8733 } 8734 for (int id : resolvedUserIds) { 8735 final Intent intent = new Intent(action, 8736 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8737 if (extras != null) { 8738 intent.putExtras(extras); 8739 } 8740 if (targetPkg != null) { 8741 intent.setPackage(targetPkg); 8742 } 8743 // Modify the UID when posting to other users 8744 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8745 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8746 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8747 intent.putExtra(Intent.EXTRA_UID, uid); 8748 } 8749 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8750 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8751 if (DEBUG_BROADCASTS) { 8752 RuntimeException here = new RuntimeException("here"); 8753 here.fillInStackTrace(); 8754 Slog.d(TAG, "Sending to user " + id + ": " 8755 + intent.toShortString(false, true, false, false) 8756 + " " + intent.getExtras(), here); 8757 } 8758 am.broadcastIntent(null, intent, null, finishedReceiver, 8759 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8760 finishedReceiver != null, false, id); 8761 } 8762 } catch (RemoteException ex) { 8763 } 8764 } 8765 }); 8766 } 8767 8768 /** 8769 * Check if the external storage media is available. This is true if there 8770 * is a mounted external storage medium or if the external storage is 8771 * emulated. 8772 */ 8773 private boolean isExternalMediaAvailable() { 8774 return mMediaMounted || Environment.isExternalStorageEmulated(); 8775 } 8776 8777 @Override 8778 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8779 // writer 8780 synchronized (mPackages) { 8781 if (!isExternalMediaAvailable()) { 8782 // If the external storage is no longer mounted at this point, 8783 // the caller may not have been able to delete all of this 8784 // packages files and can not delete any more. Bail. 8785 return null; 8786 } 8787 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8788 if (lastPackage != null) { 8789 pkgs.remove(lastPackage); 8790 } 8791 if (pkgs.size() > 0) { 8792 return pkgs.get(0); 8793 } 8794 } 8795 return null; 8796 } 8797 8798 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8799 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8800 userId, andCode ? 1 : 0, packageName); 8801 if (mSystemReady) { 8802 msg.sendToTarget(); 8803 } else { 8804 if (mPostSystemReadyMessages == null) { 8805 mPostSystemReadyMessages = new ArrayList<>(); 8806 } 8807 mPostSystemReadyMessages.add(msg); 8808 } 8809 } 8810 8811 void startCleaningPackages() { 8812 // reader 8813 synchronized (mPackages) { 8814 if (!isExternalMediaAvailable()) { 8815 return; 8816 } 8817 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8818 return; 8819 } 8820 } 8821 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8822 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8823 IActivityManager am = ActivityManagerNative.getDefault(); 8824 if (am != null) { 8825 try { 8826 am.startService(null, intent, null, UserHandle.USER_OWNER); 8827 } catch (RemoteException e) { 8828 } 8829 } 8830 } 8831 8832 @Override 8833 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8834 int installFlags, String installerPackageName, VerificationParams verificationParams, 8835 String packageAbiOverride) { 8836 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8837 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8838 } 8839 8840 @Override 8841 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8842 int installFlags, String installerPackageName, VerificationParams verificationParams, 8843 String packageAbiOverride, int userId) { 8844 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8845 8846 final int callingUid = Binder.getCallingUid(); 8847 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8848 8849 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8850 try { 8851 if (observer != null) { 8852 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8853 } 8854 } catch (RemoteException re) { 8855 } 8856 return; 8857 } 8858 8859 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8860 installFlags |= PackageManager.INSTALL_FROM_ADB; 8861 8862 } else { 8863 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8864 // about installerPackageName. 8865 8866 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8867 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8868 } 8869 8870 UserHandle user; 8871 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8872 user = UserHandle.ALL; 8873 } else { 8874 user = new UserHandle(userId); 8875 } 8876 8877 // Only system components can circumvent runtime permissions when installing. 8878 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8879 && mContext.checkCallingOrSelfPermission(Manifest.permission 8880 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8881 throw new SecurityException("You need the " 8882 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8883 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8884 } 8885 8886 verificationParams.setInstallerUid(callingUid); 8887 8888 final File originFile = new File(originPath); 8889 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8890 8891 final Message msg = mHandler.obtainMessage(INIT_COPY); 8892 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8893 null, verificationParams, user, packageAbiOverride); 8894 mHandler.sendMessage(msg); 8895 } 8896 8897 void installStage(String packageName, File stagedDir, String stagedCid, 8898 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8899 String installerPackageName, int installerUid, UserHandle user) { 8900 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8901 params.referrerUri, installerUid, null); 8902 8903 final OriginInfo origin; 8904 if (stagedDir != null) { 8905 origin = OriginInfo.fromStagedFile(stagedDir); 8906 } else { 8907 origin = OriginInfo.fromStagedContainer(stagedCid); 8908 } 8909 8910 final Message msg = mHandler.obtainMessage(INIT_COPY); 8911 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8912 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8913 mHandler.sendMessage(msg); 8914 } 8915 8916 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8917 Bundle extras = new Bundle(1); 8918 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8919 8920 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8921 packageName, extras, null, null, new int[] {userId}); 8922 try { 8923 IActivityManager am = ActivityManagerNative.getDefault(); 8924 final boolean isSystem = 8925 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8926 if (isSystem && am.isUserRunning(userId, false)) { 8927 // The just-installed/enabled app is bundled on the system, so presumed 8928 // to be able to run automatically without needing an explicit launch. 8929 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8930 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8931 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8932 .setPackage(packageName); 8933 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8934 android.app.AppOpsManager.OP_NONE, false, false, userId); 8935 } 8936 } catch (RemoteException e) { 8937 // shouldn't happen 8938 Slog.w(TAG, "Unable to bootstrap installed package", e); 8939 } 8940 } 8941 8942 @Override 8943 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8944 int userId) { 8945 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8946 PackageSetting pkgSetting; 8947 final int uid = Binder.getCallingUid(); 8948 enforceCrossUserPermission(uid, userId, true, true, 8949 "setApplicationHiddenSetting for user " + userId); 8950 8951 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8952 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8953 return false; 8954 } 8955 8956 long callingId = Binder.clearCallingIdentity(); 8957 try { 8958 boolean sendAdded = false; 8959 boolean sendRemoved = false; 8960 // writer 8961 synchronized (mPackages) { 8962 pkgSetting = mSettings.mPackages.get(packageName); 8963 if (pkgSetting == null) { 8964 return false; 8965 } 8966 if (pkgSetting.getHidden(userId) != hidden) { 8967 pkgSetting.setHidden(hidden, userId); 8968 mSettings.writePackageRestrictionsLPr(userId); 8969 if (hidden) { 8970 sendRemoved = true; 8971 } else { 8972 sendAdded = true; 8973 } 8974 } 8975 } 8976 if (sendAdded) { 8977 sendPackageAddedForUser(packageName, pkgSetting, userId); 8978 return true; 8979 } 8980 if (sendRemoved) { 8981 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8982 "hiding pkg"); 8983 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8984 } 8985 } finally { 8986 Binder.restoreCallingIdentity(callingId); 8987 } 8988 return false; 8989 } 8990 8991 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8992 int userId) { 8993 final PackageRemovedInfo info = new PackageRemovedInfo(); 8994 info.removedPackage = packageName; 8995 info.removedUsers = new int[] {userId}; 8996 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8997 info.sendBroadcast(false, false, false); 8998 } 8999 9000 /** 9001 * Returns true if application is not found or there was an error. Otherwise it returns 9002 * the hidden state of the package for the given user. 9003 */ 9004 @Override 9005 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9006 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9007 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9008 false, "getApplicationHidden for user " + userId); 9009 PackageSetting pkgSetting; 9010 long callingId = Binder.clearCallingIdentity(); 9011 try { 9012 // writer 9013 synchronized (mPackages) { 9014 pkgSetting = mSettings.mPackages.get(packageName); 9015 if (pkgSetting == null) { 9016 return true; 9017 } 9018 return pkgSetting.getHidden(userId); 9019 } 9020 } finally { 9021 Binder.restoreCallingIdentity(callingId); 9022 } 9023 } 9024 9025 /** 9026 * @hide 9027 */ 9028 @Override 9029 public int installExistingPackageAsUser(String packageName, int userId) { 9030 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9031 null); 9032 PackageSetting pkgSetting; 9033 final int uid = Binder.getCallingUid(); 9034 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9035 + userId); 9036 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9037 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9038 } 9039 9040 long callingId = Binder.clearCallingIdentity(); 9041 try { 9042 boolean sendAdded = false; 9043 9044 // writer 9045 synchronized (mPackages) { 9046 pkgSetting = mSettings.mPackages.get(packageName); 9047 if (pkgSetting == null) { 9048 return PackageManager.INSTALL_FAILED_INVALID_URI; 9049 } 9050 if (!pkgSetting.getInstalled(userId)) { 9051 pkgSetting.setInstalled(true, userId); 9052 pkgSetting.setHidden(false, userId); 9053 mSettings.writePackageRestrictionsLPr(userId); 9054 sendAdded = true; 9055 } 9056 } 9057 9058 if (sendAdded) { 9059 sendPackageAddedForUser(packageName, pkgSetting, userId); 9060 } 9061 } finally { 9062 Binder.restoreCallingIdentity(callingId); 9063 } 9064 9065 return PackageManager.INSTALL_SUCCEEDED; 9066 } 9067 9068 boolean isUserRestricted(int userId, String restrictionKey) { 9069 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9070 if (restrictions.getBoolean(restrictionKey, false)) { 9071 Log.w(TAG, "User is restricted: " + restrictionKey); 9072 return true; 9073 } 9074 return false; 9075 } 9076 9077 @Override 9078 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9079 mContext.enforceCallingOrSelfPermission( 9080 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9081 "Only package verification agents can verify applications"); 9082 9083 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9084 final PackageVerificationResponse response = new PackageVerificationResponse( 9085 verificationCode, Binder.getCallingUid()); 9086 msg.arg1 = id; 9087 msg.obj = response; 9088 mHandler.sendMessage(msg); 9089 } 9090 9091 @Override 9092 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9093 long millisecondsToDelay) { 9094 mContext.enforceCallingOrSelfPermission( 9095 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9096 "Only package verification agents can extend verification timeouts"); 9097 9098 final PackageVerificationState state = mPendingVerification.get(id); 9099 final PackageVerificationResponse response = new PackageVerificationResponse( 9100 verificationCodeAtTimeout, Binder.getCallingUid()); 9101 9102 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9103 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9104 } 9105 if (millisecondsToDelay < 0) { 9106 millisecondsToDelay = 0; 9107 } 9108 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9109 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9110 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9111 } 9112 9113 if ((state != null) && !state.timeoutExtended()) { 9114 state.extendTimeout(); 9115 9116 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9117 msg.arg1 = id; 9118 msg.obj = response; 9119 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9120 } 9121 } 9122 9123 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9124 int verificationCode, UserHandle user) { 9125 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9126 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9127 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9128 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9129 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9130 9131 mContext.sendBroadcastAsUser(intent, user, 9132 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9133 } 9134 9135 private ComponentName matchComponentForVerifier(String packageName, 9136 List<ResolveInfo> receivers) { 9137 ActivityInfo targetReceiver = null; 9138 9139 final int NR = receivers.size(); 9140 for (int i = 0; i < NR; i++) { 9141 final ResolveInfo info = receivers.get(i); 9142 if (info.activityInfo == null) { 9143 continue; 9144 } 9145 9146 if (packageName.equals(info.activityInfo.packageName)) { 9147 targetReceiver = info.activityInfo; 9148 break; 9149 } 9150 } 9151 9152 if (targetReceiver == null) { 9153 return null; 9154 } 9155 9156 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9157 } 9158 9159 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9160 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9161 if (pkgInfo.verifiers.length == 0) { 9162 return null; 9163 } 9164 9165 final int N = pkgInfo.verifiers.length; 9166 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9167 for (int i = 0; i < N; i++) { 9168 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9169 9170 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9171 receivers); 9172 if (comp == null) { 9173 continue; 9174 } 9175 9176 final int verifierUid = getUidForVerifier(verifierInfo); 9177 if (verifierUid == -1) { 9178 continue; 9179 } 9180 9181 if (DEBUG_VERIFY) { 9182 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9183 + " with the correct signature"); 9184 } 9185 sufficientVerifiers.add(comp); 9186 verificationState.addSufficientVerifier(verifierUid); 9187 } 9188 9189 return sufficientVerifiers; 9190 } 9191 9192 private int getUidForVerifier(VerifierInfo verifierInfo) { 9193 synchronized (mPackages) { 9194 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9195 if (pkg == null) { 9196 return -1; 9197 } else if (pkg.mSignatures.length != 1) { 9198 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9199 + " has more than one signature; ignoring"); 9200 return -1; 9201 } 9202 9203 /* 9204 * If the public key of the package's signature does not match 9205 * our expected public key, then this is a different package and 9206 * we should skip. 9207 */ 9208 9209 final byte[] expectedPublicKey; 9210 try { 9211 final Signature verifierSig = pkg.mSignatures[0]; 9212 final PublicKey publicKey = verifierSig.getPublicKey(); 9213 expectedPublicKey = publicKey.getEncoded(); 9214 } catch (CertificateException e) { 9215 return -1; 9216 } 9217 9218 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9219 9220 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9221 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9222 + " does not have the expected public key; ignoring"); 9223 return -1; 9224 } 9225 9226 return pkg.applicationInfo.uid; 9227 } 9228 } 9229 9230 @Override 9231 public void finishPackageInstall(int token) { 9232 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9233 9234 if (DEBUG_INSTALL) { 9235 Slog.v(TAG, "BM finishing package install for " + token); 9236 } 9237 9238 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9239 mHandler.sendMessage(msg); 9240 } 9241 9242 /** 9243 * Get the verification agent timeout. 9244 * 9245 * @return verification timeout in milliseconds 9246 */ 9247 private long getVerificationTimeout() { 9248 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9249 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9250 DEFAULT_VERIFICATION_TIMEOUT); 9251 } 9252 9253 /** 9254 * Get the default verification agent response code. 9255 * 9256 * @return default verification response code 9257 */ 9258 private int getDefaultVerificationResponse() { 9259 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9260 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9261 DEFAULT_VERIFICATION_RESPONSE); 9262 } 9263 9264 /** 9265 * Check whether or not package verification has been enabled. 9266 * 9267 * @return true if verification should be performed 9268 */ 9269 private boolean isVerificationEnabled(int userId, int installFlags) { 9270 if (!DEFAULT_VERIFY_ENABLE) { 9271 return false; 9272 } 9273 9274 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9275 9276 // Check if installing from ADB 9277 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9278 // Do not run verification in a test harness environment 9279 if (ActivityManager.isRunningInTestHarness()) { 9280 return false; 9281 } 9282 if (ensureVerifyAppsEnabled) { 9283 return true; 9284 } 9285 // Check if the developer does not want package verification for ADB installs 9286 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9287 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9288 return false; 9289 } 9290 } 9291 9292 if (ensureVerifyAppsEnabled) { 9293 return true; 9294 } 9295 9296 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9297 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9298 } 9299 9300 @Override 9301 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9302 throws RemoteException { 9303 mContext.enforceCallingOrSelfPermission( 9304 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9305 "Only intentfilter verification agents can verify applications"); 9306 9307 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9308 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9309 Binder.getCallingUid(), verificationCode, failedDomains); 9310 msg.arg1 = id; 9311 msg.obj = response; 9312 mHandler.sendMessage(msg); 9313 } 9314 9315 @Override 9316 public int getIntentVerificationStatus(String packageName, int userId) { 9317 synchronized (mPackages) { 9318 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9319 } 9320 } 9321 9322 @Override 9323 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9324 boolean result = false; 9325 synchronized (mPackages) { 9326 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9327 } 9328 if (result) { 9329 scheduleWritePackageRestrictionsLocked(userId); 9330 } 9331 return result; 9332 } 9333 9334 @Override 9335 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9336 synchronized (mPackages) { 9337 return mSettings.getIntentFilterVerificationsLPr(packageName); 9338 } 9339 } 9340 9341 @Override 9342 public List<IntentFilter> getAllIntentFilters(String packageName) { 9343 if (TextUtils.isEmpty(packageName)) { 9344 return Collections.<IntentFilter>emptyList(); 9345 } 9346 synchronized (mPackages) { 9347 PackageParser.Package pkg = mPackages.get(packageName); 9348 if (pkg == null || pkg.activities == null) { 9349 return Collections.<IntentFilter>emptyList(); 9350 } 9351 final int count = pkg.activities.size(); 9352 ArrayList<IntentFilter> result = new ArrayList<>(); 9353 for (int n=0; n<count; n++) { 9354 PackageParser.Activity activity = pkg.activities.get(n); 9355 if (activity.intents != null || activity.intents.size() > 0) { 9356 result.addAll(activity.intents); 9357 } 9358 } 9359 return result; 9360 } 9361 } 9362 9363 @Override 9364 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9365 synchronized (mPackages) { 9366 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9367 if (packageName != null) { 9368 result |= updateIntentVerificationStatus(packageName, 9369 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9370 UserHandle.myUserId()); 9371 } 9372 return result; 9373 } 9374 } 9375 9376 @Override 9377 public String getDefaultBrowserPackageName(int userId) { 9378 synchronized (mPackages) { 9379 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9380 } 9381 } 9382 9383 /** 9384 * Get the "allow unknown sources" setting. 9385 * 9386 * @return the current "allow unknown sources" setting 9387 */ 9388 private int getUnknownSourcesSettings() { 9389 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9390 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9391 -1); 9392 } 9393 9394 @Override 9395 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9396 final int uid = Binder.getCallingUid(); 9397 // writer 9398 synchronized (mPackages) { 9399 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9400 if (targetPackageSetting == null) { 9401 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9402 } 9403 9404 PackageSetting installerPackageSetting; 9405 if (installerPackageName != null) { 9406 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9407 if (installerPackageSetting == null) { 9408 throw new IllegalArgumentException("Unknown installer package: " 9409 + installerPackageName); 9410 } 9411 } else { 9412 installerPackageSetting = null; 9413 } 9414 9415 Signature[] callerSignature; 9416 Object obj = mSettings.getUserIdLPr(uid); 9417 if (obj != null) { 9418 if (obj instanceof SharedUserSetting) { 9419 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9420 } else if (obj instanceof PackageSetting) { 9421 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9422 } else { 9423 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9424 } 9425 } else { 9426 throw new SecurityException("Unknown calling uid " + uid); 9427 } 9428 9429 // Verify: can't set installerPackageName to a package that is 9430 // not signed with the same cert as the caller. 9431 if (installerPackageSetting != null) { 9432 if (compareSignatures(callerSignature, 9433 installerPackageSetting.signatures.mSignatures) 9434 != PackageManager.SIGNATURE_MATCH) { 9435 throw new SecurityException( 9436 "Caller does not have same cert as new installer package " 9437 + installerPackageName); 9438 } 9439 } 9440 9441 // Verify: if target already has an installer package, it must 9442 // be signed with the same cert as the caller. 9443 if (targetPackageSetting.installerPackageName != null) { 9444 PackageSetting setting = mSettings.mPackages.get( 9445 targetPackageSetting.installerPackageName); 9446 // If the currently set package isn't valid, then it's always 9447 // okay to change it. 9448 if (setting != null) { 9449 if (compareSignatures(callerSignature, 9450 setting.signatures.mSignatures) 9451 != PackageManager.SIGNATURE_MATCH) { 9452 throw new SecurityException( 9453 "Caller does not have same cert as old installer package " 9454 + targetPackageSetting.installerPackageName); 9455 } 9456 } 9457 } 9458 9459 // Okay! 9460 targetPackageSetting.installerPackageName = installerPackageName; 9461 scheduleWriteSettingsLocked(); 9462 } 9463 } 9464 9465 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9466 // Queue up an async operation since the package installation may take a little while. 9467 mHandler.post(new Runnable() { 9468 public void run() { 9469 mHandler.removeCallbacks(this); 9470 // Result object to be returned 9471 PackageInstalledInfo res = new PackageInstalledInfo(); 9472 res.returnCode = currentStatus; 9473 res.uid = -1; 9474 res.pkg = null; 9475 res.removedInfo = new PackageRemovedInfo(); 9476 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9477 args.doPreInstall(res.returnCode); 9478 synchronized (mInstallLock) { 9479 installPackageLI(args, res); 9480 } 9481 args.doPostInstall(res.returnCode, res.uid); 9482 } 9483 9484 // A restore should be performed at this point if (a) the install 9485 // succeeded, (b) the operation is not an update, and (c) the new 9486 // package has not opted out of backup participation. 9487 final boolean update = res.removedInfo.removedPackage != null; 9488 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9489 boolean doRestore = !update 9490 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9491 9492 // Set up the post-install work request bookkeeping. This will be used 9493 // and cleaned up by the post-install event handling regardless of whether 9494 // there's a restore pass performed. Token values are >= 1. 9495 int token; 9496 if (mNextInstallToken < 0) mNextInstallToken = 1; 9497 token = mNextInstallToken++; 9498 9499 PostInstallData data = new PostInstallData(args, res); 9500 mRunningInstalls.put(token, data); 9501 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9502 9503 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9504 // Pass responsibility to the Backup Manager. It will perform a 9505 // restore if appropriate, then pass responsibility back to the 9506 // Package Manager to run the post-install observer callbacks 9507 // and broadcasts. 9508 IBackupManager bm = IBackupManager.Stub.asInterface( 9509 ServiceManager.getService(Context.BACKUP_SERVICE)); 9510 if (bm != null) { 9511 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9512 + " to BM for possible restore"); 9513 try { 9514 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9515 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9516 } else { 9517 doRestore = false; 9518 } 9519 } catch (RemoteException e) { 9520 // can't happen; the backup manager is local 9521 } catch (Exception e) { 9522 Slog.e(TAG, "Exception trying to enqueue restore", e); 9523 doRestore = false; 9524 } 9525 } else { 9526 Slog.e(TAG, "Backup Manager not found!"); 9527 doRestore = false; 9528 } 9529 } 9530 9531 if (!doRestore) { 9532 // No restore possible, or the Backup Manager was mysteriously not 9533 // available -- just fire the post-install work request directly. 9534 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9535 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9536 mHandler.sendMessage(msg); 9537 } 9538 } 9539 }); 9540 } 9541 9542 private abstract class HandlerParams { 9543 private static final int MAX_RETRIES = 4; 9544 9545 /** 9546 * Number of times startCopy() has been attempted and had a non-fatal 9547 * error. 9548 */ 9549 private int mRetries = 0; 9550 9551 /** User handle for the user requesting the information or installation. */ 9552 private final UserHandle mUser; 9553 9554 HandlerParams(UserHandle user) { 9555 mUser = user; 9556 } 9557 9558 UserHandle getUser() { 9559 return mUser; 9560 } 9561 9562 final boolean startCopy() { 9563 boolean res; 9564 try { 9565 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9566 9567 if (++mRetries > MAX_RETRIES) { 9568 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9569 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9570 handleServiceError(); 9571 return false; 9572 } else { 9573 handleStartCopy(); 9574 res = true; 9575 } 9576 } catch (RemoteException e) { 9577 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9578 mHandler.sendEmptyMessage(MCS_RECONNECT); 9579 res = false; 9580 } 9581 handleReturnCode(); 9582 return res; 9583 } 9584 9585 final void serviceError() { 9586 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9587 handleServiceError(); 9588 handleReturnCode(); 9589 } 9590 9591 abstract void handleStartCopy() throws RemoteException; 9592 abstract void handleServiceError(); 9593 abstract void handleReturnCode(); 9594 } 9595 9596 class MeasureParams extends HandlerParams { 9597 private final PackageStats mStats; 9598 private boolean mSuccess; 9599 9600 private final IPackageStatsObserver mObserver; 9601 9602 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9603 super(new UserHandle(stats.userHandle)); 9604 mObserver = observer; 9605 mStats = stats; 9606 } 9607 9608 @Override 9609 public String toString() { 9610 return "MeasureParams{" 9611 + Integer.toHexString(System.identityHashCode(this)) 9612 + " " + mStats.packageName + "}"; 9613 } 9614 9615 @Override 9616 void handleStartCopy() throws RemoteException { 9617 synchronized (mInstallLock) { 9618 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9619 } 9620 9621 if (mSuccess) { 9622 final boolean mounted; 9623 if (Environment.isExternalStorageEmulated()) { 9624 mounted = true; 9625 } else { 9626 final String status = Environment.getExternalStorageState(); 9627 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9628 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9629 } 9630 9631 if (mounted) { 9632 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9633 9634 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9635 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9636 9637 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9638 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9639 9640 // Always subtract cache size, since it's a subdirectory 9641 mStats.externalDataSize -= mStats.externalCacheSize; 9642 9643 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9644 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9645 9646 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9647 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9648 } 9649 } 9650 } 9651 9652 @Override 9653 void handleReturnCode() { 9654 if (mObserver != null) { 9655 try { 9656 mObserver.onGetStatsCompleted(mStats, mSuccess); 9657 } catch (RemoteException e) { 9658 Slog.i(TAG, "Observer no longer exists."); 9659 } 9660 } 9661 } 9662 9663 @Override 9664 void handleServiceError() { 9665 Slog.e(TAG, "Could not measure application " + mStats.packageName 9666 + " external storage"); 9667 } 9668 } 9669 9670 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9671 throws RemoteException { 9672 long result = 0; 9673 for (File path : paths) { 9674 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9675 } 9676 return result; 9677 } 9678 9679 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9680 for (File path : paths) { 9681 try { 9682 mcs.clearDirectory(path.getAbsolutePath()); 9683 } catch (RemoteException e) { 9684 } 9685 } 9686 } 9687 9688 static class OriginInfo { 9689 /** 9690 * Location where install is coming from, before it has been 9691 * copied/renamed into place. This could be a single monolithic APK 9692 * file, or a cluster directory. This location may be untrusted. 9693 */ 9694 final File file; 9695 final String cid; 9696 9697 /** 9698 * Flag indicating that {@link #file} or {@link #cid} has already been 9699 * staged, meaning downstream users don't need to defensively copy the 9700 * contents. 9701 */ 9702 final boolean staged; 9703 9704 /** 9705 * Flag indicating that {@link #file} or {@link #cid} is an already 9706 * installed app that is being moved. 9707 */ 9708 final boolean existing; 9709 9710 final String resolvedPath; 9711 final File resolvedFile; 9712 9713 static OriginInfo fromNothing() { 9714 return new OriginInfo(null, null, false, false); 9715 } 9716 9717 static OriginInfo fromUntrustedFile(File file) { 9718 return new OriginInfo(file, null, false, false); 9719 } 9720 9721 static OriginInfo fromExistingFile(File file) { 9722 return new OriginInfo(file, null, false, true); 9723 } 9724 9725 static OriginInfo fromStagedFile(File file) { 9726 return new OriginInfo(file, null, true, false); 9727 } 9728 9729 static OriginInfo fromStagedContainer(String cid) { 9730 return new OriginInfo(null, cid, true, false); 9731 } 9732 9733 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9734 this.file = file; 9735 this.cid = cid; 9736 this.staged = staged; 9737 this.existing = existing; 9738 9739 if (cid != null) { 9740 resolvedPath = PackageHelper.getSdDir(cid); 9741 resolvedFile = new File(resolvedPath); 9742 } else if (file != null) { 9743 resolvedPath = file.getAbsolutePath(); 9744 resolvedFile = file; 9745 } else { 9746 resolvedPath = null; 9747 resolvedFile = null; 9748 } 9749 } 9750 } 9751 9752 class MoveInfo { 9753 final int moveId; 9754 final String fromUuid; 9755 final String toUuid; 9756 final String packageName; 9757 final String dataAppName; 9758 final int appId; 9759 final String seinfo; 9760 9761 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9762 String dataAppName, int appId, String seinfo) { 9763 this.moveId = moveId; 9764 this.fromUuid = fromUuid; 9765 this.toUuid = toUuid; 9766 this.packageName = packageName; 9767 this.dataAppName = dataAppName; 9768 this.appId = appId; 9769 this.seinfo = seinfo; 9770 } 9771 } 9772 9773 class InstallParams extends HandlerParams { 9774 final OriginInfo origin; 9775 final MoveInfo move; 9776 final IPackageInstallObserver2 observer; 9777 int installFlags; 9778 final String installerPackageName; 9779 final String volumeUuid; 9780 final VerificationParams verificationParams; 9781 private InstallArgs mArgs; 9782 private int mRet; 9783 final String packageAbiOverride; 9784 9785 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9786 int installFlags, String installerPackageName, String volumeUuid, 9787 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9788 super(user); 9789 this.origin = origin; 9790 this.move = move; 9791 this.observer = observer; 9792 this.installFlags = installFlags; 9793 this.installerPackageName = installerPackageName; 9794 this.volumeUuid = volumeUuid; 9795 this.verificationParams = verificationParams; 9796 this.packageAbiOverride = packageAbiOverride; 9797 } 9798 9799 @Override 9800 public String toString() { 9801 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9802 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9803 } 9804 9805 public ManifestDigest getManifestDigest() { 9806 if (verificationParams == null) { 9807 return null; 9808 } 9809 return verificationParams.getManifestDigest(); 9810 } 9811 9812 private int installLocationPolicy(PackageInfoLite pkgLite) { 9813 String packageName = pkgLite.packageName; 9814 int installLocation = pkgLite.installLocation; 9815 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9816 // reader 9817 synchronized (mPackages) { 9818 PackageParser.Package pkg = mPackages.get(packageName); 9819 if (pkg != null) { 9820 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9821 // Check for downgrading. 9822 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9823 try { 9824 checkDowngrade(pkg, pkgLite); 9825 } catch (PackageManagerException e) { 9826 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9827 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9828 } 9829 } 9830 // Check for updated system application. 9831 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9832 if (onSd) { 9833 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9834 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9835 } 9836 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9837 } else { 9838 if (onSd) { 9839 // Install flag overrides everything. 9840 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9841 } 9842 // If current upgrade specifies particular preference 9843 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9844 // Application explicitly specified internal. 9845 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9846 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9847 // App explictly prefers external. Let policy decide 9848 } else { 9849 // Prefer previous location 9850 if (isExternal(pkg)) { 9851 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9852 } 9853 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9854 } 9855 } 9856 } else { 9857 // Invalid install. Return error code 9858 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9859 } 9860 } 9861 } 9862 // All the special cases have been taken care of. 9863 // Return result based on recommended install location. 9864 if (onSd) { 9865 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9866 } 9867 return pkgLite.recommendedInstallLocation; 9868 } 9869 9870 /* 9871 * Invoke remote method to get package information and install 9872 * location values. Override install location based on default 9873 * policy if needed and then create install arguments based 9874 * on the install location. 9875 */ 9876 public void handleStartCopy() throws RemoteException { 9877 int ret = PackageManager.INSTALL_SUCCEEDED; 9878 9879 // If we're already staged, we've firmly committed to an install location 9880 if (origin.staged) { 9881 if (origin.file != null) { 9882 installFlags |= PackageManager.INSTALL_INTERNAL; 9883 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9884 } else if (origin.cid != null) { 9885 installFlags |= PackageManager.INSTALL_EXTERNAL; 9886 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9887 } else { 9888 throw new IllegalStateException("Invalid stage location"); 9889 } 9890 } 9891 9892 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9893 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9894 9895 PackageInfoLite pkgLite = null; 9896 9897 if (onInt && onSd) { 9898 // Check if both bits are set. 9899 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9900 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9901 } else { 9902 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9903 packageAbiOverride); 9904 9905 /* 9906 * If we have too little free space, try to free cache 9907 * before giving up. 9908 */ 9909 if (!origin.staged && pkgLite.recommendedInstallLocation 9910 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9911 // TODO: focus freeing disk space on the target device 9912 final StorageManager storage = StorageManager.from(mContext); 9913 final long lowThreshold = storage.getStorageLowBytes( 9914 Environment.getDataDirectory()); 9915 9916 final long sizeBytes = mContainerService.calculateInstalledSize( 9917 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9918 9919 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9920 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9921 installFlags, packageAbiOverride); 9922 } 9923 9924 /* 9925 * The cache free must have deleted the file we 9926 * downloaded to install. 9927 * 9928 * TODO: fix the "freeCache" call to not delete 9929 * the file we care about. 9930 */ 9931 if (pkgLite.recommendedInstallLocation 9932 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9933 pkgLite.recommendedInstallLocation 9934 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9935 } 9936 } 9937 } 9938 9939 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9940 int loc = pkgLite.recommendedInstallLocation; 9941 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9942 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9943 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9944 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9945 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9946 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9947 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9948 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9949 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9950 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9951 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9952 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9953 } else { 9954 // Override with defaults if needed. 9955 loc = installLocationPolicy(pkgLite); 9956 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9957 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9958 } else if (!onSd && !onInt) { 9959 // Override install location with flags 9960 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9961 // Set the flag to install on external media. 9962 installFlags |= PackageManager.INSTALL_EXTERNAL; 9963 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9964 } else { 9965 // Make sure the flag for installing on external 9966 // media is unset 9967 installFlags |= PackageManager.INSTALL_INTERNAL; 9968 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9969 } 9970 } 9971 } 9972 } 9973 9974 final InstallArgs args = createInstallArgs(this); 9975 mArgs = args; 9976 9977 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9978 /* 9979 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9980 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9981 */ 9982 int userIdentifier = getUser().getIdentifier(); 9983 if (userIdentifier == UserHandle.USER_ALL 9984 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9985 userIdentifier = UserHandle.USER_OWNER; 9986 } 9987 9988 /* 9989 * Determine if we have any installed package verifiers. If we 9990 * do, then we'll defer to them to verify the packages. 9991 */ 9992 final int requiredUid = mRequiredVerifierPackage == null ? -1 9993 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9994 if (!origin.existing && requiredUid != -1 9995 && isVerificationEnabled(userIdentifier, installFlags)) { 9996 final Intent verification = new Intent( 9997 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9998 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9999 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10000 PACKAGE_MIME_TYPE); 10001 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10002 10003 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10004 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10005 0 /* TODO: Which userId? */); 10006 10007 if (DEBUG_VERIFY) { 10008 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10009 + verification.toString() + " with " + pkgLite.verifiers.length 10010 + " optional verifiers"); 10011 } 10012 10013 final int verificationId = mPendingVerificationToken++; 10014 10015 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10016 10017 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10018 installerPackageName); 10019 10020 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10021 installFlags); 10022 10023 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10024 pkgLite.packageName); 10025 10026 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10027 pkgLite.versionCode); 10028 10029 if (verificationParams != null) { 10030 if (verificationParams.getVerificationURI() != null) { 10031 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10032 verificationParams.getVerificationURI()); 10033 } 10034 if (verificationParams.getOriginatingURI() != null) { 10035 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10036 verificationParams.getOriginatingURI()); 10037 } 10038 if (verificationParams.getReferrer() != null) { 10039 verification.putExtra(Intent.EXTRA_REFERRER, 10040 verificationParams.getReferrer()); 10041 } 10042 if (verificationParams.getOriginatingUid() >= 0) { 10043 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10044 verificationParams.getOriginatingUid()); 10045 } 10046 if (verificationParams.getInstallerUid() >= 0) { 10047 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10048 verificationParams.getInstallerUid()); 10049 } 10050 } 10051 10052 final PackageVerificationState verificationState = new PackageVerificationState( 10053 requiredUid, args); 10054 10055 mPendingVerification.append(verificationId, verificationState); 10056 10057 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10058 receivers, verificationState); 10059 10060 /* 10061 * If any sufficient verifiers were listed in the package 10062 * manifest, attempt to ask them. 10063 */ 10064 if (sufficientVerifiers != null) { 10065 final int N = sufficientVerifiers.size(); 10066 if (N == 0) { 10067 Slog.i(TAG, "Additional verifiers required, but none installed."); 10068 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10069 } else { 10070 for (int i = 0; i < N; i++) { 10071 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10072 10073 final Intent sufficientIntent = new Intent(verification); 10074 sufficientIntent.setComponent(verifierComponent); 10075 10076 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10077 } 10078 } 10079 } 10080 10081 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10082 mRequiredVerifierPackage, receivers); 10083 if (ret == PackageManager.INSTALL_SUCCEEDED 10084 && mRequiredVerifierPackage != null) { 10085 /* 10086 * Send the intent to the required verification agent, 10087 * but only start the verification timeout after the 10088 * target BroadcastReceivers have run. 10089 */ 10090 verification.setComponent(requiredVerifierComponent); 10091 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10092 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10093 new BroadcastReceiver() { 10094 @Override 10095 public void onReceive(Context context, Intent intent) { 10096 final Message msg = mHandler 10097 .obtainMessage(CHECK_PENDING_VERIFICATION); 10098 msg.arg1 = verificationId; 10099 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10100 } 10101 }, null, 0, null, null); 10102 10103 /* 10104 * We don't want the copy to proceed until verification 10105 * succeeds, so null out this field. 10106 */ 10107 mArgs = null; 10108 } 10109 } else { 10110 /* 10111 * No package verification is enabled, so immediately start 10112 * the remote call to initiate copy using temporary file. 10113 */ 10114 ret = args.copyApk(mContainerService, true); 10115 } 10116 } 10117 10118 mRet = ret; 10119 } 10120 10121 @Override 10122 void handleReturnCode() { 10123 // If mArgs is null, then MCS couldn't be reached. When it 10124 // reconnects, it will try again to install. At that point, this 10125 // will succeed. 10126 if (mArgs != null) { 10127 processPendingInstall(mArgs, mRet); 10128 } 10129 } 10130 10131 @Override 10132 void handleServiceError() { 10133 mArgs = createInstallArgs(this); 10134 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10135 } 10136 10137 public boolean isForwardLocked() { 10138 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10139 } 10140 } 10141 10142 /** 10143 * Used during creation of InstallArgs 10144 * 10145 * @param installFlags package installation flags 10146 * @return true if should be installed on external storage 10147 */ 10148 private static boolean installOnExternalAsec(int installFlags) { 10149 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10150 return false; 10151 } 10152 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10153 return true; 10154 } 10155 return false; 10156 } 10157 10158 /** 10159 * Used during creation of InstallArgs 10160 * 10161 * @param installFlags package installation flags 10162 * @return true if should be installed as forward locked 10163 */ 10164 private static boolean installForwardLocked(int installFlags) { 10165 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10166 } 10167 10168 private InstallArgs createInstallArgs(InstallParams params) { 10169 if (params.move != null) { 10170 return new MoveInstallArgs(params); 10171 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10172 return new AsecInstallArgs(params); 10173 } else { 10174 return new FileInstallArgs(params); 10175 } 10176 } 10177 10178 /** 10179 * Create args that describe an existing installed package. Typically used 10180 * when cleaning up old installs, or used as a move source. 10181 */ 10182 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10183 String resourcePath, String[] instructionSets) { 10184 final boolean isInAsec; 10185 if (installOnExternalAsec(installFlags)) { 10186 /* Apps on SD card are always in ASEC containers. */ 10187 isInAsec = true; 10188 } else if (installForwardLocked(installFlags) 10189 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10190 /* 10191 * Forward-locked apps are only in ASEC containers if they're the 10192 * new style 10193 */ 10194 isInAsec = true; 10195 } else { 10196 isInAsec = false; 10197 } 10198 10199 if (isInAsec) { 10200 return new AsecInstallArgs(codePath, instructionSets, 10201 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10202 } else { 10203 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10204 } 10205 } 10206 10207 static abstract class InstallArgs { 10208 /** @see InstallParams#origin */ 10209 final OriginInfo origin; 10210 /** @see InstallParams#move */ 10211 final MoveInfo move; 10212 10213 final IPackageInstallObserver2 observer; 10214 // Always refers to PackageManager flags only 10215 final int installFlags; 10216 final String installerPackageName; 10217 final String volumeUuid; 10218 final ManifestDigest manifestDigest; 10219 final UserHandle user; 10220 final String abiOverride; 10221 10222 // The list of instruction sets supported by this app. This is currently 10223 // only used during the rmdex() phase to clean up resources. We can get rid of this 10224 // if we move dex files under the common app path. 10225 /* nullable */ String[] instructionSets; 10226 10227 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10228 int installFlags, String installerPackageName, String volumeUuid, 10229 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10230 String abiOverride) { 10231 this.origin = origin; 10232 this.move = move; 10233 this.installFlags = installFlags; 10234 this.observer = observer; 10235 this.installerPackageName = installerPackageName; 10236 this.volumeUuid = volumeUuid; 10237 this.manifestDigest = manifestDigest; 10238 this.user = user; 10239 this.instructionSets = instructionSets; 10240 this.abiOverride = abiOverride; 10241 } 10242 10243 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10244 abstract int doPreInstall(int status); 10245 10246 /** 10247 * Rename package into final resting place. All paths on the given 10248 * scanned package should be updated to reflect the rename. 10249 */ 10250 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10251 abstract int doPostInstall(int status, int uid); 10252 10253 /** @see PackageSettingBase#codePathString */ 10254 abstract String getCodePath(); 10255 /** @see PackageSettingBase#resourcePathString */ 10256 abstract String getResourcePath(); 10257 10258 // Need installer lock especially for dex file removal. 10259 abstract void cleanUpResourcesLI(); 10260 abstract boolean doPostDeleteLI(boolean delete); 10261 10262 /** 10263 * Called before the source arguments are copied. This is used mostly 10264 * for MoveParams when it needs to read the source file to put it in the 10265 * destination. 10266 */ 10267 int doPreCopy() { 10268 return PackageManager.INSTALL_SUCCEEDED; 10269 } 10270 10271 /** 10272 * Called after the source arguments are copied. This is used mostly for 10273 * MoveParams when it needs to read the source file to put it in the 10274 * destination. 10275 * 10276 * @return 10277 */ 10278 int doPostCopy(int uid) { 10279 return PackageManager.INSTALL_SUCCEEDED; 10280 } 10281 10282 protected boolean isFwdLocked() { 10283 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10284 } 10285 10286 protected boolean isExternalAsec() { 10287 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10288 } 10289 10290 UserHandle getUser() { 10291 return user; 10292 } 10293 } 10294 10295 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10296 if (!allCodePaths.isEmpty()) { 10297 if (instructionSets == null) { 10298 throw new IllegalStateException("instructionSet == null"); 10299 } 10300 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10301 for (String codePath : allCodePaths) { 10302 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10303 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10304 if (retCode < 0) { 10305 Slog.w(TAG, "Couldn't remove dex file for package: " 10306 + " at location " + codePath + ", retcode=" + retCode); 10307 // we don't consider this to be a failure of the core package deletion 10308 } 10309 } 10310 } 10311 } 10312 } 10313 10314 /** 10315 * Logic to handle installation of non-ASEC applications, including copying 10316 * and renaming logic. 10317 */ 10318 class FileInstallArgs extends InstallArgs { 10319 private File codeFile; 10320 private File resourceFile; 10321 10322 // Example topology: 10323 // /data/app/com.example/base.apk 10324 // /data/app/com.example/split_foo.apk 10325 // /data/app/com.example/lib/arm/libfoo.so 10326 // /data/app/com.example/lib/arm64/libfoo.so 10327 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10328 10329 /** New install */ 10330 FileInstallArgs(InstallParams params) { 10331 super(params.origin, params.move, params.observer, params.installFlags, 10332 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10333 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10334 if (isFwdLocked()) { 10335 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10336 } 10337 } 10338 10339 /** Existing install */ 10340 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10341 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10342 null); 10343 this.codeFile = (codePath != null) ? new File(codePath) : null; 10344 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10345 } 10346 10347 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10348 if (origin.staged) { 10349 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10350 codeFile = origin.file; 10351 resourceFile = origin.file; 10352 return PackageManager.INSTALL_SUCCEEDED; 10353 } 10354 10355 try { 10356 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10357 codeFile = tempDir; 10358 resourceFile = tempDir; 10359 } catch (IOException e) { 10360 Slog.w(TAG, "Failed to create copy file: " + e); 10361 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10362 } 10363 10364 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10365 @Override 10366 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10367 if (!FileUtils.isValidExtFilename(name)) { 10368 throw new IllegalArgumentException("Invalid filename: " + name); 10369 } 10370 try { 10371 final File file = new File(codeFile, name); 10372 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10373 O_RDWR | O_CREAT, 0644); 10374 Os.chmod(file.getAbsolutePath(), 0644); 10375 return new ParcelFileDescriptor(fd); 10376 } catch (ErrnoException e) { 10377 throw new RemoteException("Failed to open: " + e.getMessage()); 10378 } 10379 } 10380 }; 10381 10382 int ret = PackageManager.INSTALL_SUCCEEDED; 10383 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10384 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10385 Slog.e(TAG, "Failed to copy package"); 10386 return ret; 10387 } 10388 10389 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10390 NativeLibraryHelper.Handle handle = null; 10391 try { 10392 handle = NativeLibraryHelper.Handle.create(codeFile); 10393 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10394 abiOverride); 10395 } catch (IOException e) { 10396 Slog.e(TAG, "Copying native libraries failed", e); 10397 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10398 } finally { 10399 IoUtils.closeQuietly(handle); 10400 } 10401 10402 return ret; 10403 } 10404 10405 int doPreInstall(int status) { 10406 if (status != PackageManager.INSTALL_SUCCEEDED) { 10407 cleanUp(); 10408 } 10409 return status; 10410 } 10411 10412 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10413 if (status != PackageManager.INSTALL_SUCCEEDED) { 10414 cleanUp(); 10415 return false; 10416 } 10417 10418 final File targetDir = codeFile.getParentFile(); 10419 final File beforeCodeFile = codeFile; 10420 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10421 10422 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10423 try { 10424 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10425 } catch (ErrnoException e) { 10426 Slog.d(TAG, "Failed to rename", e); 10427 return false; 10428 } 10429 10430 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10431 Slog.d(TAG, "Failed to restorecon"); 10432 return false; 10433 } 10434 10435 // Reflect the rename internally 10436 codeFile = afterCodeFile; 10437 resourceFile = afterCodeFile; 10438 10439 // Reflect the rename in scanned details 10440 pkg.codePath = afterCodeFile.getAbsolutePath(); 10441 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10442 pkg.baseCodePath); 10443 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10444 pkg.splitCodePaths); 10445 10446 // Reflect the rename in app info 10447 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10448 pkg.applicationInfo.setCodePath(pkg.codePath); 10449 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10450 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10451 pkg.applicationInfo.setResourcePath(pkg.codePath); 10452 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10453 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10454 10455 return true; 10456 } 10457 10458 int doPostInstall(int status, int uid) { 10459 if (status != PackageManager.INSTALL_SUCCEEDED) { 10460 cleanUp(); 10461 } 10462 return status; 10463 } 10464 10465 @Override 10466 String getCodePath() { 10467 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10468 } 10469 10470 @Override 10471 String getResourcePath() { 10472 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10473 } 10474 10475 private boolean cleanUp() { 10476 if (codeFile == null || !codeFile.exists()) { 10477 return false; 10478 } 10479 10480 if (codeFile.isDirectory()) { 10481 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10482 } else { 10483 codeFile.delete(); 10484 } 10485 10486 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10487 resourceFile.delete(); 10488 } 10489 10490 return true; 10491 } 10492 10493 void cleanUpResourcesLI() { 10494 // Try enumerating all code paths before deleting 10495 List<String> allCodePaths = Collections.EMPTY_LIST; 10496 if (codeFile != null && codeFile.exists()) { 10497 try { 10498 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10499 allCodePaths = pkg.getAllCodePaths(); 10500 } catch (PackageParserException e) { 10501 // Ignored; we tried our best 10502 } 10503 } 10504 10505 cleanUp(); 10506 removeDexFiles(allCodePaths, instructionSets); 10507 } 10508 10509 boolean doPostDeleteLI(boolean delete) { 10510 // XXX err, shouldn't we respect the delete flag? 10511 cleanUpResourcesLI(); 10512 return true; 10513 } 10514 } 10515 10516 private boolean isAsecExternal(String cid) { 10517 final String asecPath = PackageHelper.getSdFilesystem(cid); 10518 return !asecPath.startsWith(mAsecInternalPath); 10519 } 10520 10521 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10522 PackageManagerException { 10523 if (copyRet < 0) { 10524 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10525 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10526 throw new PackageManagerException(copyRet, message); 10527 } 10528 } 10529 } 10530 10531 /** 10532 * Extract the MountService "container ID" from the full code path of an 10533 * .apk. 10534 */ 10535 static String cidFromCodePath(String fullCodePath) { 10536 int eidx = fullCodePath.lastIndexOf("/"); 10537 String subStr1 = fullCodePath.substring(0, eidx); 10538 int sidx = subStr1.lastIndexOf("/"); 10539 return subStr1.substring(sidx+1, eidx); 10540 } 10541 10542 /** 10543 * Logic to handle installation of ASEC applications, including copying and 10544 * renaming logic. 10545 */ 10546 class AsecInstallArgs extends InstallArgs { 10547 static final String RES_FILE_NAME = "pkg.apk"; 10548 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10549 10550 String cid; 10551 String packagePath; 10552 String resourcePath; 10553 10554 /** New install */ 10555 AsecInstallArgs(InstallParams params) { 10556 super(params.origin, params.move, params.observer, params.installFlags, 10557 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10558 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10559 } 10560 10561 /** Existing install */ 10562 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10563 boolean isExternal, boolean isForwardLocked) { 10564 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10565 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10566 instructionSets, null); 10567 // Hackily pretend we're still looking at a full code path 10568 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10569 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10570 } 10571 10572 // Extract cid from fullCodePath 10573 int eidx = fullCodePath.lastIndexOf("/"); 10574 String subStr1 = fullCodePath.substring(0, eidx); 10575 int sidx = subStr1.lastIndexOf("/"); 10576 cid = subStr1.substring(sidx+1, eidx); 10577 setMountPath(subStr1); 10578 } 10579 10580 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10581 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10582 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10583 instructionSets, null); 10584 this.cid = cid; 10585 setMountPath(PackageHelper.getSdDir(cid)); 10586 } 10587 10588 void createCopyFile() { 10589 cid = mInstallerService.allocateExternalStageCidLegacy(); 10590 } 10591 10592 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10593 if (origin.staged) { 10594 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10595 cid = origin.cid; 10596 setMountPath(PackageHelper.getSdDir(cid)); 10597 return PackageManager.INSTALL_SUCCEEDED; 10598 } 10599 10600 if (temp) { 10601 createCopyFile(); 10602 } else { 10603 /* 10604 * Pre-emptively destroy the container since it's destroyed if 10605 * copying fails due to it existing anyway. 10606 */ 10607 PackageHelper.destroySdDir(cid); 10608 } 10609 10610 final String newMountPath = imcs.copyPackageToContainer( 10611 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10612 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10613 10614 if (newMountPath != null) { 10615 setMountPath(newMountPath); 10616 return PackageManager.INSTALL_SUCCEEDED; 10617 } else { 10618 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10619 } 10620 } 10621 10622 @Override 10623 String getCodePath() { 10624 return packagePath; 10625 } 10626 10627 @Override 10628 String getResourcePath() { 10629 return resourcePath; 10630 } 10631 10632 int doPreInstall(int status) { 10633 if (status != PackageManager.INSTALL_SUCCEEDED) { 10634 // Destroy container 10635 PackageHelper.destroySdDir(cid); 10636 } else { 10637 boolean mounted = PackageHelper.isContainerMounted(cid); 10638 if (!mounted) { 10639 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10640 Process.SYSTEM_UID); 10641 if (newMountPath != null) { 10642 setMountPath(newMountPath); 10643 } else { 10644 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10645 } 10646 } 10647 } 10648 return status; 10649 } 10650 10651 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10652 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10653 String newMountPath = null; 10654 if (PackageHelper.isContainerMounted(cid)) { 10655 // Unmount the container 10656 if (!PackageHelper.unMountSdDir(cid)) { 10657 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10658 return false; 10659 } 10660 } 10661 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10662 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10663 " which might be stale. Will try to clean up."); 10664 // Clean up the stale container and proceed to recreate. 10665 if (!PackageHelper.destroySdDir(newCacheId)) { 10666 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10667 return false; 10668 } 10669 // Successfully cleaned up stale container. Try to rename again. 10670 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10671 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10672 + " inspite of cleaning it up."); 10673 return false; 10674 } 10675 } 10676 if (!PackageHelper.isContainerMounted(newCacheId)) { 10677 Slog.w(TAG, "Mounting container " + newCacheId); 10678 newMountPath = PackageHelper.mountSdDir(newCacheId, 10679 getEncryptKey(), Process.SYSTEM_UID); 10680 } else { 10681 newMountPath = PackageHelper.getSdDir(newCacheId); 10682 } 10683 if (newMountPath == null) { 10684 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10685 return false; 10686 } 10687 Log.i(TAG, "Succesfully renamed " + cid + 10688 " to " + newCacheId + 10689 " at new path: " + newMountPath); 10690 cid = newCacheId; 10691 10692 final File beforeCodeFile = new File(packagePath); 10693 setMountPath(newMountPath); 10694 final File afterCodeFile = new File(packagePath); 10695 10696 // Reflect the rename in scanned details 10697 pkg.codePath = afterCodeFile.getAbsolutePath(); 10698 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10699 pkg.baseCodePath); 10700 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10701 pkg.splitCodePaths); 10702 10703 // Reflect the rename in app info 10704 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10705 pkg.applicationInfo.setCodePath(pkg.codePath); 10706 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10707 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10708 pkg.applicationInfo.setResourcePath(pkg.codePath); 10709 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10710 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10711 10712 return true; 10713 } 10714 10715 private void setMountPath(String mountPath) { 10716 final File mountFile = new File(mountPath); 10717 10718 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10719 if (monolithicFile.exists()) { 10720 packagePath = monolithicFile.getAbsolutePath(); 10721 if (isFwdLocked()) { 10722 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10723 } else { 10724 resourcePath = packagePath; 10725 } 10726 } else { 10727 packagePath = mountFile.getAbsolutePath(); 10728 resourcePath = packagePath; 10729 } 10730 } 10731 10732 int doPostInstall(int status, int uid) { 10733 if (status != PackageManager.INSTALL_SUCCEEDED) { 10734 cleanUp(); 10735 } else { 10736 final int groupOwner; 10737 final String protectedFile; 10738 if (isFwdLocked()) { 10739 groupOwner = UserHandle.getSharedAppGid(uid); 10740 protectedFile = RES_FILE_NAME; 10741 } else { 10742 groupOwner = -1; 10743 protectedFile = null; 10744 } 10745 10746 if (uid < Process.FIRST_APPLICATION_UID 10747 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10748 Slog.e(TAG, "Failed to finalize " + cid); 10749 PackageHelper.destroySdDir(cid); 10750 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10751 } 10752 10753 boolean mounted = PackageHelper.isContainerMounted(cid); 10754 if (!mounted) { 10755 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10756 } 10757 } 10758 return status; 10759 } 10760 10761 private void cleanUp() { 10762 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10763 10764 // Destroy secure container 10765 PackageHelper.destroySdDir(cid); 10766 } 10767 10768 private List<String> getAllCodePaths() { 10769 final File codeFile = new File(getCodePath()); 10770 if (codeFile != null && codeFile.exists()) { 10771 try { 10772 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10773 return pkg.getAllCodePaths(); 10774 } catch (PackageParserException e) { 10775 // Ignored; we tried our best 10776 } 10777 } 10778 return Collections.EMPTY_LIST; 10779 } 10780 10781 void cleanUpResourcesLI() { 10782 // Enumerate all code paths before deleting 10783 cleanUpResourcesLI(getAllCodePaths()); 10784 } 10785 10786 private void cleanUpResourcesLI(List<String> allCodePaths) { 10787 cleanUp(); 10788 removeDexFiles(allCodePaths, instructionSets); 10789 } 10790 10791 String getPackageName() { 10792 return getAsecPackageName(cid); 10793 } 10794 10795 boolean doPostDeleteLI(boolean delete) { 10796 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10797 final List<String> allCodePaths = getAllCodePaths(); 10798 boolean mounted = PackageHelper.isContainerMounted(cid); 10799 if (mounted) { 10800 // Unmount first 10801 if (PackageHelper.unMountSdDir(cid)) { 10802 mounted = false; 10803 } 10804 } 10805 if (!mounted && delete) { 10806 cleanUpResourcesLI(allCodePaths); 10807 } 10808 return !mounted; 10809 } 10810 10811 @Override 10812 int doPreCopy() { 10813 if (isFwdLocked()) { 10814 if (!PackageHelper.fixSdPermissions(cid, 10815 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10816 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10817 } 10818 } 10819 10820 return PackageManager.INSTALL_SUCCEEDED; 10821 } 10822 10823 @Override 10824 int doPostCopy(int uid) { 10825 if (isFwdLocked()) { 10826 if (uid < Process.FIRST_APPLICATION_UID 10827 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10828 RES_FILE_NAME)) { 10829 Slog.e(TAG, "Failed to finalize " + cid); 10830 PackageHelper.destroySdDir(cid); 10831 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10832 } 10833 } 10834 10835 return PackageManager.INSTALL_SUCCEEDED; 10836 } 10837 } 10838 10839 /** 10840 * Logic to handle movement of existing installed applications. 10841 */ 10842 class MoveInstallArgs extends InstallArgs { 10843 private File codeFile; 10844 private File resourceFile; 10845 10846 /** New install */ 10847 MoveInstallArgs(InstallParams params) { 10848 super(params.origin, params.move, params.observer, params.installFlags, 10849 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10850 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10851 } 10852 10853 int copyApk(IMediaContainerService imcs, boolean temp) { 10854 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10855 + move.toUuid); 10856 synchronized (mInstaller) { 10857 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10858 move.dataAppName, move.appId, move.seinfo) != 0) { 10859 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10860 } 10861 } 10862 10863 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10864 resourceFile = codeFile; 10865 Slog.d(TAG, "codeFile after move is " + codeFile); 10866 10867 return PackageManager.INSTALL_SUCCEEDED; 10868 } 10869 10870 int doPreInstall(int status) { 10871 if (status != PackageManager.INSTALL_SUCCEEDED) { 10872 cleanUp(); 10873 } 10874 return status; 10875 } 10876 10877 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10878 if (status != PackageManager.INSTALL_SUCCEEDED) { 10879 cleanUp(); 10880 return false; 10881 } 10882 10883 // Reflect the move in app info 10884 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10885 pkg.applicationInfo.setCodePath(pkg.codePath); 10886 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10887 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10888 pkg.applicationInfo.setResourcePath(pkg.codePath); 10889 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10890 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10891 10892 return true; 10893 } 10894 10895 int doPostInstall(int status, int uid) { 10896 if (status != PackageManager.INSTALL_SUCCEEDED) { 10897 cleanUp(); 10898 } 10899 return status; 10900 } 10901 10902 @Override 10903 String getCodePath() { 10904 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10905 } 10906 10907 @Override 10908 String getResourcePath() { 10909 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10910 } 10911 10912 private boolean cleanUp() { 10913 if (codeFile == null || !codeFile.exists()) { 10914 return false; 10915 } 10916 10917 if (codeFile.isDirectory()) { 10918 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10919 } else { 10920 codeFile.delete(); 10921 } 10922 10923 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10924 resourceFile.delete(); 10925 } 10926 10927 return true; 10928 } 10929 10930 void cleanUpResourcesLI() { 10931 cleanUp(); 10932 } 10933 10934 boolean doPostDeleteLI(boolean delete) { 10935 // XXX err, shouldn't we respect the delete flag? 10936 cleanUpResourcesLI(); 10937 return true; 10938 } 10939 } 10940 10941 static String getAsecPackageName(String packageCid) { 10942 int idx = packageCid.lastIndexOf("-"); 10943 if (idx == -1) { 10944 return packageCid; 10945 } 10946 return packageCid.substring(0, idx); 10947 } 10948 10949 // Utility method used to create code paths based on package name and available index. 10950 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10951 String idxStr = ""; 10952 int idx = 1; 10953 // Fall back to default value of idx=1 if prefix is not 10954 // part of oldCodePath 10955 if (oldCodePath != null) { 10956 String subStr = oldCodePath; 10957 // Drop the suffix right away 10958 if (suffix != null && subStr.endsWith(suffix)) { 10959 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10960 } 10961 // If oldCodePath already contains prefix find out the 10962 // ending index to either increment or decrement. 10963 int sidx = subStr.lastIndexOf(prefix); 10964 if (sidx != -1) { 10965 subStr = subStr.substring(sidx + prefix.length()); 10966 if (subStr != null) { 10967 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10968 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10969 } 10970 try { 10971 idx = Integer.parseInt(subStr); 10972 if (idx <= 1) { 10973 idx++; 10974 } else { 10975 idx--; 10976 } 10977 } catch(NumberFormatException e) { 10978 } 10979 } 10980 } 10981 } 10982 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10983 return prefix + idxStr; 10984 } 10985 10986 private File getNextCodePath(File targetDir, String packageName) { 10987 int suffix = 1; 10988 File result; 10989 do { 10990 result = new File(targetDir, packageName + "-" + suffix); 10991 suffix++; 10992 } while (result.exists()); 10993 return result; 10994 } 10995 10996 // Utility method that returns the relative package path with respect 10997 // to the installation directory. Like say for /data/data/com.test-1.apk 10998 // string com.test-1 is returned. 10999 static String deriveCodePathName(String codePath) { 11000 if (codePath == null) { 11001 return null; 11002 } 11003 final File codeFile = new File(codePath); 11004 final String name = codeFile.getName(); 11005 if (codeFile.isDirectory()) { 11006 return name; 11007 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11008 final int lastDot = name.lastIndexOf('.'); 11009 return name.substring(0, lastDot); 11010 } else { 11011 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11012 return null; 11013 } 11014 } 11015 11016 class PackageInstalledInfo { 11017 String name; 11018 int uid; 11019 // The set of users that originally had this package installed. 11020 int[] origUsers; 11021 // The set of users that now have this package installed. 11022 int[] newUsers; 11023 PackageParser.Package pkg; 11024 int returnCode; 11025 String returnMsg; 11026 PackageRemovedInfo removedInfo; 11027 11028 public void setError(int code, String msg) { 11029 returnCode = code; 11030 returnMsg = msg; 11031 Slog.w(TAG, msg); 11032 } 11033 11034 public void setError(String msg, PackageParserException e) { 11035 returnCode = e.error; 11036 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11037 Slog.w(TAG, msg, e); 11038 } 11039 11040 public void setError(String msg, PackageManagerException e) { 11041 returnCode = e.error; 11042 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11043 Slog.w(TAG, msg, e); 11044 } 11045 11046 // In some error cases we want to convey more info back to the observer 11047 String origPackage; 11048 String origPermission; 11049 } 11050 11051 /* 11052 * Install a non-existing package. 11053 */ 11054 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11055 UserHandle user, String installerPackageName, String volumeUuid, 11056 PackageInstalledInfo res) { 11057 // Remember this for later, in case we need to rollback this install 11058 String pkgName = pkg.packageName; 11059 11060 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11061 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11062 UserHandle.USER_OWNER).exists(); 11063 synchronized(mPackages) { 11064 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11065 // A package with the same name is already installed, though 11066 // it has been renamed to an older name. The package we 11067 // are trying to install should be installed as an update to 11068 // the existing one, but that has not been requested, so bail. 11069 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11070 + " without first uninstalling package running as " 11071 + mSettings.mRenamedPackages.get(pkgName)); 11072 return; 11073 } 11074 if (mPackages.containsKey(pkgName)) { 11075 // Don't allow installation over an existing package with the same name. 11076 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11077 + " without first uninstalling."); 11078 return; 11079 } 11080 } 11081 11082 try { 11083 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11084 System.currentTimeMillis(), user); 11085 11086 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11087 // delete the partially installed application. the data directory will have to be 11088 // restored if it was already existing 11089 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11090 // remove package from internal structures. Note that we want deletePackageX to 11091 // delete the package data and cache directories that it created in 11092 // scanPackageLocked, unless those directories existed before we even tried to 11093 // install. 11094 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11095 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11096 res.removedInfo, true); 11097 } 11098 11099 } catch (PackageManagerException e) { 11100 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11101 } 11102 } 11103 11104 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11105 // Upgrade keysets are being used. Determine if new package has a superset of the 11106 // required keys. 11107 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11108 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11109 for (int i = 0; i < upgradeKeySets.length; i++) { 11110 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11111 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11112 return true; 11113 } 11114 } 11115 return false; 11116 } 11117 11118 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11119 UserHandle user, String installerPackageName, String volumeUuid, 11120 PackageInstalledInfo res) { 11121 final PackageParser.Package oldPackage; 11122 final String pkgName = pkg.packageName; 11123 final int[] allUsers; 11124 final boolean[] perUserInstalled; 11125 final boolean weFroze; 11126 11127 // First find the old package info and check signatures 11128 synchronized(mPackages) { 11129 oldPackage = mPackages.get(pkgName); 11130 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11131 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11132 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11133 // default to original signature matching 11134 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11135 != PackageManager.SIGNATURE_MATCH) { 11136 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11137 "New package has a different signature: " + pkgName); 11138 return; 11139 } 11140 } else { 11141 if(!checkUpgradeKeySetLP(ps, pkg)) { 11142 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11143 "New package not signed by keys specified by upgrade-keysets: " 11144 + pkgName); 11145 return; 11146 } 11147 } 11148 11149 // In case of rollback, remember per-user/profile install state 11150 allUsers = sUserManager.getUserIds(); 11151 perUserInstalled = new boolean[allUsers.length]; 11152 for (int i = 0; i < allUsers.length; i++) { 11153 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11154 } 11155 11156 // Mark the app as frozen to prevent launching during the upgrade 11157 // process, and then kill all running instances 11158 if (!ps.frozen) { 11159 ps.frozen = true; 11160 weFroze = true; 11161 } else { 11162 weFroze = false; 11163 } 11164 } 11165 11166 // Now that we're guarded by frozen state, kill app during upgrade 11167 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11168 11169 try { 11170 boolean sysPkg = (isSystemApp(oldPackage)); 11171 if (sysPkg) { 11172 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11173 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11174 } else { 11175 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11176 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11177 } 11178 } finally { 11179 // Regardless of success or failure of upgrade steps above, always 11180 // unfreeze the package if we froze it 11181 if (weFroze) { 11182 unfreezePackage(pkgName); 11183 } 11184 } 11185 } 11186 11187 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11188 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11189 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11190 String volumeUuid, PackageInstalledInfo res) { 11191 String pkgName = deletedPackage.packageName; 11192 boolean deletedPkg = true; 11193 boolean updatedSettings = false; 11194 11195 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11196 + deletedPackage); 11197 long origUpdateTime; 11198 if (pkg.mExtras != null) { 11199 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11200 } else { 11201 origUpdateTime = 0; 11202 } 11203 11204 // First delete the existing package while retaining the data directory 11205 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11206 res.removedInfo, true)) { 11207 // If the existing package wasn't successfully deleted 11208 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11209 deletedPkg = false; 11210 } else { 11211 // Successfully deleted the old package; proceed with replace. 11212 11213 // If deleted package lived in a container, give users a chance to 11214 // relinquish resources before killing. 11215 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11216 if (DEBUG_INSTALL) { 11217 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11218 } 11219 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11220 final ArrayList<String> pkgList = new ArrayList<String>(1); 11221 pkgList.add(deletedPackage.applicationInfo.packageName); 11222 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11223 } 11224 11225 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11226 try { 11227 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11228 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11229 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11230 perUserInstalled, res, user); 11231 updatedSettings = true; 11232 } catch (PackageManagerException e) { 11233 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11234 } 11235 } 11236 11237 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11238 // remove package from internal structures. Note that we want deletePackageX to 11239 // delete the package data and cache directories that it created in 11240 // scanPackageLocked, unless those directories existed before we even tried to 11241 // install. 11242 if(updatedSettings) { 11243 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11244 deletePackageLI( 11245 pkgName, null, true, allUsers, perUserInstalled, 11246 PackageManager.DELETE_KEEP_DATA, 11247 res.removedInfo, true); 11248 } 11249 // Since we failed to install the new package we need to restore the old 11250 // package that we deleted. 11251 if (deletedPkg) { 11252 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11253 File restoreFile = new File(deletedPackage.codePath); 11254 // Parse old package 11255 boolean oldExternal = isExternal(deletedPackage); 11256 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11257 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11258 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11259 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11260 try { 11261 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11262 } catch (PackageManagerException e) { 11263 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11264 + e.getMessage()); 11265 return; 11266 } 11267 // Restore of old package succeeded. Update permissions. 11268 // writer 11269 synchronized (mPackages) { 11270 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11271 UPDATE_PERMISSIONS_ALL); 11272 // can downgrade to reader 11273 mSettings.writeLPr(); 11274 } 11275 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11276 } 11277 } 11278 } 11279 11280 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11281 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11282 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11283 String volumeUuid, PackageInstalledInfo res) { 11284 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11285 + ", old=" + deletedPackage); 11286 boolean disabledSystem = false; 11287 boolean updatedSettings = false; 11288 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11289 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11290 != 0) { 11291 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11292 } 11293 String packageName = deletedPackage.packageName; 11294 if (packageName == null) { 11295 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11296 "Attempt to delete null packageName."); 11297 return; 11298 } 11299 PackageParser.Package oldPkg; 11300 PackageSetting oldPkgSetting; 11301 // reader 11302 synchronized (mPackages) { 11303 oldPkg = mPackages.get(packageName); 11304 oldPkgSetting = mSettings.mPackages.get(packageName); 11305 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11306 (oldPkgSetting == null)) { 11307 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11308 "Couldn't find package:" + packageName + " information"); 11309 return; 11310 } 11311 } 11312 11313 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11314 res.removedInfo.removedPackage = packageName; 11315 // Remove existing system package 11316 removePackageLI(oldPkgSetting, true); 11317 // writer 11318 synchronized (mPackages) { 11319 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11320 if (!disabledSystem && deletedPackage != null) { 11321 // We didn't need to disable the .apk as a current system package, 11322 // which means we are replacing another update that is already 11323 // installed. We need to make sure to delete the older one's .apk. 11324 res.removedInfo.args = createInstallArgsForExisting(0, 11325 deletedPackage.applicationInfo.getCodePath(), 11326 deletedPackage.applicationInfo.getResourcePath(), 11327 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11328 } else { 11329 res.removedInfo.args = null; 11330 } 11331 } 11332 11333 // Successfully disabled the old package. Now proceed with re-installation 11334 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11335 11336 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11337 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11338 11339 PackageParser.Package newPackage = null; 11340 try { 11341 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11342 if (newPackage.mExtras != null) { 11343 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11344 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11345 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11346 11347 // is the update attempting to change shared user? that isn't going to work... 11348 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11349 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11350 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11351 + " to " + newPkgSetting.sharedUser); 11352 updatedSettings = true; 11353 } 11354 } 11355 11356 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11357 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11358 perUserInstalled, res, user); 11359 updatedSettings = true; 11360 } 11361 11362 } catch (PackageManagerException e) { 11363 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11364 } 11365 11366 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11367 // Re installation failed. Restore old information 11368 // Remove new pkg information 11369 if (newPackage != null) { 11370 removeInstalledPackageLI(newPackage, true); 11371 } 11372 // Add back the old system package 11373 try { 11374 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11375 } catch (PackageManagerException e) { 11376 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11377 } 11378 // Restore the old system information in Settings 11379 synchronized (mPackages) { 11380 if (disabledSystem) { 11381 mSettings.enableSystemPackageLPw(packageName); 11382 } 11383 if (updatedSettings) { 11384 mSettings.setInstallerPackageName(packageName, 11385 oldPkgSetting.installerPackageName); 11386 } 11387 mSettings.writeLPr(); 11388 } 11389 } 11390 } 11391 11392 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11393 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11394 UserHandle user) { 11395 String pkgName = newPackage.packageName; 11396 synchronized (mPackages) { 11397 //write settings. the installStatus will be incomplete at this stage. 11398 //note that the new package setting would have already been 11399 //added to mPackages. It hasn't been persisted yet. 11400 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11401 mSettings.writeLPr(); 11402 } 11403 11404 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11405 11406 synchronized (mPackages) { 11407 updatePermissionsLPw(newPackage.packageName, newPackage, 11408 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11409 ? UPDATE_PERMISSIONS_ALL : 0)); 11410 // For system-bundled packages, we assume that installing an upgraded version 11411 // of the package implies that the user actually wants to run that new code, 11412 // so we enable the package. 11413 PackageSetting ps = mSettings.mPackages.get(pkgName); 11414 if (ps != null) { 11415 if (isSystemApp(newPackage)) { 11416 // NB: implicit assumption that system package upgrades apply to all users 11417 if (DEBUG_INSTALL) { 11418 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11419 } 11420 if (res.origUsers != null) { 11421 for (int userHandle : res.origUsers) { 11422 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11423 userHandle, installerPackageName); 11424 } 11425 } 11426 // Also convey the prior install/uninstall state 11427 if (allUsers != null && perUserInstalled != null) { 11428 for (int i = 0; i < allUsers.length; i++) { 11429 if (DEBUG_INSTALL) { 11430 Slog.d(TAG, " user " + allUsers[i] 11431 + " => " + perUserInstalled[i]); 11432 } 11433 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11434 } 11435 // these install state changes will be persisted in the 11436 // upcoming call to mSettings.writeLPr(). 11437 } 11438 } 11439 // It's implied that when a user requests installation, they want the app to be 11440 // installed and enabled. 11441 int userId = user.getIdentifier(); 11442 if (userId != UserHandle.USER_ALL) { 11443 ps.setInstalled(true, userId); 11444 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11445 } 11446 } 11447 res.name = pkgName; 11448 res.uid = newPackage.applicationInfo.uid; 11449 res.pkg = newPackage; 11450 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11451 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11452 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11453 //to update install status 11454 mSettings.writeLPr(); 11455 } 11456 } 11457 11458 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11459 final int installFlags = args.installFlags; 11460 final String installerPackageName = args.installerPackageName; 11461 final String volumeUuid = args.volumeUuid; 11462 final File tmpPackageFile = new File(args.getCodePath()); 11463 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11464 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11465 || (args.volumeUuid != null)); 11466 boolean replace = false; 11467 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11468 // Result object to be returned 11469 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11470 11471 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11472 // Retrieve PackageSettings and parse package 11473 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11474 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11475 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11476 PackageParser pp = new PackageParser(); 11477 pp.setSeparateProcesses(mSeparateProcesses); 11478 pp.setDisplayMetrics(mMetrics); 11479 11480 final PackageParser.Package pkg; 11481 try { 11482 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11483 } catch (PackageParserException e) { 11484 res.setError("Failed parse during installPackageLI", e); 11485 return; 11486 } 11487 11488 // Mark that we have an install time CPU ABI override. 11489 pkg.cpuAbiOverride = args.abiOverride; 11490 11491 String pkgName = res.name = pkg.packageName; 11492 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11493 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11494 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11495 return; 11496 } 11497 } 11498 11499 try { 11500 pp.collectCertificates(pkg, parseFlags); 11501 pp.collectManifestDigest(pkg); 11502 } catch (PackageParserException e) { 11503 res.setError("Failed collect during installPackageLI", e); 11504 return; 11505 } 11506 11507 /* If the installer passed in a manifest digest, compare it now. */ 11508 if (args.manifestDigest != null) { 11509 if (DEBUG_INSTALL) { 11510 final String parsedManifest = pkg.manifestDigest == null ? "null" 11511 : pkg.manifestDigest.toString(); 11512 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11513 + parsedManifest); 11514 } 11515 11516 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11517 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11518 return; 11519 } 11520 } else if (DEBUG_INSTALL) { 11521 final String parsedManifest = pkg.manifestDigest == null 11522 ? "null" : pkg.manifestDigest.toString(); 11523 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11524 } 11525 11526 // Get rid of all references to package scan path via parser. 11527 pp = null; 11528 String oldCodePath = null; 11529 boolean systemApp = false; 11530 synchronized (mPackages) { 11531 // Check if installing already existing package 11532 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11533 String oldName = mSettings.mRenamedPackages.get(pkgName); 11534 if (pkg.mOriginalPackages != null 11535 && pkg.mOriginalPackages.contains(oldName) 11536 && mPackages.containsKey(oldName)) { 11537 // This package is derived from an original package, 11538 // and this device has been updating from that original 11539 // name. We must continue using the original name, so 11540 // rename the new package here. 11541 pkg.setPackageName(oldName); 11542 pkgName = pkg.packageName; 11543 replace = true; 11544 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11545 + oldName + " pkgName=" + pkgName); 11546 } else if (mPackages.containsKey(pkgName)) { 11547 // This package, under its official name, already exists 11548 // on the device; we should replace it. 11549 replace = true; 11550 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11551 } 11552 11553 // Prevent apps opting out from runtime permissions 11554 if (replace) { 11555 PackageParser.Package oldPackage = mPackages.get(pkgName); 11556 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11557 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11558 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11559 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11560 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11561 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11562 + " doesn't support runtime permissions but the old" 11563 + " target SDK " + oldTargetSdk + " does."); 11564 return; 11565 } 11566 } 11567 } 11568 11569 PackageSetting ps = mSettings.mPackages.get(pkgName); 11570 if (ps != null) { 11571 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11572 11573 // Quick sanity check that we're signed correctly if updating; 11574 // we'll check this again later when scanning, but we want to 11575 // bail early here before tripping over redefined permissions. 11576 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11577 try { 11578 verifySignaturesLP(ps, pkg); 11579 } catch (PackageManagerException e) { 11580 res.setError(e.error, e.getMessage()); 11581 return; 11582 } 11583 } else { 11584 if (!checkUpgradeKeySetLP(ps, pkg)) { 11585 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11586 + pkg.packageName + " upgrade keys do not match the " 11587 + "previously installed version"); 11588 return; 11589 } 11590 } 11591 11592 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11593 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11594 systemApp = (ps.pkg.applicationInfo.flags & 11595 ApplicationInfo.FLAG_SYSTEM) != 0; 11596 } 11597 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11598 } 11599 11600 // Check whether the newly-scanned package wants to define an already-defined perm 11601 int N = pkg.permissions.size(); 11602 for (int i = N-1; i >= 0; i--) { 11603 PackageParser.Permission perm = pkg.permissions.get(i); 11604 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11605 if (bp != null) { 11606 // If the defining package is signed with our cert, it's okay. This 11607 // also includes the "updating the same package" case, of course. 11608 // "updating same package" could also involve key-rotation. 11609 final boolean sigsOk; 11610 if (!bp.sourcePackage.equals(pkg.packageName) 11611 || !(bp.packageSetting instanceof PackageSetting) 11612 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11613 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11614 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11615 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11616 } else { 11617 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11618 } 11619 if (!sigsOk) { 11620 // If the owning package is the system itself, we log but allow 11621 // install to proceed; we fail the install on all other permission 11622 // redefinitions. 11623 if (!bp.sourcePackage.equals("android")) { 11624 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11625 + pkg.packageName + " attempting to redeclare permission " 11626 + perm.info.name + " already owned by " + bp.sourcePackage); 11627 res.origPermission = perm.info.name; 11628 res.origPackage = bp.sourcePackage; 11629 return; 11630 } else { 11631 Slog.w(TAG, "Package " + pkg.packageName 11632 + " attempting to redeclare system permission " 11633 + perm.info.name + "; ignoring new declaration"); 11634 pkg.permissions.remove(i); 11635 } 11636 } 11637 } 11638 } 11639 11640 } 11641 11642 if (systemApp && onExternal) { 11643 // Disable updates to system apps on sdcard 11644 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11645 "Cannot install updates to system apps on sdcard"); 11646 return; 11647 } 11648 11649 if (args.move != null) { 11650 // We did an in-place move, so dex is ready to roll 11651 scanFlags |= SCAN_NO_DEX; 11652 scanFlags |= SCAN_MOVE; 11653 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11654 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11655 scanFlags |= SCAN_NO_DEX; 11656 11657 try { 11658 deriveNonSystemPackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11659 true /* extract libs */); 11660 } catch (PackageManagerException pme) { 11661 Slog.e(TAG, "Error deriving application ABI", pme); 11662 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11663 return; 11664 } 11665 11666 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11667 int result = mPackageDexOptimizer 11668 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11669 false /* defer */, false /* inclDependencies */); 11670 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11671 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11672 return; 11673 } 11674 } 11675 11676 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11677 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11678 return; 11679 } 11680 11681 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11682 11683 if (replace) { 11684 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11685 installerPackageName, volumeUuid, res); 11686 } else { 11687 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11688 args.user, installerPackageName, volumeUuid, res); 11689 } 11690 synchronized (mPackages) { 11691 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11692 if (ps != null) { 11693 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11694 } 11695 } 11696 } 11697 11698 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11699 if (mIntentFilterVerifierComponent == null) { 11700 Slog.d(TAG, "No IntentFilter verification will not be done as " 11701 + "there is no IntentFilterVerifier available!"); 11702 return; 11703 } 11704 11705 final int verifierUid = getPackageUid( 11706 mIntentFilterVerifierComponent.getPackageName(), 11707 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11708 11709 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11710 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11711 msg.obj = pkg; 11712 msg.arg1 = userId; 11713 msg.arg2 = verifierUid; 11714 11715 mHandler.sendMessage(msg); 11716 } 11717 11718 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11719 PackageParser.Package pkg) { 11720 int size = pkg.activities.size(); 11721 if (size == 0) { 11722 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11723 return; 11724 } 11725 11726 final boolean hasDomainURLs = hasDomainURLs(pkg); 11727 if (!hasDomainURLs) { 11728 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11729 return; 11730 } 11731 11732 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11733 + " Activities needs verification ..."); 11734 11735 final int verificationId = mIntentFilterVerificationToken++; 11736 int count = 0; 11737 final String packageName = pkg.packageName; 11738 ArrayList<String> allHosts = new ArrayList<>(); 11739 11740 synchronized (mPackages) { 11741 for (PackageParser.Activity a : pkg.activities) { 11742 for (ActivityIntentInfo filter : a.intents) { 11743 boolean needsFilterVerification = filter.needsVerification(); 11744 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11745 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11746 mIntentFilterVerifier.addOneIntentFilterVerification( 11747 verifierUid, userId, verificationId, filter, packageName); 11748 count++; 11749 } else if (!needsFilterVerification) { 11750 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11751 if (hasValidDomains(filter)) { 11752 ArrayList<String> hosts = filter.getHostsList(); 11753 if (hosts.size() > 0) { 11754 allHosts.addAll(hosts); 11755 } else { 11756 if (allHosts.isEmpty()) { 11757 allHosts.add("*"); 11758 } 11759 } 11760 } 11761 } else { 11762 Slog.d(TAG, "Verification already done for IntentFilter:" 11763 + filter.toString()); 11764 } 11765 } 11766 } 11767 } 11768 11769 if (count > 0) { 11770 mIntentFilterVerifier.startVerifications(userId); 11771 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11772 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11773 } else { 11774 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11775 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11776 packageName, allHosts) != null) { 11777 scheduleWriteSettingsLocked(); 11778 } 11779 } 11780 } 11781 11782 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11783 final ComponentName cn = filter.activity.getComponentName(); 11784 final String packageName = cn.getPackageName(); 11785 11786 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11787 packageName); 11788 if (ivi == null) { 11789 return true; 11790 } 11791 int status = ivi.getStatus(); 11792 switch (status) { 11793 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11794 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11795 return true; 11796 11797 default: 11798 // Nothing to do 11799 return false; 11800 } 11801 } 11802 11803 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11804 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11805 || ((pkg.applicationInfo.privateFlags 11806 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11807 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11808 } 11809 11810 private static boolean isMultiArch(PackageSetting ps) { 11811 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11812 } 11813 11814 private static boolean isMultiArch(ApplicationInfo info) { 11815 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11816 } 11817 11818 private static boolean isExternal(PackageParser.Package pkg) { 11819 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11820 } 11821 11822 private static boolean isExternal(PackageSetting ps) { 11823 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11824 } 11825 11826 private static boolean isExternal(ApplicationInfo info) { 11827 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11828 } 11829 11830 private static boolean isSystemApp(PackageParser.Package pkg) { 11831 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11832 } 11833 11834 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11835 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11836 } 11837 11838 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11839 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11840 } 11841 11842 private static boolean isSystemApp(PackageSetting ps) { 11843 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11844 } 11845 11846 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11847 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11848 } 11849 11850 private int packageFlagsToInstallFlags(PackageSetting ps) { 11851 int installFlags = 0; 11852 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11853 // This existing package was an external ASEC install when we have 11854 // the external flag without a UUID 11855 installFlags |= PackageManager.INSTALL_EXTERNAL; 11856 } 11857 if (ps.isForwardLocked()) { 11858 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11859 } 11860 return installFlags; 11861 } 11862 11863 private void deleteTempPackageFiles() { 11864 final FilenameFilter filter = new FilenameFilter() { 11865 public boolean accept(File dir, String name) { 11866 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11867 } 11868 }; 11869 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11870 file.delete(); 11871 } 11872 } 11873 11874 @Override 11875 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11876 int flags) { 11877 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11878 flags); 11879 } 11880 11881 @Override 11882 public void deletePackage(final String packageName, 11883 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11884 mContext.enforceCallingOrSelfPermission( 11885 android.Manifest.permission.DELETE_PACKAGES, null); 11886 final int uid = Binder.getCallingUid(); 11887 if (UserHandle.getUserId(uid) != userId) { 11888 mContext.enforceCallingPermission( 11889 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11890 "deletePackage for user " + userId); 11891 } 11892 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11893 try { 11894 observer.onPackageDeleted(packageName, 11895 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11896 } catch (RemoteException re) { 11897 } 11898 return; 11899 } 11900 11901 boolean uninstallBlocked = false; 11902 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11903 int[] users = sUserManager.getUserIds(); 11904 for (int i = 0; i < users.length; ++i) { 11905 if (getBlockUninstallForUser(packageName, users[i])) { 11906 uninstallBlocked = true; 11907 break; 11908 } 11909 } 11910 } else { 11911 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11912 } 11913 if (uninstallBlocked) { 11914 try { 11915 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11916 null); 11917 } catch (RemoteException re) { 11918 } 11919 return; 11920 } 11921 11922 if (DEBUG_REMOVE) { 11923 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11924 } 11925 // Queue up an async operation since the package deletion may take a little while. 11926 mHandler.post(new Runnable() { 11927 public void run() { 11928 mHandler.removeCallbacks(this); 11929 final int returnCode = deletePackageX(packageName, userId, flags); 11930 if (observer != null) { 11931 try { 11932 observer.onPackageDeleted(packageName, returnCode, null); 11933 } catch (RemoteException e) { 11934 Log.i(TAG, "Observer no longer exists."); 11935 } //end catch 11936 } //end if 11937 } //end run 11938 }); 11939 } 11940 11941 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11942 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11943 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11944 try { 11945 if (dpm != null) { 11946 if (dpm.isDeviceOwner(packageName)) { 11947 return true; 11948 } 11949 int[] users; 11950 if (userId == UserHandle.USER_ALL) { 11951 users = sUserManager.getUserIds(); 11952 } else { 11953 users = new int[]{userId}; 11954 } 11955 for (int i = 0; i < users.length; ++i) { 11956 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11957 return true; 11958 } 11959 } 11960 } 11961 } catch (RemoteException e) { 11962 } 11963 return false; 11964 } 11965 11966 /** 11967 * This method is an internal method that could be get invoked either 11968 * to delete an installed package or to clean up a failed installation. 11969 * After deleting an installed package, a broadcast is sent to notify any 11970 * listeners that the package has been installed. For cleaning up a failed 11971 * installation, the broadcast is not necessary since the package's 11972 * installation wouldn't have sent the initial broadcast either 11973 * The key steps in deleting a package are 11974 * deleting the package information in internal structures like mPackages, 11975 * deleting the packages base directories through installd 11976 * updating mSettings to reflect current status 11977 * persisting settings for later use 11978 * sending a broadcast if necessary 11979 */ 11980 private int deletePackageX(String packageName, int userId, int flags) { 11981 final PackageRemovedInfo info = new PackageRemovedInfo(); 11982 final boolean res; 11983 11984 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11985 ? UserHandle.ALL : new UserHandle(userId); 11986 11987 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11988 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11989 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11990 } 11991 11992 boolean removedForAllUsers = false; 11993 boolean systemUpdate = false; 11994 11995 // for the uninstall-updates case and restricted profiles, remember the per- 11996 // userhandle installed state 11997 int[] allUsers; 11998 boolean[] perUserInstalled; 11999 synchronized (mPackages) { 12000 PackageSetting ps = mSettings.mPackages.get(packageName); 12001 allUsers = sUserManager.getUserIds(); 12002 perUserInstalled = new boolean[allUsers.length]; 12003 for (int i = 0; i < allUsers.length; i++) { 12004 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12005 } 12006 } 12007 12008 synchronized (mInstallLock) { 12009 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12010 res = deletePackageLI(packageName, removeForUser, 12011 true, allUsers, perUserInstalled, 12012 flags | REMOVE_CHATTY, info, true); 12013 systemUpdate = info.isRemovedPackageSystemUpdate; 12014 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12015 removedForAllUsers = true; 12016 } 12017 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12018 + " removedForAllUsers=" + removedForAllUsers); 12019 } 12020 12021 if (res) { 12022 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12023 12024 // If the removed package was a system update, the old system package 12025 // was re-enabled; we need to broadcast this information 12026 if (systemUpdate) { 12027 Bundle extras = new Bundle(1); 12028 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12029 ? info.removedAppId : info.uid); 12030 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12031 12032 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12033 extras, null, null, null); 12034 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12035 extras, null, null, null); 12036 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12037 null, packageName, null, null); 12038 } 12039 } 12040 // Force a gc here. 12041 Runtime.getRuntime().gc(); 12042 // Delete the resources here after sending the broadcast to let 12043 // other processes clean up before deleting resources. 12044 if (info.args != null) { 12045 synchronized (mInstallLock) { 12046 info.args.doPostDeleteLI(true); 12047 } 12048 } 12049 12050 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12051 } 12052 12053 class PackageRemovedInfo { 12054 String removedPackage; 12055 int uid = -1; 12056 int removedAppId = -1; 12057 int[] removedUsers = null; 12058 boolean isRemovedPackageSystemUpdate = false; 12059 // Clean up resources deleted packages. 12060 InstallArgs args = null; 12061 12062 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12063 Bundle extras = new Bundle(1); 12064 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12065 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12066 if (replacing) { 12067 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12068 } 12069 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12070 if (removedPackage != null) { 12071 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12072 extras, null, null, removedUsers); 12073 if (fullRemove && !replacing) { 12074 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12075 extras, null, null, removedUsers); 12076 } 12077 } 12078 if (removedAppId >= 0) { 12079 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12080 removedUsers); 12081 } 12082 } 12083 } 12084 12085 /* 12086 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12087 * flag is not set, the data directory is removed as well. 12088 * make sure this flag is set for partially installed apps. If not its meaningless to 12089 * delete a partially installed application. 12090 */ 12091 private void removePackageDataLI(PackageSetting ps, 12092 int[] allUserHandles, boolean[] perUserInstalled, 12093 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12094 String packageName = ps.name; 12095 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12096 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12097 // Retrieve object to delete permissions for shared user later on 12098 final PackageSetting deletedPs; 12099 // reader 12100 synchronized (mPackages) { 12101 deletedPs = mSettings.mPackages.get(packageName); 12102 if (outInfo != null) { 12103 outInfo.removedPackage = packageName; 12104 outInfo.removedUsers = deletedPs != null 12105 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12106 : null; 12107 } 12108 } 12109 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12110 removeDataDirsLI(ps.volumeUuid, packageName); 12111 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12112 } 12113 // writer 12114 synchronized (mPackages) { 12115 if (deletedPs != null) { 12116 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12117 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12118 clearDefaultBrowserIfNeeded(packageName); 12119 if (outInfo != null) { 12120 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12121 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12122 } 12123 updatePermissionsLPw(deletedPs.name, null, 0); 12124 if (deletedPs.sharedUser != null) { 12125 // Remove permissions associated with package. Since runtime 12126 // permissions are per user we have to kill the removed package 12127 // or packages running under the shared user of the removed 12128 // package if revoking the permissions requested only by the removed 12129 // package is successful and this causes a change in gids. 12130 for (int userId : UserManagerService.getInstance().getUserIds()) { 12131 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12132 userId); 12133 if (userIdToKill == UserHandle.USER_ALL 12134 || userIdToKill >= UserHandle.USER_OWNER) { 12135 // If gids changed for this user, kill all affected packages. 12136 mHandler.post(new Runnable() { 12137 @Override 12138 public void run() { 12139 // This has to happen with no lock held. 12140 killSettingPackagesForUser(deletedPs, userIdToKill, 12141 KILL_APP_REASON_GIDS_CHANGED); 12142 } 12143 }); 12144 break; 12145 } 12146 } 12147 } 12148 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12149 } 12150 // make sure to preserve per-user disabled state if this removal was just 12151 // a downgrade of a system app to the factory package 12152 if (allUserHandles != null && perUserInstalled != null) { 12153 if (DEBUG_REMOVE) { 12154 Slog.d(TAG, "Propagating install state across downgrade"); 12155 } 12156 for (int i = 0; i < allUserHandles.length; i++) { 12157 if (DEBUG_REMOVE) { 12158 Slog.d(TAG, " user " + allUserHandles[i] 12159 + " => " + perUserInstalled[i]); 12160 } 12161 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12162 } 12163 } 12164 } 12165 // can downgrade to reader 12166 if (writeSettings) { 12167 // Save settings now 12168 mSettings.writeLPr(); 12169 } 12170 } 12171 if (outInfo != null) { 12172 // A user ID was deleted here. Go through all users and remove it 12173 // from KeyStore. 12174 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12175 } 12176 } 12177 12178 static boolean locationIsPrivileged(File path) { 12179 try { 12180 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12181 .getCanonicalPath(); 12182 return path.getCanonicalPath().startsWith(privilegedAppDir); 12183 } catch (IOException e) { 12184 Slog.e(TAG, "Unable to access code path " + path); 12185 } 12186 return false; 12187 } 12188 12189 /* 12190 * Tries to delete system package. 12191 */ 12192 private boolean deleteSystemPackageLI(PackageSetting newPs, 12193 int[] allUserHandles, boolean[] perUserInstalled, 12194 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12195 final boolean applyUserRestrictions 12196 = (allUserHandles != null) && (perUserInstalled != null); 12197 PackageSetting disabledPs = null; 12198 // Confirm if the system package has been updated 12199 // An updated system app can be deleted. This will also have to restore 12200 // the system pkg from system partition 12201 // reader 12202 synchronized (mPackages) { 12203 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12204 } 12205 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12206 + " disabledPs=" + disabledPs); 12207 if (disabledPs == null) { 12208 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12209 return false; 12210 } else if (DEBUG_REMOVE) { 12211 Slog.d(TAG, "Deleting system pkg from data partition"); 12212 } 12213 if (DEBUG_REMOVE) { 12214 if (applyUserRestrictions) { 12215 Slog.d(TAG, "Remembering install states:"); 12216 for (int i = 0; i < allUserHandles.length; i++) { 12217 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12218 } 12219 } 12220 } 12221 // Delete the updated package 12222 outInfo.isRemovedPackageSystemUpdate = true; 12223 if (disabledPs.versionCode < newPs.versionCode) { 12224 // Delete data for downgrades 12225 flags &= ~PackageManager.DELETE_KEEP_DATA; 12226 } else { 12227 // Preserve data by setting flag 12228 flags |= PackageManager.DELETE_KEEP_DATA; 12229 } 12230 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12231 allUserHandles, perUserInstalled, outInfo, writeSettings); 12232 if (!ret) { 12233 return false; 12234 } 12235 // writer 12236 synchronized (mPackages) { 12237 // Reinstate the old system package 12238 mSettings.enableSystemPackageLPw(newPs.name); 12239 // Remove any native libraries from the upgraded package. 12240 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12241 } 12242 // Install the system package 12243 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12244 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12245 if (locationIsPrivileged(disabledPs.codePath)) { 12246 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12247 } 12248 12249 final PackageParser.Package newPkg; 12250 try { 12251 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12252 } catch (PackageManagerException e) { 12253 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12254 return false; 12255 } 12256 12257 // writer 12258 synchronized (mPackages) { 12259 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12260 updatePermissionsLPw(newPkg.packageName, newPkg, 12261 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12262 if (applyUserRestrictions) { 12263 if (DEBUG_REMOVE) { 12264 Slog.d(TAG, "Propagating install state across reinstall"); 12265 } 12266 for (int i = 0; i < allUserHandles.length; i++) { 12267 if (DEBUG_REMOVE) { 12268 Slog.d(TAG, " user " + allUserHandles[i] 12269 + " => " + perUserInstalled[i]); 12270 } 12271 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12272 } 12273 // Regardless of writeSettings we need to ensure that this restriction 12274 // state propagation is persisted 12275 mSettings.writeAllUsersPackageRestrictionsLPr(); 12276 } 12277 // can downgrade to reader here 12278 if (writeSettings) { 12279 mSettings.writeLPr(); 12280 } 12281 } 12282 return true; 12283 } 12284 12285 private boolean deleteInstalledPackageLI(PackageSetting ps, 12286 boolean deleteCodeAndResources, int flags, 12287 int[] allUserHandles, boolean[] perUserInstalled, 12288 PackageRemovedInfo outInfo, boolean writeSettings) { 12289 if (outInfo != null) { 12290 outInfo.uid = ps.appId; 12291 } 12292 12293 // Delete package data from internal structures and also remove data if flag is set 12294 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12295 12296 // Delete application code and resources 12297 if (deleteCodeAndResources && (outInfo != null)) { 12298 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12299 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12300 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12301 } 12302 return true; 12303 } 12304 12305 @Override 12306 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12307 int userId) { 12308 mContext.enforceCallingOrSelfPermission( 12309 android.Manifest.permission.DELETE_PACKAGES, null); 12310 synchronized (mPackages) { 12311 PackageSetting ps = mSettings.mPackages.get(packageName); 12312 if (ps == null) { 12313 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12314 return false; 12315 } 12316 if (!ps.getInstalled(userId)) { 12317 // Can't block uninstall for an app that is not installed or enabled. 12318 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12319 return false; 12320 } 12321 ps.setBlockUninstall(blockUninstall, userId); 12322 mSettings.writePackageRestrictionsLPr(userId); 12323 } 12324 return true; 12325 } 12326 12327 @Override 12328 public boolean getBlockUninstallForUser(String packageName, int userId) { 12329 synchronized (mPackages) { 12330 PackageSetting ps = mSettings.mPackages.get(packageName); 12331 if (ps == null) { 12332 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12333 return false; 12334 } 12335 return ps.getBlockUninstall(userId); 12336 } 12337 } 12338 12339 /* 12340 * This method handles package deletion in general 12341 */ 12342 private boolean deletePackageLI(String packageName, UserHandle user, 12343 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12344 int flags, PackageRemovedInfo outInfo, 12345 boolean writeSettings) { 12346 if (packageName == null) { 12347 Slog.w(TAG, "Attempt to delete null packageName."); 12348 return false; 12349 } 12350 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12351 PackageSetting ps; 12352 boolean dataOnly = false; 12353 int removeUser = -1; 12354 int appId = -1; 12355 synchronized (mPackages) { 12356 ps = mSettings.mPackages.get(packageName); 12357 if (ps == null) { 12358 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12359 return false; 12360 } 12361 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12362 && user.getIdentifier() != UserHandle.USER_ALL) { 12363 // The caller is asking that the package only be deleted for a single 12364 // user. To do this, we just mark its uninstalled state and delete 12365 // its data. If this is a system app, we only allow this to happen if 12366 // they have set the special DELETE_SYSTEM_APP which requests different 12367 // semantics than normal for uninstalling system apps. 12368 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12369 ps.setUserState(user.getIdentifier(), 12370 COMPONENT_ENABLED_STATE_DEFAULT, 12371 false, //installed 12372 true, //stopped 12373 true, //notLaunched 12374 false, //hidden 12375 null, null, null, 12376 false, // blockUninstall 12377 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12378 if (!isSystemApp(ps)) { 12379 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12380 // Other user still have this package installed, so all 12381 // we need to do is clear this user's data and save that 12382 // it is uninstalled. 12383 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12384 removeUser = user.getIdentifier(); 12385 appId = ps.appId; 12386 scheduleWritePackageRestrictionsLocked(removeUser); 12387 } else { 12388 // We need to set it back to 'installed' so the uninstall 12389 // broadcasts will be sent correctly. 12390 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12391 ps.setInstalled(true, user.getIdentifier()); 12392 } 12393 } else { 12394 // This is a system app, so we assume that the 12395 // other users still have this package installed, so all 12396 // we need to do is clear this user's data and save that 12397 // it is uninstalled. 12398 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12399 removeUser = user.getIdentifier(); 12400 appId = ps.appId; 12401 scheduleWritePackageRestrictionsLocked(removeUser); 12402 } 12403 } 12404 } 12405 12406 if (removeUser >= 0) { 12407 // From above, we determined that we are deleting this only 12408 // for a single user. Continue the work here. 12409 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12410 if (outInfo != null) { 12411 outInfo.removedPackage = packageName; 12412 outInfo.removedAppId = appId; 12413 outInfo.removedUsers = new int[] {removeUser}; 12414 } 12415 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12416 removeKeystoreDataIfNeeded(removeUser, appId); 12417 schedulePackageCleaning(packageName, removeUser, false); 12418 synchronized (mPackages) { 12419 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12420 scheduleWritePackageRestrictionsLocked(removeUser); 12421 } 12422 } 12423 return true; 12424 } 12425 12426 if (dataOnly) { 12427 // Delete application data first 12428 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12429 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12430 return true; 12431 } 12432 12433 boolean ret = false; 12434 if (isSystemApp(ps)) { 12435 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12436 // When an updated system application is deleted we delete the existing resources as well and 12437 // fall back to existing code in system partition 12438 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12439 flags, outInfo, writeSettings); 12440 } else { 12441 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12442 // Kill application pre-emptively especially for apps on sd. 12443 killApplication(packageName, ps.appId, "uninstall pkg"); 12444 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12445 allUserHandles, perUserInstalled, 12446 outInfo, writeSettings); 12447 } 12448 12449 return ret; 12450 } 12451 12452 private final class ClearStorageConnection implements ServiceConnection { 12453 IMediaContainerService mContainerService; 12454 12455 @Override 12456 public void onServiceConnected(ComponentName name, IBinder service) { 12457 synchronized (this) { 12458 mContainerService = IMediaContainerService.Stub.asInterface(service); 12459 notifyAll(); 12460 } 12461 } 12462 12463 @Override 12464 public void onServiceDisconnected(ComponentName name) { 12465 } 12466 } 12467 12468 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12469 final boolean mounted; 12470 if (Environment.isExternalStorageEmulated()) { 12471 mounted = true; 12472 } else { 12473 final String status = Environment.getExternalStorageState(); 12474 12475 mounted = status.equals(Environment.MEDIA_MOUNTED) 12476 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12477 } 12478 12479 if (!mounted) { 12480 return; 12481 } 12482 12483 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12484 int[] users; 12485 if (userId == UserHandle.USER_ALL) { 12486 users = sUserManager.getUserIds(); 12487 } else { 12488 users = new int[] { userId }; 12489 } 12490 final ClearStorageConnection conn = new ClearStorageConnection(); 12491 if (mContext.bindServiceAsUser( 12492 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12493 try { 12494 for (int curUser : users) { 12495 long timeout = SystemClock.uptimeMillis() + 5000; 12496 synchronized (conn) { 12497 long now = SystemClock.uptimeMillis(); 12498 while (conn.mContainerService == null && now < timeout) { 12499 try { 12500 conn.wait(timeout - now); 12501 } catch (InterruptedException e) { 12502 } 12503 } 12504 } 12505 if (conn.mContainerService == null) { 12506 return; 12507 } 12508 12509 final UserEnvironment userEnv = new UserEnvironment(curUser); 12510 clearDirectory(conn.mContainerService, 12511 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12512 if (allData) { 12513 clearDirectory(conn.mContainerService, 12514 userEnv.buildExternalStorageAppDataDirs(packageName)); 12515 clearDirectory(conn.mContainerService, 12516 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12517 } 12518 } 12519 } finally { 12520 mContext.unbindService(conn); 12521 } 12522 } 12523 } 12524 12525 @Override 12526 public void clearApplicationUserData(final String packageName, 12527 final IPackageDataObserver observer, final int userId) { 12528 mContext.enforceCallingOrSelfPermission( 12529 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12530 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12531 // Queue up an async operation since the package deletion may take a little while. 12532 mHandler.post(new Runnable() { 12533 public void run() { 12534 mHandler.removeCallbacks(this); 12535 final boolean succeeded; 12536 synchronized (mInstallLock) { 12537 succeeded = clearApplicationUserDataLI(packageName, userId); 12538 } 12539 clearExternalStorageDataSync(packageName, userId, true); 12540 if (succeeded) { 12541 // invoke DeviceStorageMonitor's update method to clear any notifications 12542 DeviceStorageMonitorInternal 12543 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12544 if (dsm != null) { 12545 dsm.checkMemory(); 12546 } 12547 } 12548 if(observer != null) { 12549 try { 12550 observer.onRemoveCompleted(packageName, succeeded); 12551 } catch (RemoteException e) { 12552 Log.i(TAG, "Observer no longer exists."); 12553 } 12554 } //end if observer 12555 } //end run 12556 }); 12557 } 12558 12559 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12560 if (packageName == null) { 12561 Slog.w(TAG, "Attempt to delete null packageName."); 12562 return false; 12563 } 12564 12565 // Try finding details about the requested package 12566 PackageParser.Package pkg; 12567 synchronized (mPackages) { 12568 pkg = mPackages.get(packageName); 12569 if (pkg == null) { 12570 final PackageSetting ps = mSettings.mPackages.get(packageName); 12571 if (ps != null) { 12572 pkg = ps.pkg; 12573 } 12574 } 12575 } 12576 12577 if (pkg == null) { 12578 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12579 } 12580 12581 // Always delete data directories for package, even if we found no other 12582 // record of app. This helps users recover from UID mismatches without 12583 // resorting to a full data wipe. 12584 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12585 if (retCode < 0) { 12586 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12587 return false; 12588 } 12589 12590 if (pkg == null) { 12591 return false; 12592 } 12593 12594 if (pkg != null && pkg.applicationInfo != null) { 12595 final int appId = pkg.applicationInfo.uid; 12596 removeKeystoreDataIfNeeded(userId, appId); 12597 } 12598 12599 // Create a native library symlink only if we have native libraries 12600 // and if the native libraries are 32 bit libraries. We do not provide 12601 // this symlink for 64 bit libraries. 12602 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12603 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12604 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12605 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12606 nativeLibPath, userId) < 0) { 12607 Slog.w(TAG, "Failed linking native library dir"); 12608 return false; 12609 } 12610 } 12611 12612 return true; 12613 } 12614 12615 /** 12616 * Remove entries from the keystore daemon. Will only remove it if the 12617 * {@code appId} is valid. 12618 */ 12619 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12620 if (appId < 0) { 12621 return; 12622 } 12623 12624 final KeyStore keyStore = KeyStore.getInstance(); 12625 if (keyStore != null) { 12626 if (userId == UserHandle.USER_ALL) { 12627 for (final int individual : sUserManager.getUserIds()) { 12628 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12629 } 12630 } else { 12631 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12632 } 12633 } else { 12634 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12635 } 12636 } 12637 12638 @Override 12639 public void deleteApplicationCacheFiles(final String packageName, 12640 final IPackageDataObserver observer) { 12641 mContext.enforceCallingOrSelfPermission( 12642 android.Manifest.permission.DELETE_CACHE_FILES, null); 12643 // Queue up an async operation since the package deletion may take a little while. 12644 final int userId = UserHandle.getCallingUserId(); 12645 mHandler.post(new Runnable() { 12646 public void run() { 12647 mHandler.removeCallbacks(this); 12648 final boolean succeded; 12649 synchronized (mInstallLock) { 12650 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12651 } 12652 clearExternalStorageDataSync(packageName, userId, false); 12653 if (observer != null) { 12654 try { 12655 observer.onRemoveCompleted(packageName, succeded); 12656 } catch (RemoteException e) { 12657 Log.i(TAG, "Observer no longer exists."); 12658 } 12659 } //end if observer 12660 } //end run 12661 }); 12662 } 12663 12664 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12665 if (packageName == null) { 12666 Slog.w(TAG, "Attempt to delete null packageName."); 12667 return false; 12668 } 12669 PackageParser.Package p; 12670 synchronized (mPackages) { 12671 p = mPackages.get(packageName); 12672 } 12673 if (p == null) { 12674 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12675 return false; 12676 } 12677 final ApplicationInfo applicationInfo = p.applicationInfo; 12678 if (applicationInfo == null) { 12679 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12680 return false; 12681 } 12682 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12683 if (retCode < 0) { 12684 Slog.w(TAG, "Couldn't remove cache files for package: " 12685 + packageName + " u" + userId); 12686 return false; 12687 } 12688 return true; 12689 } 12690 12691 @Override 12692 public void getPackageSizeInfo(final String packageName, int userHandle, 12693 final IPackageStatsObserver observer) { 12694 mContext.enforceCallingOrSelfPermission( 12695 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12696 if (packageName == null) { 12697 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12698 } 12699 12700 PackageStats stats = new PackageStats(packageName, userHandle); 12701 12702 /* 12703 * Queue up an async operation since the package measurement may take a 12704 * little while. 12705 */ 12706 Message msg = mHandler.obtainMessage(INIT_COPY); 12707 msg.obj = new MeasureParams(stats, observer); 12708 mHandler.sendMessage(msg); 12709 } 12710 12711 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12712 PackageStats pStats) { 12713 if (packageName == null) { 12714 Slog.w(TAG, "Attempt to get size of null packageName."); 12715 return false; 12716 } 12717 PackageParser.Package p; 12718 boolean dataOnly = false; 12719 String libDirRoot = null; 12720 String asecPath = null; 12721 PackageSetting ps = null; 12722 synchronized (mPackages) { 12723 p = mPackages.get(packageName); 12724 ps = mSettings.mPackages.get(packageName); 12725 if(p == null) { 12726 dataOnly = true; 12727 if((ps == null) || (ps.pkg == null)) { 12728 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12729 return false; 12730 } 12731 p = ps.pkg; 12732 } 12733 if (ps != null) { 12734 libDirRoot = ps.legacyNativeLibraryPathString; 12735 } 12736 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12737 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12738 if (secureContainerId != null) { 12739 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12740 } 12741 } 12742 } 12743 String publicSrcDir = null; 12744 if(!dataOnly) { 12745 final ApplicationInfo applicationInfo = p.applicationInfo; 12746 if (applicationInfo == null) { 12747 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12748 return false; 12749 } 12750 if (p.isForwardLocked()) { 12751 publicSrcDir = applicationInfo.getBaseResourcePath(); 12752 } 12753 } 12754 // TODO: extend to measure size of split APKs 12755 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12756 // not just the first level. 12757 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12758 // just the primary. 12759 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12760 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12761 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12762 if (res < 0) { 12763 return false; 12764 } 12765 12766 // Fix-up for forward-locked applications in ASEC containers. 12767 if (!isExternal(p)) { 12768 pStats.codeSize += pStats.externalCodeSize; 12769 pStats.externalCodeSize = 0L; 12770 } 12771 12772 return true; 12773 } 12774 12775 12776 @Override 12777 public void addPackageToPreferred(String packageName) { 12778 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12779 } 12780 12781 @Override 12782 public void removePackageFromPreferred(String packageName) { 12783 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12784 } 12785 12786 @Override 12787 public List<PackageInfo> getPreferredPackages(int flags) { 12788 return new ArrayList<PackageInfo>(); 12789 } 12790 12791 private int getUidTargetSdkVersionLockedLPr(int uid) { 12792 Object obj = mSettings.getUserIdLPr(uid); 12793 if (obj instanceof SharedUserSetting) { 12794 final SharedUserSetting sus = (SharedUserSetting) obj; 12795 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12796 final Iterator<PackageSetting> it = sus.packages.iterator(); 12797 while (it.hasNext()) { 12798 final PackageSetting ps = it.next(); 12799 if (ps.pkg != null) { 12800 int v = ps.pkg.applicationInfo.targetSdkVersion; 12801 if (v < vers) vers = v; 12802 } 12803 } 12804 return vers; 12805 } else if (obj instanceof PackageSetting) { 12806 final PackageSetting ps = (PackageSetting) obj; 12807 if (ps.pkg != null) { 12808 return ps.pkg.applicationInfo.targetSdkVersion; 12809 } 12810 } 12811 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12812 } 12813 12814 @Override 12815 public void addPreferredActivity(IntentFilter filter, int match, 12816 ComponentName[] set, ComponentName activity, int userId) { 12817 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12818 "Adding preferred"); 12819 } 12820 12821 private void addPreferredActivityInternal(IntentFilter filter, int match, 12822 ComponentName[] set, ComponentName activity, boolean always, int userId, 12823 String opname) { 12824 // writer 12825 int callingUid = Binder.getCallingUid(); 12826 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12827 if (filter.countActions() == 0) { 12828 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12829 return; 12830 } 12831 synchronized (mPackages) { 12832 if (mContext.checkCallingOrSelfPermission( 12833 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12834 != PackageManager.PERMISSION_GRANTED) { 12835 if (getUidTargetSdkVersionLockedLPr(callingUid) 12836 < Build.VERSION_CODES.FROYO) { 12837 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12838 + callingUid); 12839 return; 12840 } 12841 mContext.enforceCallingOrSelfPermission( 12842 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12843 } 12844 12845 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12846 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12847 + userId + ":"); 12848 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12849 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12850 scheduleWritePackageRestrictionsLocked(userId); 12851 } 12852 } 12853 12854 @Override 12855 public void replacePreferredActivity(IntentFilter filter, int match, 12856 ComponentName[] set, ComponentName activity, int userId) { 12857 if (filter.countActions() != 1) { 12858 throw new IllegalArgumentException( 12859 "replacePreferredActivity expects filter to have only 1 action."); 12860 } 12861 if (filter.countDataAuthorities() != 0 12862 || filter.countDataPaths() != 0 12863 || filter.countDataSchemes() > 1 12864 || filter.countDataTypes() != 0) { 12865 throw new IllegalArgumentException( 12866 "replacePreferredActivity expects filter to have no data authorities, " + 12867 "paths, or types; and at most one scheme."); 12868 } 12869 12870 final int callingUid = Binder.getCallingUid(); 12871 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12872 synchronized (mPackages) { 12873 if (mContext.checkCallingOrSelfPermission( 12874 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12875 != PackageManager.PERMISSION_GRANTED) { 12876 if (getUidTargetSdkVersionLockedLPr(callingUid) 12877 < Build.VERSION_CODES.FROYO) { 12878 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12879 + Binder.getCallingUid()); 12880 return; 12881 } 12882 mContext.enforceCallingOrSelfPermission( 12883 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12884 } 12885 12886 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12887 if (pir != null) { 12888 // Get all of the existing entries that exactly match this filter. 12889 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12890 if (existing != null && existing.size() == 1) { 12891 PreferredActivity cur = existing.get(0); 12892 if (DEBUG_PREFERRED) { 12893 Slog.i(TAG, "Checking replace of preferred:"); 12894 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12895 if (!cur.mPref.mAlways) { 12896 Slog.i(TAG, " -- CUR; not mAlways!"); 12897 } else { 12898 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12899 Slog.i(TAG, " -- CUR: mSet=" 12900 + Arrays.toString(cur.mPref.mSetComponents)); 12901 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12902 Slog.i(TAG, " -- NEW: mMatch=" 12903 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12904 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12905 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12906 } 12907 } 12908 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12909 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12910 && cur.mPref.sameSet(set)) { 12911 // Setting the preferred activity to what it happens to be already 12912 if (DEBUG_PREFERRED) { 12913 Slog.i(TAG, "Replacing with same preferred activity " 12914 + cur.mPref.mShortComponent + " for user " 12915 + userId + ":"); 12916 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12917 } 12918 return; 12919 } 12920 } 12921 12922 if (existing != null) { 12923 if (DEBUG_PREFERRED) { 12924 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12925 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12926 } 12927 for (int i = 0; i < existing.size(); i++) { 12928 PreferredActivity pa = existing.get(i); 12929 if (DEBUG_PREFERRED) { 12930 Slog.i(TAG, "Removing existing preferred activity " 12931 + pa.mPref.mComponent + ":"); 12932 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12933 } 12934 pir.removeFilter(pa); 12935 } 12936 } 12937 } 12938 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12939 "Replacing preferred"); 12940 } 12941 } 12942 12943 @Override 12944 public void clearPackagePreferredActivities(String packageName) { 12945 final int uid = Binder.getCallingUid(); 12946 // writer 12947 synchronized (mPackages) { 12948 PackageParser.Package pkg = mPackages.get(packageName); 12949 if (pkg == null || pkg.applicationInfo.uid != uid) { 12950 if (mContext.checkCallingOrSelfPermission( 12951 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12952 != PackageManager.PERMISSION_GRANTED) { 12953 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12954 < Build.VERSION_CODES.FROYO) { 12955 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12956 + Binder.getCallingUid()); 12957 return; 12958 } 12959 mContext.enforceCallingOrSelfPermission( 12960 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12961 } 12962 } 12963 12964 int user = UserHandle.getCallingUserId(); 12965 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12966 scheduleWritePackageRestrictionsLocked(user); 12967 } 12968 } 12969 } 12970 12971 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12972 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12973 ArrayList<PreferredActivity> removed = null; 12974 boolean changed = false; 12975 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12976 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12977 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12978 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12979 continue; 12980 } 12981 Iterator<PreferredActivity> it = pir.filterIterator(); 12982 while (it.hasNext()) { 12983 PreferredActivity pa = it.next(); 12984 // Mark entry for removal only if it matches the package name 12985 // and the entry is of type "always". 12986 if (packageName == null || 12987 (pa.mPref.mComponent.getPackageName().equals(packageName) 12988 && pa.mPref.mAlways)) { 12989 if (removed == null) { 12990 removed = new ArrayList<PreferredActivity>(); 12991 } 12992 removed.add(pa); 12993 } 12994 } 12995 if (removed != null) { 12996 for (int j=0; j<removed.size(); j++) { 12997 PreferredActivity pa = removed.get(j); 12998 pir.removeFilter(pa); 12999 } 13000 changed = true; 13001 } 13002 } 13003 return changed; 13004 } 13005 13006 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13007 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13008 if (userId == UserHandle.USER_ALL) { 13009 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13010 sUserManager.getUserIds())) { 13011 for (int oneUserId : sUserManager.getUserIds()) { 13012 scheduleWritePackageRestrictionsLocked(oneUserId); 13013 } 13014 } 13015 } else { 13016 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13017 scheduleWritePackageRestrictionsLocked(userId); 13018 } 13019 } 13020 } 13021 13022 13023 void clearDefaultBrowserIfNeeded(String packageName) { 13024 for (int oneUserId : sUserManager.getUserIds()) { 13025 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13026 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13027 if (packageName.equals(defaultBrowserPackageName)) { 13028 setDefaultBrowserPackageName(null, oneUserId); 13029 } 13030 } 13031 } 13032 13033 @Override 13034 public void resetPreferredActivities(int userId) { 13035 /* TODO: Actually use userId. Why is it being passed in? */ 13036 mContext.enforceCallingOrSelfPermission( 13037 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13038 // writer 13039 synchronized (mPackages) { 13040 int user = UserHandle.getCallingUserId(); 13041 clearPackagePreferredActivitiesLPw(null, user); 13042 mSettings.readDefaultPreferredAppsLPw(this, user); 13043 scheduleWritePackageRestrictionsLocked(user); 13044 } 13045 } 13046 13047 @Override 13048 public int getPreferredActivities(List<IntentFilter> outFilters, 13049 List<ComponentName> outActivities, String packageName) { 13050 13051 int num = 0; 13052 final int userId = UserHandle.getCallingUserId(); 13053 // reader 13054 synchronized (mPackages) { 13055 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13056 if (pir != null) { 13057 final Iterator<PreferredActivity> it = pir.filterIterator(); 13058 while (it.hasNext()) { 13059 final PreferredActivity pa = it.next(); 13060 if (packageName == null 13061 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13062 && pa.mPref.mAlways)) { 13063 if (outFilters != null) { 13064 outFilters.add(new IntentFilter(pa)); 13065 } 13066 if (outActivities != null) { 13067 outActivities.add(pa.mPref.mComponent); 13068 } 13069 } 13070 } 13071 } 13072 } 13073 13074 return num; 13075 } 13076 13077 @Override 13078 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13079 int userId) { 13080 int callingUid = Binder.getCallingUid(); 13081 if (callingUid != Process.SYSTEM_UID) { 13082 throw new SecurityException( 13083 "addPersistentPreferredActivity can only be run by the system"); 13084 } 13085 if (filter.countActions() == 0) { 13086 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13087 return; 13088 } 13089 synchronized (mPackages) { 13090 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13091 " :"); 13092 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13093 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13094 new PersistentPreferredActivity(filter, activity)); 13095 scheduleWritePackageRestrictionsLocked(userId); 13096 } 13097 } 13098 13099 @Override 13100 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13101 int callingUid = Binder.getCallingUid(); 13102 if (callingUid != Process.SYSTEM_UID) { 13103 throw new SecurityException( 13104 "clearPackagePersistentPreferredActivities can only be run by the system"); 13105 } 13106 ArrayList<PersistentPreferredActivity> removed = null; 13107 boolean changed = false; 13108 synchronized (mPackages) { 13109 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13110 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13111 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13112 .valueAt(i); 13113 if (userId != thisUserId) { 13114 continue; 13115 } 13116 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13117 while (it.hasNext()) { 13118 PersistentPreferredActivity ppa = it.next(); 13119 // Mark entry for removal only if it matches the package name. 13120 if (ppa.mComponent.getPackageName().equals(packageName)) { 13121 if (removed == null) { 13122 removed = new ArrayList<PersistentPreferredActivity>(); 13123 } 13124 removed.add(ppa); 13125 } 13126 } 13127 if (removed != null) { 13128 for (int j=0; j<removed.size(); j++) { 13129 PersistentPreferredActivity ppa = removed.get(j); 13130 ppir.removeFilter(ppa); 13131 } 13132 changed = true; 13133 } 13134 } 13135 13136 if (changed) { 13137 scheduleWritePackageRestrictionsLocked(userId); 13138 } 13139 } 13140 } 13141 13142 /** 13143 * Non-Binder method, support for the backup/restore mechanism: write the 13144 * full set of preferred activities in its canonical XML format. Returns true 13145 * on success; false otherwise. 13146 */ 13147 @Override 13148 public byte[] getPreferredActivityBackup(int userId) { 13149 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13150 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13151 } 13152 13153 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13154 try { 13155 final XmlSerializer serializer = new FastXmlSerializer(); 13156 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13157 serializer.startDocument(null, true); 13158 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13159 13160 synchronized (mPackages) { 13161 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13162 } 13163 13164 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13165 serializer.endDocument(); 13166 serializer.flush(); 13167 } catch (Exception e) { 13168 if (DEBUG_BACKUP) { 13169 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13170 } 13171 return null; 13172 } 13173 13174 return dataStream.toByteArray(); 13175 } 13176 13177 @Override 13178 public void restorePreferredActivities(byte[] backup, int userId) { 13179 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13180 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13181 } 13182 13183 try { 13184 final XmlPullParser parser = Xml.newPullParser(); 13185 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13186 13187 int type; 13188 while ((type = parser.next()) != XmlPullParser.START_TAG 13189 && type != XmlPullParser.END_DOCUMENT) { 13190 } 13191 if (type != XmlPullParser.START_TAG) { 13192 // oops didn't find a start tag?! 13193 if (DEBUG_BACKUP) { 13194 Slog.e(TAG, "Didn't find start tag during restore"); 13195 } 13196 return; 13197 } 13198 13199 // this is supposed to be TAG_PREFERRED_BACKUP 13200 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13201 if (DEBUG_BACKUP) { 13202 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13203 } 13204 return; 13205 } 13206 13207 // skip interfering stuff, then we're aligned with the backing implementation 13208 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13209 synchronized (mPackages) { 13210 mSettings.readPreferredActivitiesLPw(parser, userId); 13211 } 13212 } catch (Exception e) { 13213 if (DEBUG_BACKUP) { 13214 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13215 } 13216 } 13217 } 13218 13219 @Override 13220 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13221 int sourceUserId, int targetUserId, int flags) { 13222 mContext.enforceCallingOrSelfPermission( 13223 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13224 int callingUid = Binder.getCallingUid(); 13225 enforceOwnerRights(ownerPackage, callingUid); 13226 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13227 if (intentFilter.countActions() == 0) { 13228 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13229 return; 13230 } 13231 synchronized (mPackages) { 13232 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13233 ownerPackage, targetUserId, flags); 13234 CrossProfileIntentResolver resolver = 13235 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13236 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13237 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13238 if (existing != null) { 13239 int size = existing.size(); 13240 for (int i = 0; i < size; i++) { 13241 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13242 return; 13243 } 13244 } 13245 } 13246 resolver.addFilter(newFilter); 13247 scheduleWritePackageRestrictionsLocked(sourceUserId); 13248 } 13249 } 13250 13251 @Override 13252 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13253 mContext.enforceCallingOrSelfPermission( 13254 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13255 int callingUid = Binder.getCallingUid(); 13256 enforceOwnerRights(ownerPackage, callingUid); 13257 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13258 synchronized (mPackages) { 13259 CrossProfileIntentResolver resolver = 13260 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13261 ArraySet<CrossProfileIntentFilter> set = 13262 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13263 for (CrossProfileIntentFilter filter : set) { 13264 if (filter.getOwnerPackage().equals(ownerPackage)) { 13265 resolver.removeFilter(filter); 13266 } 13267 } 13268 scheduleWritePackageRestrictionsLocked(sourceUserId); 13269 } 13270 } 13271 13272 // Enforcing that callingUid is owning pkg on userId 13273 private void enforceOwnerRights(String pkg, int callingUid) { 13274 // The system owns everything. 13275 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13276 return; 13277 } 13278 int callingUserId = UserHandle.getUserId(callingUid); 13279 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13280 if (pi == null) { 13281 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13282 + callingUserId); 13283 } 13284 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13285 throw new SecurityException("Calling uid " + callingUid 13286 + " does not own package " + pkg); 13287 } 13288 } 13289 13290 @Override 13291 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13292 Intent intent = new Intent(Intent.ACTION_MAIN); 13293 intent.addCategory(Intent.CATEGORY_HOME); 13294 13295 final int callingUserId = UserHandle.getCallingUserId(); 13296 List<ResolveInfo> list = queryIntentActivities(intent, null, 13297 PackageManager.GET_META_DATA, callingUserId); 13298 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13299 true, false, false, callingUserId); 13300 13301 allHomeCandidates.clear(); 13302 if (list != null) { 13303 for (ResolveInfo ri : list) { 13304 allHomeCandidates.add(ri); 13305 } 13306 } 13307 return (preferred == null || preferred.activityInfo == null) 13308 ? null 13309 : new ComponentName(preferred.activityInfo.packageName, 13310 preferred.activityInfo.name); 13311 } 13312 13313 @Override 13314 public void setApplicationEnabledSetting(String appPackageName, 13315 int newState, int flags, int userId, String callingPackage) { 13316 if (!sUserManager.exists(userId)) return; 13317 if (callingPackage == null) { 13318 callingPackage = Integer.toString(Binder.getCallingUid()); 13319 } 13320 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13321 } 13322 13323 @Override 13324 public void setComponentEnabledSetting(ComponentName componentName, 13325 int newState, int flags, int userId) { 13326 if (!sUserManager.exists(userId)) return; 13327 setEnabledSetting(componentName.getPackageName(), 13328 componentName.getClassName(), newState, flags, userId, null); 13329 } 13330 13331 private void setEnabledSetting(final String packageName, String className, int newState, 13332 final int flags, int userId, String callingPackage) { 13333 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13334 || newState == COMPONENT_ENABLED_STATE_ENABLED 13335 || newState == COMPONENT_ENABLED_STATE_DISABLED 13336 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13337 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13338 throw new IllegalArgumentException("Invalid new component state: " 13339 + newState); 13340 } 13341 PackageSetting pkgSetting; 13342 final int uid = Binder.getCallingUid(); 13343 final int permission = mContext.checkCallingOrSelfPermission( 13344 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13345 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13346 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13347 boolean sendNow = false; 13348 boolean isApp = (className == null); 13349 String componentName = isApp ? packageName : className; 13350 int packageUid = -1; 13351 ArrayList<String> components; 13352 13353 // writer 13354 synchronized (mPackages) { 13355 pkgSetting = mSettings.mPackages.get(packageName); 13356 if (pkgSetting == null) { 13357 if (className == null) { 13358 throw new IllegalArgumentException( 13359 "Unknown package: " + packageName); 13360 } 13361 throw new IllegalArgumentException( 13362 "Unknown component: " + packageName 13363 + "/" + className); 13364 } 13365 // Allow root and verify that userId is not being specified by a different user 13366 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13367 throw new SecurityException( 13368 "Permission Denial: attempt to change component state from pid=" 13369 + Binder.getCallingPid() 13370 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13371 } 13372 if (className == null) { 13373 // We're dealing with an application/package level state change 13374 if (pkgSetting.getEnabled(userId) == newState) { 13375 // Nothing to do 13376 return; 13377 } 13378 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13379 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13380 // Don't care about who enables an app. 13381 callingPackage = null; 13382 } 13383 pkgSetting.setEnabled(newState, userId, callingPackage); 13384 // pkgSetting.pkg.mSetEnabled = newState; 13385 } else { 13386 // We're dealing with a component level state change 13387 // First, verify that this is a valid class name. 13388 PackageParser.Package pkg = pkgSetting.pkg; 13389 if (pkg == null || !pkg.hasComponentClassName(className)) { 13390 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13391 throw new IllegalArgumentException("Component class " + className 13392 + " does not exist in " + packageName); 13393 } else { 13394 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13395 + className + " does not exist in " + packageName); 13396 } 13397 } 13398 switch (newState) { 13399 case COMPONENT_ENABLED_STATE_ENABLED: 13400 if (!pkgSetting.enableComponentLPw(className, userId)) { 13401 return; 13402 } 13403 break; 13404 case COMPONENT_ENABLED_STATE_DISABLED: 13405 if (!pkgSetting.disableComponentLPw(className, userId)) { 13406 return; 13407 } 13408 break; 13409 case COMPONENT_ENABLED_STATE_DEFAULT: 13410 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13411 return; 13412 } 13413 break; 13414 default: 13415 Slog.e(TAG, "Invalid new component state: " + newState); 13416 return; 13417 } 13418 } 13419 scheduleWritePackageRestrictionsLocked(userId); 13420 components = mPendingBroadcasts.get(userId, packageName); 13421 final boolean newPackage = components == null; 13422 if (newPackage) { 13423 components = new ArrayList<String>(); 13424 } 13425 if (!components.contains(componentName)) { 13426 components.add(componentName); 13427 } 13428 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13429 sendNow = true; 13430 // Purge entry from pending broadcast list if another one exists already 13431 // since we are sending one right away. 13432 mPendingBroadcasts.remove(userId, packageName); 13433 } else { 13434 if (newPackage) { 13435 mPendingBroadcasts.put(userId, packageName, components); 13436 } 13437 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13438 // Schedule a message 13439 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13440 } 13441 } 13442 } 13443 13444 long callingId = Binder.clearCallingIdentity(); 13445 try { 13446 if (sendNow) { 13447 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13448 sendPackageChangedBroadcast(packageName, 13449 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13450 } 13451 } finally { 13452 Binder.restoreCallingIdentity(callingId); 13453 } 13454 } 13455 13456 private void sendPackageChangedBroadcast(String packageName, 13457 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13458 if (DEBUG_INSTALL) 13459 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13460 + componentNames); 13461 Bundle extras = new Bundle(4); 13462 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13463 String nameList[] = new String[componentNames.size()]; 13464 componentNames.toArray(nameList); 13465 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13466 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13467 extras.putInt(Intent.EXTRA_UID, packageUid); 13468 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13469 new int[] {UserHandle.getUserId(packageUid)}); 13470 } 13471 13472 @Override 13473 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13474 if (!sUserManager.exists(userId)) return; 13475 final int uid = Binder.getCallingUid(); 13476 final int permission = mContext.checkCallingOrSelfPermission( 13477 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13478 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13479 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13480 // writer 13481 synchronized (mPackages) { 13482 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13483 allowedByPermission, uid, userId)) { 13484 scheduleWritePackageRestrictionsLocked(userId); 13485 } 13486 } 13487 } 13488 13489 @Override 13490 public String getInstallerPackageName(String packageName) { 13491 // reader 13492 synchronized (mPackages) { 13493 return mSettings.getInstallerPackageNameLPr(packageName); 13494 } 13495 } 13496 13497 @Override 13498 public int getApplicationEnabledSetting(String packageName, int userId) { 13499 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13500 int uid = Binder.getCallingUid(); 13501 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13502 // reader 13503 synchronized (mPackages) { 13504 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13505 } 13506 } 13507 13508 @Override 13509 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13510 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13511 int uid = Binder.getCallingUid(); 13512 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13513 // reader 13514 synchronized (mPackages) { 13515 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13516 } 13517 } 13518 13519 @Override 13520 public void enterSafeMode() { 13521 enforceSystemOrRoot("Only the system can request entering safe mode"); 13522 13523 if (!mSystemReady) { 13524 mSafeMode = true; 13525 } 13526 } 13527 13528 @Override 13529 public void systemReady() { 13530 mSystemReady = true; 13531 13532 // Read the compatibilty setting when the system is ready. 13533 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13534 mContext.getContentResolver(), 13535 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13536 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13537 if (DEBUG_SETTINGS) { 13538 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13539 } 13540 13541 synchronized (mPackages) { 13542 // Verify that all of the preferred activity components actually 13543 // exist. It is possible for applications to be updated and at 13544 // that point remove a previously declared activity component that 13545 // had been set as a preferred activity. We try to clean this up 13546 // the next time we encounter that preferred activity, but it is 13547 // possible for the user flow to never be able to return to that 13548 // situation so here we do a sanity check to make sure we haven't 13549 // left any junk around. 13550 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13551 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13552 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13553 removed.clear(); 13554 for (PreferredActivity pa : pir.filterSet()) { 13555 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13556 removed.add(pa); 13557 } 13558 } 13559 if (removed.size() > 0) { 13560 for (int r=0; r<removed.size(); r++) { 13561 PreferredActivity pa = removed.get(r); 13562 Slog.w(TAG, "Removing dangling preferred activity: " 13563 + pa.mPref.mComponent); 13564 pir.removeFilter(pa); 13565 } 13566 mSettings.writePackageRestrictionsLPr( 13567 mSettings.mPreferredActivities.keyAt(i)); 13568 } 13569 } 13570 } 13571 sUserManager.systemReady(); 13572 13573 // Kick off any messages waiting for system ready 13574 if (mPostSystemReadyMessages != null) { 13575 for (Message msg : mPostSystemReadyMessages) { 13576 msg.sendToTarget(); 13577 } 13578 mPostSystemReadyMessages = null; 13579 } 13580 13581 // Watch for external volumes that come and go over time 13582 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13583 storage.registerListener(mStorageListener); 13584 13585 mInstallerService.systemReady(); 13586 mPackageDexOptimizer.systemReady(); 13587 } 13588 13589 @Override 13590 public boolean isSafeMode() { 13591 return mSafeMode; 13592 } 13593 13594 @Override 13595 public boolean hasSystemUidErrors() { 13596 return mHasSystemUidErrors; 13597 } 13598 13599 static String arrayToString(int[] array) { 13600 StringBuffer buf = new StringBuffer(128); 13601 buf.append('['); 13602 if (array != null) { 13603 for (int i=0; i<array.length; i++) { 13604 if (i > 0) buf.append(", "); 13605 buf.append(array[i]); 13606 } 13607 } 13608 buf.append(']'); 13609 return buf.toString(); 13610 } 13611 13612 static class DumpState { 13613 public static final int DUMP_LIBS = 1 << 0; 13614 public static final int DUMP_FEATURES = 1 << 1; 13615 public static final int DUMP_RESOLVERS = 1 << 2; 13616 public static final int DUMP_PERMISSIONS = 1 << 3; 13617 public static final int DUMP_PACKAGES = 1 << 4; 13618 public static final int DUMP_SHARED_USERS = 1 << 5; 13619 public static final int DUMP_MESSAGES = 1 << 6; 13620 public static final int DUMP_PROVIDERS = 1 << 7; 13621 public static final int DUMP_VERIFIERS = 1 << 8; 13622 public static final int DUMP_PREFERRED = 1 << 9; 13623 public static final int DUMP_PREFERRED_XML = 1 << 10; 13624 public static final int DUMP_KEYSETS = 1 << 11; 13625 public static final int DUMP_VERSION = 1 << 12; 13626 public static final int DUMP_INSTALLS = 1 << 13; 13627 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13628 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13629 13630 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13631 13632 private int mTypes; 13633 13634 private int mOptions; 13635 13636 private boolean mTitlePrinted; 13637 13638 private SharedUserSetting mSharedUser; 13639 13640 public boolean isDumping(int type) { 13641 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13642 return true; 13643 } 13644 13645 return (mTypes & type) != 0; 13646 } 13647 13648 public void setDump(int type) { 13649 mTypes |= type; 13650 } 13651 13652 public boolean isOptionEnabled(int option) { 13653 return (mOptions & option) != 0; 13654 } 13655 13656 public void setOptionEnabled(int option) { 13657 mOptions |= option; 13658 } 13659 13660 public boolean onTitlePrinted() { 13661 final boolean printed = mTitlePrinted; 13662 mTitlePrinted = true; 13663 return printed; 13664 } 13665 13666 public boolean getTitlePrinted() { 13667 return mTitlePrinted; 13668 } 13669 13670 public void setTitlePrinted(boolean enabled) { 13671 mTitlePrinted = enabled; 13672 } 13673 13674 public SharedUserSetting getSharedUser() { 13675 return mSharedUser; 13676 } 13677 13678 public void setSharedUser(SharedUserSetting user) { 13679 mSharedUser = user; 13680 } 13681 } 13682 13683 @Override 13684 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13685 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13686 != PackageManager.PERMISSION_GRANTED) { 13687 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13688 + Binder.getCallingPid() 13689 + ", uid=" + Binder.getCallingUid() 13690 + " without permission " 13691 + android.Manifest.permission.DUMP); 13692 return; 13693 } 13694 13695 DumpState dumpState = new DumpState(); 13696 boolean fullPreferred = false; 13697 boolean checkin = false; 13698 13699 String packageName = null; 13700 13701 int opti = 0; 13702 while (opti < args.length) { 13703 String opt = args[opti]; 13704 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13705 break; 13706 } 13707 opti++; 13708 13709 if ("-a".equals(opt)) { 13710 // Right now we only know how to print all. 13711 } else if ("-h".equals(opt)) { 13712 pw.println("Package manager dump options:"); 13713 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13714 pw.println(" --checkin: dump for a checkin"); 13715 pw.println(" -f: print details of intent filters"); 13716 pw.println(" -h: print this help"); 13717 pw.println(" cmd may be one of:"); 13718 pw.println(" l[ibraries]: list known shared libraries"); 13719 pw.println(" f[ibraries]: list device features"); 13720 pw.println(" k[eysets]: print known keysets"); 13721 pw.println(" r[esolvers]: dump intent resolvers"); 13722 pw.println(" perm[issions]: dump permissions"); 13723 pw.println(" pref[erred]: print preferred package settings"); 13724 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13725 pw.println(" prov[iders]: dump content providers"); 13726 pw.println(" p[ackages]: dump installed packages"); 13727 pw.println(" s[hared-users]: dump shared user IDs"); 13728 pw.println(" m[essages]: print collected runtime messages"); 13729 pw.println(" v[erifiers]: print package verifier info"); 13730 pw.println(" version: print database version info"); 13731 pw.println(" write: write current settings now"); 13732 pw.println(" <package.name>: info about given package"); 13733 pw.println(" installs: details about install sessions"); 13734 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13735 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13736 return; 13737 } else if ("--checkin".equals(opt)) { 13738 checkin = true; 13739 } else if ("-f".equals(opt)) { 13740 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13741 } else { 13742 pw.println("Unknown argument: " + opt + "; use -h for help"); 13743 } 13744 } 13745 13746 // Is the caller requesting to dump a particular piece of data? 13747 if (opti < args.length) { 13748 String cmd = args[opti]; 13749 opti++; 13750 // Is this a package name? 13751 if ("android".equals(cmd) || cmd.contains(".")) { 13752 packageName = cmd; 13753 // When dumping a single package, we always dump all of its 13754 // filter information since the amount of data will be reasonable. 13755 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13756 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13757 dumpState.setDump(DumpState.DUMP_LIBS); 13758 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13759 dumpState.setDump(DumpState.DUMP_FEATURES); 13760 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13761 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13762 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13763 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13764 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13765 dumpState.setDump(DumpState.DUMP_PREFERRED); 13766 } else if ("preferred-xml".equals(cmd)) { 13767 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13768 if (opti < args.length && "--full".equals(args[opti])) { 13769 fullPreferred = true; 13770 opti++; 13771 } 13772 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13773 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13774 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13775 dumpState.setDump(DumpState.DUMP_PACKAGES); 13776 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13777 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13778 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13779 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13780 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13781 dumpState.setDump(DumpState.DUMP_MESSAGES); 13782 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13783 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13784 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13785 || "intent-filter-verifiers".equals(cmd)) { 13786 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13787 } else if ("version".equals(cmd)) { 13788 dumpState.setDump(DumpState.DUMP_VERSION); 13789 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13790 dumpState.setDump(DumpState.DUMP_KEYSETS); 13791 } else if ("installs".equals(cmd)) { 13792 dumpState.setDump(DumpState.DUMP_INSTALLS); 13793 } else if ("write".equals(cmd)) { 13794 synchronized (mPackages) { 13795 mSettings.writeLPr(); 13796 pw.println("Settings written."); 13797 return; 13798 } 13799 } 13800 } 13801 13802 if (checkin) { 13803 pw.println("vers,1"); 13804 } 13805 13806 // reader 13807 synchronized (mPackages) { 13808 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13809 if (!checkin) { 13810 if (dumpState.onTitlePrinted()) 13811 pw.println(); 13812 pw.println("Database versions:"); 13813 pw.print(" SDK Version:"); 13814 pw.print(" internal="); 13815 pw.print(mSettings.mInternalSdkPlatform); 13816 pw.print(" external="); 13817 pw.println(mSettings.mExternalSdkPlatform); 13818 pw.print(" DB Version:"); 13819 pw.print(" internal="); 13820 pw.print(mSettings.mInternalDatabaseVersion); 13821 pw.print(" external="); 13822 pw.println(mSettings.mExternalDatabaseVersion); 13823 } 13824 } 13825 13826 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13827 if (!checkin) { 13828 if (dumpState.onTitlePrinted()) 13829 pw.println(); 13830 pw.println("Verifiers:"); 13831 pw.print(" Required: "); 13832 pw.print(mRequiredVerifierPackage); 13833 pw.print(" (uid="); 13834 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13835 pw.println(")"); 13836 } else if (mRequiredVerifierPackage != null) { 13837 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13838 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13839 } 13840 } 13841 13842 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13843 packageName == null) { 13844 if (mIntentFilterVerifierComponent != null) { 13845 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13846 if (!checkin) { 13847 if (dumpState.onTitlePrinted()) 13848 pw.println(); 13849 pw.println("Intent Filter Verifier:"); 13850 pw.print(" Using: "); 13851 pw.print(verifierPackageName); 13852 pw.print(" (uid="); 13853 pw.print(getPackageUid(verifierPackageName, 0)); 13854 pw.println(")"); 13855 } else if (verifierPackageName != null) { 13856 pw.print("ifv,"); pw.print(verifierPackageName); 13857 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13858 } 13859 } else { 13860 pw.println(); 13861 pw.println("No Intent Filter Verifier available!"); 13862 } 13863 } 13864 13865 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13866 boolean printedHeader = false; 13867 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13868 while (it.hasNext()) { 13869 String name = it.next(); 13870 SharedLibraryEntry ent = mSharedLibraries.get(name); 13871 if (!checkin) { 13872 if (!printedHeader) { 13873 if (dumpState.onTitlePrinted()) 13874 pw.println(); 13875 pw.println("Libraries:"); 13876 printedHeader = true; 13877 } 13878 pw.print(" "); 13879 } else { 13880 pw.print("lib,"); 13881 } 13882 pw.print(name); 13883 if (!checkin) { 13884 pw.print(" -> "); 13885 } 13886 if (ent.path != null) { 13887 if (!checkin) { 13888 pw.print("(jar) "); 13889 pw.print(ent.path); 13890 } else { 13891 pw.print(",jar,"); 13892 pw.print(ent.path); 13893 } 13894 } else { 13895 if (!checkin) { 13896 pw.print("(apk) "); 13897 pw.print(ent.apk); 13898 } else { 13899 pw.print(",apk,"); 13900 pw.print(ent.apk); 13901 } 13902 } 13903 pw.println(); 13904 } 13905 } 13906 13907 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13908 if (dumpState.onTitlePrinted()) 13909 pw.println(); 13910 if (!checkin) { 13911 pw.println("Features:"); 13912 } 13913 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13914 while (it.hasNext()) { 13915 String name = it.next(); 13916 if (!checkin) { 13917 pw.print(" "); 13918 } else { 13919 pw.print("feat,"); 13920 } 13921 pw.println(name); 13922 } 13923 } 13924 13925 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13926 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13927 : "Activity Resolver Table:", " ", packageName, 13928 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13929 dumpState.setTitlePrinted(true); 13930 } 13931 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13932 : "Receiver Resolver Table:", " ", packageName, 13933 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13934 dumpState.setTitlePrinted(true); 13935 } 13936 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13937 : "Service Resolver Table:", " ", packageName, 13938 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13939 dumpState.setTitlePrinted(true); 13940 } 13941 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13942 : "Provider Resolver Table:", " ", packageName, 13943 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13944 dumpState.setTitlePrinted(true); 13945 } 13946 } 13947 13948 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13949 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13950 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13951 int user = mSettings.mPreferredActivities.keyAt(i); 13952 if (pir.dump(pw, 13953 dumpState.getTitlePrinted() 13954 ? "\nPreferred Activities User " + user + ":" 13955 : "Preferred Activities User " + user + ":", " ", 13956 packageName, true, false)) { 13957 dumpState.setTitlePrinted(true); 13958 } 13959 } 13960 } 13961 13962 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13963 pw.flush(); 13964 FileOutputStream fout = new FileOutputStream(fd); 13965 BufferedOutputStream str = new BufferedOutputStream(fout); 13966 XmlSerializer serializer = new FastXmlSerializer(); 13967 try { 13968 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 13969 serializer.startDocument(null, true); 13970 serializer.setFeature( 13971 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13972 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13973 serializer.endDocument(); 13974 serializer.flush(); 13975 } catch (IllegalArgumentException e) { 13976 pw.println("Failed writing: " + e); 13977 } catch (IllegalStateException e) { 13978 pw.println("Failed writing: " + e); 13979 } catch (IOException e) { 13980 pw.println("Failed writing: " + e); 13981 } 13982 } 13983 13984 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13985 pw.println(); 13986 int count = mSettings.mPackages.size(); 13987 if (count == 0) { 13988 pw.println("No domain preferred apps!"); 13989 pw.println(); 13990 } else { 13991 final String prefix = " "; 13992 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13993 if (allPackageSettings.size() == 0) { 13994 pw.println("No domain preferred apps!"); 13995 pw.println(); 13996 } else { 13997 pw.println("Domain preferred apps status:"); 13998 pw.println(); 13999 count = 0; 14000 for (PackageSetting ps : allPackageSettings) { 14001 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14002 if (ivi == null || ivi.getPackageName() == null) continue; 14003 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14004 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14005 pw.println(prefix + "Status: " + ivi.getStatusString()); 14006 pw.println(); 14007 count++; 14008 } 14009 if (count == 0) { 14010 pw.println(prefix + "No domain preferred app status!"); 14011 pw.println(); 14012 } 14013 for (int userId : sUserManager.getUserIds()) { 14014 pw.println("Domain preferred apps for User " + userId + ":"); 14015 pw.println(); 14016 count = 0; 14017 for (PackageSetting ps : allPackageSettings) { 14018 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14019 if (ivi == null || ivi.getPackageName() == null) { 14020 continue; 14021 } 14022 final int status = ps.getDomainVerificationStatusForUser(userId); 14023 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14024 continue; 14025 } 14026 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14027 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14028 String statusStr = IntentFilterVerificationInfo. 14029 getStatusStringFromValue(status); 14030 pw.println(prefix + "Status: " + statusStr); 14031 pw.println(); 14032 count++; 14033 } 14034 if (count == 0) { 14035 pw.println(prefix + "No domain preferred apps!"); 14036 pw.println(); 14037 } 14038 } 14039 } 14040 } 14041 } 14042 14043 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14044 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14045 if (packageName == null) { 14046 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14047 if (iperm == 0) { 14048 if (dumpState.onTitlePrinted()) 14049 pw.println(); 14050 pw.println("AppOp Permissions:"); 14051 } 14052 pw.print(" AppOp Permission "); 14053 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14054 pw.println(":"); 14055 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14056 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14057 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14058 } 14059 } 14060 } 14061 } 14062 14063 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14064 boolean printedSomething = false; 14065 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14066 if (packageName != null && !packageName.equals(p.info.packageName)) { 14067 continue; 14068 } 14069 if (!printedSomething) { 14070 if (dumpState.onTitlePrinted()) 14071 pw.println(); 14072 pw.println("Registered ContentProviders:"); 14073 printedSomething = true; 14074 } 14075 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14076 pw.print(" "); pw.println(p.toString()); 14077 } 14078 printedSomething = false; 14079 for (Map.Entry<String, PackageParser.Provider> entry : 14080 mProvidersByAuthority.entrySet()) { 14081 PackageParser.Provider p = entry.getValue(); 14082 if (packageName != null && !packageName.equals(p.info.packageName)) { 14083 continue; 14084 } 14085 if (!printedSomething) { 14086 if (dumpState.onTitlePrinted()) 14087 pw.println(); 14088 pw.println("ContentProvider Authorities:"); 14089 printedSomething = true; 14090 } 14091 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14092 pw.print(" "); pw.println(p.toString()); 14093 if (p.info != null && p.info.applicationInfo != null) { 14094 final String appInfo = p.info.applicationInfo.toString(); 14095 pw.print(" applicationInfo="); pw.println(appInfo); 14096 } 14097 } 14098 } 14099 14100 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14101 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14102 } 14103 14104 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14105 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14106 } 14107 14108 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14109 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14110 } 14111 14112 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14113 // XXX should handle packageName != null by dumping only install data that 14114 // the given package is involved with. 14115 if (dumpState.onTitlePrinted()) pw.println(); 14116 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14117 } 14118 14119 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14120 if (dumpState.onTitlePrinted()) pw.println(); 14121 mSettings.dumpReadMessagesLPr(pw, dumpState); 14122 14123 pw.println(); 14124 pw.println("Package warning messages:"); 14125 BufferedReader in = null; 14126 String line = null; 14127 try { 14128 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14129 while ((line = in.readLine()) != null) { 14130 if (line.contains("ignored: updated version")) continue; 14131 pw.println(line); 14132 } 14133 } catch (IOException ignored) { 14134 } finally { 14135 IoUtils.closeQuietly(in); 14136 } 14137 } 14138 14139 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14140 BufferedReader in = null; 14141 String line = null; 14142 try { 14143 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14144 while ((line = in.readLine()) != null) { 14145 if (line.contains("ignored: updated version")) continue; 14146 pw.print("msg,"); 14147 pw.println(line); 14148 } 14149 } catch (IOException ignored) { 14150 } finally { 14151 IoUtils.closeQuietly(in); 14152 } 14153 } 14154 } 14155 } 14156 14157 // ------- apps on sdcard specific code ------- 14158 static final boolean DEBUG_SD_INSTALL = false; 14159 14160 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14161 14162 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14163 14164 private boolean mMediaMounted = false; 14165 14166 static String getEncryptKey() { 14167 try { 14168 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14169 SD_ENCRYPTION_KEYSTORE_NAME); 14170 if (sdEncKey == null) { 14171 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14172 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14173 if (sdEncKey == null) { 14174 Slog.e(TAG, "Failed to create encryption keys"); 14175 return null; 14176 } 14177 } 14178 return sdEncKey; 14179 } catch (NoSuchAlgorithmException nsae) { 14180 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14181 return null; 14182 } catch (IOException ioe) { 14183 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14184 return null; 14185 } 14186 } 14187 14188 /* 14189 * Update media status on PackageManager. 14190 */ 14191 @Override 14192 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14193 int callingUid = Binder.getCallingUid(); 14194 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14195 throw new SecurityException("Media status can only be updated by the system"); 14196 } 14197 // reader; this apparently protects mMediaMounted, but should probably 14198 // be a different lock in that case. 14199 synchronized (mPackages) { 14200 Log.i(TAG, "Updating external media status from " 14201 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14202 + (mediaStatus ? "mounted" : "unmounted")); 14203 if (DEBUG_SD_INSTALL) 14204 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14205 + ", mMediaMounted=" + mMediaMounted); 14206 if (mediaStatus == mMediaMounted) { 14207 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14208 : 0, -1); 14209 mHandler.sendMessage(msg); 14210 return; 14211 } 14212 mMediaMounted = mediaStatus; 14213 } 14214 // Queue up an async operation since the package installation may take a 14215 // little while. 14216 mHandler.post(new Runnable() { 14217 public void run() { 14218 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14219 } 14220 }); 14221 } 14222 14223 /** 14224 * Called by MountService when the initial ASECs to scan are available. 14225 * Should block until all the ASEC containers are finished being scanned. 14226 */ 14227 public void scanAvailableAsecs() { 14228 updateExternalMediaStatusInner(true, false, false); 14229 if (mShouldRestoreconData) { 14230 SELinuxMMAC.setRestoreconDone(); 14231 mShouldRestoreconData = false; 14232 } 14233 } 14234 14235 /* 14236 * Collect information of applications on external media, map them against 14237 * existing containers and update information based on current mount status. 14238 * Please note that we always have to report status if reportStatus has been 14239 * set to true especially when unloading packages. 14240 */ 14241 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14242 boolean externalStorage) { 14243 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14244 int[] uidArr = EmptyArray.INT; 14245 14246 final String[] list = PackageHelper.getSecureContainerList(); 14247 if (ArrayUtils.isEmpty(list)) { 14248 Log.i(TAG, "No secure containers found"); 14249 } else { 14250 // Process list of secure containers and categorize them 14251 // as active or stale based on their package internal state. 14252 14253 // reader 14254 synchronized (mPackages) { 14255 for (String cid : list) { 14256 // Leave stages untouched for now; installer service owns them 14257 if (PackageInstallerService.isStageName(cid)) continue; 14258 14259 if (DEBUG_SD_INSTALL) 14260 Log.i(TAG, "Processing container " + cid); 14261 String pkgName = getAsecPackageName(cid); 14262 if (pkgName == null) { 14263 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14264 continue; 14265 } 14266 if (DEBUG_SD_INSTALL) 14267 Log.i(TAG, "Looking for pkg : " + pkgName); 14268 14269 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14270 if (ps == null) { 14271 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14272 continue; 14273 } 14274 14275 /* 14276 * Skip packages that are not external if we're unmounting 14277 * external storage. 14278 */ 14279 if (externalStorage && !isMounted && !isExternal(ps)) { 14280 continue; 14281 } 14282 14283 final AsecInstallArgs args = new AsecInstallArgs(cid, 14284 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14285 // The package status is changed only if the code path 14286 // matches between settings and the container id. 14287 if (ps.codePathString != null 14288 && ps.codePathString.startsWith(args.getCodePath())) { 14289 if (DEBUG_SD_INSTALL) { 14290 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14291 + " at code path: " + ps.codePathString); 14292 } 14293 14294 // We do have a valid package installed on sdcard 14295 processCids.put(args, ps.codePathString); 14296 final int uid = ps.appId; 14297 if (uid != -1) { 14298 uidArr = ArrayUtils.appendInt(uidArr, uid); 14299 } 14300 } else { 14301 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14302 + ps.codePathString); 14303 } 14304 } 14305 } 14306 14307 Arrays.sort(uidArr); 14308 } 14309 14310 // Process packages with valid entries. 14311 if (isMounted) { 14312 if (DEBUG_SD_INSTALL) 14313 Log.i(TAG, "Loading packages"); 14314 loadMediaPackages(processCids, uidArr); 14315 startCleaningPackages(); 14316 mInstallerService.onSecureContainersAvailable(); 14317 } else { 14318 if (DEBUG_SD_INSTALL) 14319 Log.i(TAG, "Unloading packages"); 14320 unloadMediaPackages(processCids, uidArr, reportStatus); 14321 } 14322 } 14323 14324 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14325 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14326 final int size = infos.size(); 14327 final String[] packageNames = new String[size]; 14328 final int[] packageUids = new int[size]; 14329 for (int i = 0; i < size; i++) { 14330 final ApplicationInfo info = infos.get(i); 14331 packageNames[i] = info.packageName; 14332 packageUids[i] = info.uid; 14333 } 14334 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14335 finishedReceiver); 14336 } 14337 14338 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14339 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14340 sendResourcesChangedBroadcast(mediaStatus, replacing, 14341 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14342 } 14343 14344 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14345 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14346 int size = pkgList.length; 14347 if (size > 0) { 14348 // Send broadcasts here 14349 Bundle extras = new Bundle(); 14350 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14351 if (uidArr != null) { 14352 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14353 } 14354 if (replacing) { 14355 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14356 } 14357 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14358 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14359 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14360 } 14361 } 14362 14363 /* 14364 * Look at potentially valid container ids from processCids If package 14365 * information doesn't match the one on record or package scanning fails, 14366 * the cid is added to list of removeCids. We currently don't delete stale 14367 * containers. 14368 */ 14369 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14370 ArrayList<String> pkgList = new ArrayList<String>(); 14371 Set<AsecInstallArgs> keys = processCids.keySet(); 14372 14373 for (AsecInstallArgs args : keys) { 14374 String codePath = processCids.get(args); 14375 if (DEBUG_SD_INSTALL) 14376 Log.i(TAG, "Loading container : " + args.cid); 14377 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14378 try { 14379 // Make sure there are no container errors first. 14380 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14381 Slog.e(TAG, "Failed to mount cid : " + args.cid 14382 + " when installing from sdcard"); 14383 continue; 14384 } 14385 // Check code path here. 14386 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14387 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14388 + " does not match one in settings " + codePath); 14389 continue; 14390 } 14391 // Parse package 14392 int parseFlags = mDefParseFlags; 14393 if (args.isExternalAsec()) { 14394 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14395 } 14396 if (args.isFwdLocked()) { 14397 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14398 } 14399 14400 synchronized (mInstallLock) { 14401 PackageParser.Package pkg = null; 14402 try { 14403 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14404 } catch (PackageManagerException e) { 14405 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14406 } 14407 // Scan the package 14408 if (pkg != null) { 14409 /* 14410 * TODO why is the lock being held? doPostInstall is 14411 * called in other places without the lock. This needs 14412 * to be straightened out. 14413 */ 14414 // writer 14415 synchronized (mPackages) { 14416 retCode = PackageManager.INSTALL_SUCCEEDED; 14417 pkgList.add(pkg.packageName); 14418 // Post process args 14419 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14420 pkg.applicationInfo.uid); 14421 } 14422 } else { 14423 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14424 } 14425 } 14426 14427 } finally { 14428 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14429 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14430 } 14431 } 14432 } 14433 // writer 14434 synchronized (mPackages) { 14435 // If the platform SDK has changed since the last time we booted, 14436 // we need to re-grant app permission to catch any new ones that 14437 // appear. This is really a hack, and means that apps can in some 14438 // cases get permissions that the user didn't initially explicitly 14439 // allow... it would be nice to have some better way to handle 14440 // this situation. 14441 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14442 if (regrantPermissions) 14443 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14444 + mSdkVersion + "; regranting permissions for external storage"); 14445 mSettings.mExternalSdkPlatform = mSdkVersion; 14446 14447 // Make sure group IDs have been assigned, and any permission 14448 // changes in other apps are accounted for 14449 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14450 | (regrantPermissions 14451 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14452 : 0)); 14453 14454 mSettings.updateExternalDatabaseVersion(); 14455 14456 // can downgrade to reader 14457 // Persist settings 14458 mSettings.writeLPr(); 14459 } 14460 // Send a broadcast to let everyone know we are done processing 14461 if (pkgList.size() > 0) { 14462 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14463 } 14464 } 14465 14466 /* 14467 * Utility method to unload a list of specified containers 14468 */ 14469 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14470 // Just unmount all valid containers. 14471 for (AsecInstallArgs arg : cidArgs) { 14472 synchronized (mInstallLock) { 14473 arg.doPostDeleteLI(false); 14474 } 14475 } 14476 } 14477 14478 /* 14479 * Unload packages mounted on external media. This involves deleting package 14480 * data from internal structures, sending broadcasts about diabled packages, 14481 * gc'ing to free up references, unmounting all secure containers 14482 * corresponding to packages on external media, and posting a 14483 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14484 * that we always have to post this message if status has been requested no 14485 * matter what. 14486 */ 14487 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14488 final boolean reportStatus) { 14489 if (DEBUG_SD_INSTALL) 14490 Log.i(TAG, "unloading media packages"); 14491 ArrayList<String> pkgList = new ArrayList<String>(); 14492 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14493 final Set<AsecInstallArgs> keys = processCids.keySet(); 14494 for (AsecInstallArgs args : keys) { 14495 String pkgName = args.getPackageName(); 14496 if (DEBUG_SD_INSTALL) 14497 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14498 // Delete package internally 14499 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14500 synchronized (mInstallLock) { 14501 boolean res = deletePackageLI(pkgName, null, false, null, null, 14502 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14503 if (res) { 14504 pkgList.add(pkgName); 14505 } else { 14506 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14507 failedList.add(args); 14508 } 14509 } 14510 } 14511 14512 // reader 14513 synchronized (mPackages) { 14514 // We didn't update the settings after removing each package; 14515 // write them now for all packages. 14516 mSettings.writeLPr(); 14517 } 14518 14519 // We have to absolutely send UPDATED_MEDIA_STATUS only 14520 // after confirming that all the receivers processed the ordered 14521 // broadcast when packages get disabled, force a gc to clean things up. 14522 // and unload all the containers. 14523 if (pkgList.size() > 0) { 14524 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14525 new IIntentReceiver.Stub() { 14526 public void performReceive(Intent intent, int resultCode, String data, 14527 Bundle extras, boolean ordered, boolean sticky, 14528 int sendingUser) throws RemoteException { 14529 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14530 reportStatus ? 1 : 0, 1, keys); 14531 mHandler.sendMessage(msg); 14532 } 14533 }); 14534 } else { 14535 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14536 keys); 14537 mHandler.sendMessage(msg); 14538 } 14539 } 14540 14541 private void loadPrivatePackages(VolumeInfo vol) { 14542 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14543 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14544 synchronized (mInstallLock) { 14545 synchronized (mPackages) { 14546 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14547 for (PackageSetting ps : packages) { 14548 final PackageParser.Package pkg; 14549 try { 14550 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14551 loaded.add(pkg.applicationInfo); 14552 } catch (PackageManagerException e) { 14553 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14554 } 14555 } 14556 14557 // TODO: regrant any permissions that changed based since original install 14558 14559 mSettings.writeLPr(); 14560 } 14561 } 14562 14563 Slog.d(TAG, "Loaded packages " + loaded); 14564 sendResourcesChangedBroadcast(true, false, loaded, null); 14565 } 14566 14567 private void unloadPrivatePackages(VolumeInfo vol) { 14568 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14569 synchronized (mInstallLock) { 14570 synchronized (mPackages) { 14571 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14572 for (PackageSetting ps : packages) { 14573 if (ps.pkg == null) continue; 14574 14575 final ApplicationInfo info = ps.pkg.applicationInfo; 14576 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14577 if (deletePackageLI(ps.name, null, false, null, null, 14578 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14579 unloaded.add(info); 14580 } else { 14581 Slog.w(TAG, "Failed to unload " + ps.codePath); 14582 } 14583 } 14584 14585 mSettings.writeLPr(); 14586 } 14587 } 14588 14589 Slog.d(TAG, "Unloaded packages " + unloaded); 14590 sendResourcesChangedBroadcast(false, false, unloaded, null); 14591 } 14592 14593 private void unfreezePackage(String packageName) { 14594 synchronized (mPackages) { 14595 final PackageSetting ps = mSettings.mPackages.get(packageName); 14596 if (ps != null) { 14597 ps.frozen = false; 14598 } 14599 } 14600 } 14601 14602 @Override 14603 public int movePackage(final String packageName, final String volumeUuid) { 14604 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14605 14606 final int moveId = mNextMoveId.getAndIncrement(); 14607 try { 14608 movePackageInternal(packageName, volumeUuid, moveId); 14609 } catch (PackageManagerException e) { 14610 Slog.d(TAG, "Failed to move " + packageName, e); 14611 mMoveCallbacks.notifyStatusChanged(moveId, 14612 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14613 } 14614 return moveId; 14615 } 14616 14617 private void movePackageInternal(final String packageName, final String volumeUuid, 14618 final int moveId) throws PackageManagerException { 14619 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14620 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14621 final PackageManager pm = mContext.getPackageManager(); 14622 14623 final boolean currentAsec; 14624 final String currentVolumeUuid; 14625 final File codeFile; 14626 final String installerPackageName; 14627 final String packageAbiOverride; 14628 final int appId; 14629 final String seinfo; 14630 final String label; 14631 14632 // reader 14633 synchronized (mPackages) { 14634 final PackageParser.Package pkg = mPackages.get(packageName); 14635 final PackageSetting ps = mSettings.mPackages.get(packageName); 14636 if (pkg == null || ps == null) { 14637 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14638 } 14639 14640 if (pkg.applicationInfo.isSystemApp()) { 14641 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14642 "Cannot move system application"); 14643 } 14644 14645 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14646 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14647 "Package already moved to " + volumeUuid); 14648 } 14649 14650 final File probe = new File(pkg.codePath); 14651 final File probeOat = new File(probe, "oat"); 14652 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14653 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14654 "Move only supported for modern cluster style installs"); 14655 } 14656 14657 if (ps.frozen) { 14658 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14659 "Failed to move already frozen package"); 14660 } 14661 ps.frozen = true; 14662 14663 currentAsec = pkg.applicationInfo.isForwardLocked() 14664 || pkg.applicationInfo.isExternalAsec(); 14665 currentVolumeUuid = ps.volumeUuid; 14666 codeFile = new File(pkg.codePath); 14667 installerPackageName = ps.installerPackageName; 14668 packageAbiOverride = ps.cpuAbiOverrideString; 14669 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14670 seinfo = pkg.applicationInfo.seinfo; 14671 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14672 } 14673 14674 // Now that we're guarded by frozen state, kill app during move 14675 killApplication(packageName, appId, "move pkg"); 14676 14677 final Bundle extras = new Bundle(); 14678 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14679 extras.putString(Intent.EXTRA_TITLE, label); 14680 mMoveCallbacks.notifyCreated(moveId, extras); 14681 14682 int installFlags; 14683 final boolean moveCompleteApp; 14684 final File measurePath; 14685 14686 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14687 installFlags = INSTALL_INTERNAL; 14688 moveCompleteApp = !currentAsec; 14689 measurePath = Environment.getDataAppDirectory(volumeUuid); 14690 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14691 installFlags = INSTALL_EXTERNAL; 14692 moveCompleteApp = false; 14693 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14694 } else { 14695 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14696 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14697 || !volume.isMountedWritable()) { 14698 unfreezePackage(packageName); 14699 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14700 "Move location not mounted private volume"); 14701 } 14702 14703 Preconditions.checkState(!currentAsec); 14704 14705 installFlags = INSTALL_INTERNAL; 14706 moveCompleteApp = true; 14707 measurePath = Environment.getDataAppDirectory(volumeUuid); 14708 } 14709 14710 final PackageStats stats = new PackageStats(null, -1); 14711 synchronized (mInstaller) { 14712 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14713 unfreezePackage(packageName); 14714 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14715 "Failed to measure package size"); 14716 } 14717 } 14718 14719 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14720 14721 final long startFreeBytes = measurePath.getFreeSpace(); 14722 final long sizeBytes; 14723 if (moveCompleteApp) { 14724 sizeBytes = stats.codeSize + stats.dataSize; 14725 } else { 14726 sizeBytes = stats.codeSize; 14727 } 14728 14729 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14730 unfreezePackage(packageName); 14731 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14732 "Not enough free space to move"); 14733 } 14734 14735 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14736 14737 final CountDownLatch installedLatch = new CountDownLatch(1); 14738 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14739 @Override 14740 public void onUserActionRequired(Intent intent) throws RemoteException { 14741 throw new IllegalStateException(); 14742 } 14743 14744 @Override 14745 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14746 Bundle extras) throws RemoteException { 14747 Slog.d(TAG, "Install result for move: " 14748 + PackageManager.installStatusToString(returnCode, msg)); 14749 14750 installedLatch.countDown(); 14751 14752 // Regardless of success or failure of the move operation, 14753 // always unfreeze the package 14754 unfreezePackage(packageName); 14755 14756 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14757 switch (status) { 14758 case PackageInstaller.STATUS_SUCCESS: 14759 mMoveCallbacks.notifyStatusChanged(moveId, 14760 PackageManager.MOVE_SUCCEEDED); 14761 break; 14762 case PackageInstaller.STATUS_FAILURE_STORAGE: 14763 mMoveCallbacks.notifyStatusChanged(moveId, 14764 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14765 break; 14766 default: 14767 mMoveCallbacks.notifyStatusChanged(moveId, 14768 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14769 break; 14770 } 14771 } 14772 }; 14773 14774 final MoveInfo move; 14775 if (moveCompleteApp) { 14776 // Kick off a thread to report progress estimates 14777 new Thread() { 14778 @Override 14779 public void run() { 14780 while (true) { 14781 try { 14782 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14783 break; 14784 } 14785 } catch (InterruptedException ignored) { 14786 } 14787 14788 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14789 final int progress = 10 + (int) MathUtils.constrain( 14790 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14791 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14792 } 14793 } 14794 }.start(); 14795 14796 final String dataAppName = codeFile.getName(); 14797 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14798 dataAppName, appId, seinfo); 14799 } else { 14800 move = null; 14801 } 14802 14803 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14804 14805 final Message msg = mHandler.obtainMessage(INIT_COPY); 14806 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14807 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14808 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14809 mHandler.sendMessage(msg); 14810 } 14811 14812 @Override 14813 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14814 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14815 14816 final int realMoveId = mNextMoveId.getAndIncrement(); 14817 final Bundle extras = new Bundle(); 14818 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14819 mMoveCallbacks.notifyCreated(realMoveId, extras); 14820 14821 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14822 @Override 14823 public void onCreated(int moveId, Bundle extras) { 14824 // Ignored 14825 } 14826 14827 @Override 14828 public void onStatusChanged(int moveId, int status, long estMillis) { 14829 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14830 } 14831 }; 14832 14833 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14834 storage.setPrimaryStorageUuid(volumeUuid, callback); 14835 return realMoveId; 14836 } 14837 14838 @Override 14839 public int getMoveStatus(int moveId) { 14840 mContext.enforceCallingOrSelfPermission( 14841 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14842 return mMoveCallbacks.mLastStatus.get(moveId); 14843 } 14844 14845 @Override 14846 public void registerMoveCallback(IPackageMoveObserver callback) { 14847 mContext.enforceCallingOrSelfPermission( 14848 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14849 mMoveCallbacks.register(callback); 14850 } 14851 14852 @Override 14853 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14854 mContext.enforceCallingOrSelfPermission( 14855 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14856 mMoveCallbacks.unregister(callback); 14857 } 14858 14859 @Override 14860 public boolean setInstallLocation(int loc) { 14861 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14862 null); 14863 if (getInstallLocation() == loc) { 14864 return true; 14865 } 14866 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14867 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14868 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14869 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14870 return true; 14871 } 14872 return false; 14873 } 14874 14875 @Override 14876 public int getInstallLocation() { 14877 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14878 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14879 PackageHelper.APP_INSTALL_AUTO); 14880 } 14881 14882 /** Called by UserManagerService */ 14883 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14884 mDirtyUsers.remove(userHandle); 14885 mSettings.removeUserLPw(userHandle); 14886 mPendingBroadcasts.remove(userHandle); 14887 if (mInstaller != null) { 14888 // Technically, we shouldn't be doing this with the package lock 14889 // held. However, this is very rare, and there is already so much 14890 // other disk I/O going on, that we'll let it slide for now. 14891 final StorageManager storage = StorageManager.from(mContext); 14892 final List<VolumeInfo> vols = storage.getVolumes(); 14893 for (VolumeInfo vol : vols) { 14894 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14895 final String volumeUuid = vol.getFsUuid(); 14896 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14897 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14898 } 14899 } 14900 } 14901 mUserNeedsBadging.delete(userHandle); 14902 removeUnusedPackagesLILPw(userManager, userHandle); 14903 } 14904 14905 /** 14906 * We're removing userHandle and would like to remove any downloaded packages 14907 * that are no longer in use by any other user. 14908 * @param userHandle the user being removed 14909 */ 14910 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14911 final boolean DEBUG_CLEAN_APKS = false; 14912 int [] users = userManager.getUserIdsLPr(); 14913 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14914 while (psit.hasNext()) { 14915 PackageSetting ps = psit.next(); 14916 if (ps.pkg == null) { 14917 continue; 14918 } 14919 final String packageName = ps.pkg.packageName; 14920 // Skip over if system app 14921 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14922 continue; 14923 } 14924 if (DEBUG_CLEAN_APKS) { 14925 Slog.i(TAG, "Checking package " + packageName); 14926 } 14927 boolean keep = false; 14928 for (int i = 0; i < users.length; i++) { 14929 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14930 keep = true; 14931 if (DEBUG_CLEAN_APKS) { 14932 Slog.i(TAG, " Keeping package " + packageName + " for user " 14933 + users[i]); 14934 } 14935 break; 14936 } 14937 } 14938 if (!keep) { 14939 if (DEBUG_CLEAN_APKS) { 14940 Slog.i(TAG, " Removing package " + packageName); 14941 } 14942 mHandler.post(new Runnable() { 14943 public void run() { 14944 deletePackageX(packageName, userHandle, 0); 14945 } //end run 14946 }); 14947 } 14948 } 14949 } 14950 14951 /** Called by UserManagerService */ 14952 void createNewUserLILPw(int userHandle, File path) { 14953 if (mInstaller != null) { 14954 mInstaller.createUserConfig(userHandle); 14955 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14956 } 14957 } 14958 14959 void newUserCreatedLILPw(int userHandle) { 14960 // Adding a user requires updating runtime permissions for system apps. 14961 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14962 } 14963 14964 @Override 14965 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14966 mContext.enforceCallingOrSelfPermission( 14967 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14968 "Only package verification agents can read the verifier device identity"); 14969 14970 synchronized (mPackages) { 14971 return mSettings.getVerifierDeviceIdentityLPw(); 14972 } 14973 } 14974 14975 @Override 14976 public void setPermissionEnforced(String permission, boolean enforced) { 14977 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14978 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14979 synchronized (mPackages) { 14980 if (mSettings.mReadExternalStorageEnforced == null 14981 || mSettings.mReadExternalStorageEnforced != enforced) { 14982 mSettings.mReadExternalStorageEnforced = enforced; 14983 mSettings.writeLPr(); 14984 } 14985 } 14986 // kill any non-foreground processes so we restart them and 14987 // grant/revoke the GID. 14988 final IActivityManager am = ActivityManagerNative.getDefault(); 14989 if (am != null) { 14990 final long token = Binder.clearCallingIdentity(); 14991 try { 14992 am.killProcessesBelowForeground("setPermissionEnforcement"); 14993 } catch (RemoteException e) { 14994 } finally { 14995 Binder.restoreCallingIdentity(token); 14996 } 14997 } 14998 } else { 14999 throw new IllegalArgumentException("No selective enforcement for " + permission); 15000 } 15001 } 15002 15003 @Override 15004 @Deprecated 15005 public boolean isPermissionEnforced(String permission) { 15006 return true; 15007 } 15008 15009 @Override 15010 public boolean isStorageLow() { 15011 final long token = Binder.clearCallingIdentity(); 15012 try { 15013 final DeviceStorageMonitorInternal 15014 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15015 if (dsm != null) { 15016 return dsm.isMemoryLow(); 15017 } else { 15018 return false; 15019 } 15020 } finally { 15021 Binder.restoreCallingIdentity(token); 15022 } 15023 } 15024 15025 @Override 15026 public IPackageInstaller getPackageInstaller() { 15027 return mInstallerService; 15028 } 15029 15030 private boolean userNeedsBadging(int userId) { 15031 int index = mUserNeedsBadging.indexOfKey(userId); 15032 if (index < 0) { 15033 final UserInfo userInfo; 15034 final long token = Binder.clearCallingIdentity(); 15035 try { 15036 userInfo = sUserManager.getUserInfo(userId); 15037 } finally { 15038 Binder.restoreCallingIdentity(token); 15039 } 15040 final boolean b; 15041 if (userInfo != null && userInfo.isManagedProfile()) { 15042 b = true; 15043 } else { 15044 b = false; 15045 } 15046 mUserNeedsBadging.put(userId, b); 15047 return b; 15048 } 15049 return mUserNeedsBadging.valueAt(index); 15050 } 15051 15052 @Override 15053 public KeySet getKeySetByAlias(String packageName, String alias) { 15054 if (packageName == null || alias == null) { 15055 return null; 15056 } 15057 synchronized(mPackages) { 15058 final PackageParser.Package pkg = mPackages.get(packageName); 15059 if (pkg == null) { 15060 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15061 throw new IllegalArgumentException("Unknown package: " + packageName); 15062 } 15063 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15064 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15065 } 15066 } 15067 15068 @Override 15069 public KeySet getSigningKeySet(String packageName) { 15070 if (packageName == null) { 15071 return null; 15072 } 15073 synchronized(mPackages) { 15074 final PackageParser.Package pkg = mPackages.get(packageName); 15075 if (pkg == null) { 15076 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15077 throw new IllegalArgumentException("Unknown package: " + packageName); 15078 } 15079 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15080 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15081 throw new SecurityException("May not access signing KeySet of other apps."); 15082 } 15083 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15084 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15085 } 15086 } 15087 15088 @Override 15089 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15090 if (packageName == null || ks == null) { 15091 return false; 15092 } 15093 synchronized(mPackages) { 15094 final PackageParser.Package pkg = mPackages.get(packageName); 15095 if (pkg == null) { 15096 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15097 throw new IllegalArgumentException("Unknown package: " + packageName); 15098 } 15099 IBinder ksh = ks.getToken(); 15100 if (ksh instanceof KeySetHandle) { 15101 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15102 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15103 } 15104 return false; 15105 } 15106 } 15107 15108 @Override 15109 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15110 if (packageName == null || ks == null) { 15111 return false; 15112 } 15113 synchronized(mPackages) { 15114 final PackageParser.Package pkg = mPackages.get(packageName); 15115 if (pkg == null) { 15116 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15117 throw new IllegalArgumentException("Unknown package: " + packageName); 15118 } 15119 IBinder ksh = ks.getToken(); 15120 if (ksh instanceof KeySetHandle) { 15121 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15122 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15123 } 15124 return false; 15125 } 15126 } 15127 15128 public void getUsageStatsIfNoPackageUsageInfo() { 15129 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15130 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15131 if (usm == null) { 15132 throw new IllegalStateException("UsageStatsManager must be initialized"); 15133 } 15134 long now = System.currentTimeMillis(); 15135 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15136 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15137 String packageName = entry.getKey(); 15138 PackageParser.Package pkg = mPackages.get(packageName); 15139 if (pkg == null) { 15140 continue; 15141 } 15142 UsageStats usage = entry.getValue(); 15143 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15144 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15145 } 15146 } 15147 } 15148 15149 /** 15150 * Check and throw if the given before/after packages would be considered a 15151 * downgrade. 15152 */ 15153 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15154 throws PackageManagerException { 15155 if (after.versionCode < before.mVersionCode) { 15156 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15157 "Update version code " + after.versionCode + " is older than current " 15158 + before.mVersionCode); 15159 } else if (after.versionCode == before.mVersionCode) { 15160 if (after.baseRevisionCode < before.baseRevisionCode) { 15161 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15162 "Update base revision code " + after.baseRevisionCode 15163 + " is older than current " + before.baseRevisionCode); 15164 } 15165 15166 if (!ArrayUtils.isEmpty(after.splitNames)) { 15167 for (int i = 0; i < after.splitNames.length; i++) { 15168 final String splitName = after.splitNames[i]; 15169 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15170 if (j != -1) { 15171 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15172 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15173 "Update split " + splitName + " revision code " 15174 + after.splitRevisionCodes[i] + " is older than current " 15175 + before.splitRevisionCodes[j]); 15176 } 15177 } 15178 } 15179 } 15180 } 15181 } 15182 15183 private static class MoveCallbacks extends Handler { 15184 private static final int MSG_CREATED = 1; 15185 private static final int MSG_STATUS_CHANGED = 2; 15186 15187 private final RemoteCallbackList<IPackageMoveObserver> 15188 mCallbacks = new RemoteCallbackList<>(); 15189 15190 private final SparseIntArray mLastStatus = new SparseIntArray(); 15191 15192 public MoveCallbacks(Looper looper) { 15193 super(looper); 15194 } 15195 15196 public void register(IPackageMoveObserver callback) { 15197 mCallbacks.register(callback); 15198 } 15199 15200 public void unregister(IPackageMoveObserver callback) { 15201 mCallbacks.unregister(callback); 15202 } 15203 15204 @Override 15205 public void handleMessage(Message msg) { 15206 final SomeArgs args = (SomeArgs) msg.obj; 15207 final int n = mCallbacks.beginBroadcast(); 15208 for (int i = 0; i < n; i++) { 15209 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15210 try { 15211 invokeCallback(callback, msg.what, args); 15212 } catch (RemoteException ignored) { 15213 } 15214 } 15215 mCallbacks.finishBroadcast(); 15216 args.recycle(); 15217 } 15218 15219 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15220 throws RemoteException { 15221 switch (what) { 15222 case MSG_CREATED: { 15223 callback.onCreated(args.argi1, (Bundle) args.arg2); 15224 break; 15225 } 15226 case MSG_STATUS_CHANGED: { 15227 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15228 break; 15229 } 15230 } 15231 } 15232 15233 private void notifyCreated(int moveId, Bundle extras) { 15234 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15235 15236 final SomeArgs args = SomeArgs.obtain(); 15237 args.argi1 = moveId; 15238 args.arg2 = extras; 15239 obtainMessage(MSG_CREATED, args).sendToTarget(); 15240 } 15241 15242 private void notifyStatusChanged(int moveId, int status) { 15243 notifyStatusChanged(moveId, status, -1); 15244 } 15245 15246 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15247 Slog.v(TAG, "Move " + moveId + " status " + status); 15248 15249 final SomeArgs args = SomeArgs.obtain(); 15250 args.argi1 = moveId; 15251 args.argi2 = status; 15252 args.arg3 = estMillis; 15253 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15254 15255 synchronized (mLastStatus) { 15256 mLastStatus.put(moveId, status); 15257 } 15258 } 15259 } 15260} 15261