PackageManagerService.java revision c293d3ad1a4fbbf616d4dfb041eb9cbf45262b45
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.IOnPermissionsChangeListener; 96import android.content.pm.IPackageDataObserver; 97import android.content.pm.IPackageDeleteObserver; 98import android.content.pm.IPackageDeleteObserver2; 99import android.content.pm.IPackageInstallObserver2; 100import android.content.pm.IPackageInstaller; 101import android.content.pm.IPackageManager; 102import android.content.pm.IPackageMoveObserver; 103import android.content.pm.IPackageStatsObserver; 104import android.content.pm.InstrumentationInfo; 105import android.content.pm.IntentFilterVerificationInfo; 106import android.content.pm.KeySet; 107import android.content.pm.ManifestDigest; 108import android.content.pm.PackageCleanItem; 109import android.content.pm.PackageInfo; 110import android.content.pm.PackageInfoLite; 111import android.content.pm.PackageInstaller; 112import android.content.pm.PackageManager; 113import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 114import android.content.pm.PackageParser; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageStats; 119import android.content.pm.PackageUserState; 120import android.content.pm.ParceledListSlice; 121import android.content.pm.PermissionGroupInfo; 122import android.content.pm.PermissionInfo; 123import android.content.pm.ProviderInfo; 124import android.content.pm.ResolveInfo; 125import android.content.pm.ServiceInfo; 126import android.content.pm.Signature; 127import android.content.pm.UserInfo; 128import android.content.pm.VerificationParams; 129import android.content.pm.VerifierDeviceIdentity; 130import android.content.pm.VerifierInfo; 131import android.content.res.Resources; 132import android.hardware.display.DisplayManager; 133import android.net.Uri; 134import android.os.Binder; 135import android.os.Build; 136import android.os.Bundle; 137import android.os.Debug; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.FileUtils; 141import android.os.Handler; 142import android.os.IBinder; 143import android.os.Looper; 144import android.os.Message; 145import android.os.Parcel; 146import android.os.ParcelFileDescriptor; 147import android.os.Process; 148import android.os.RemoteCallbackList; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.os.storage.IMountService; 157import android.os.storage.StorageEventListener; 158import android.os.storage.StorageManager; 159import android.os.storage.VolumeInfo; 160import android.os.storage.VolumeRecord; 161import android.security.KeyStore; 162import android.security.SystemKeyStore; 163import android.system.ErrnoException; 164import android.system.Os; 165import android.system.StructStat; 166import android.text.TextUtils; 167import android.text.format.DateUtils; 168import android.util.ArrayMap; 169import android.util.ArraySet; 170import android.util.AtomicFile; 171import android.util.DisplayMetrics; 172import android.util.EventLog; 173import android.util.ExceptionUtils; 174import android.util.Log; 175import android.util.LogPrinter; 176import android.util.MathUtils; 177import android.util.PrintStreamPrinter; 178import android.util.Slog; 179import android.util.SparseArray; 180import android.util.SparseBooleanArray; 181import android.util.SparseIntArray; 182import android.util.Xml; 183import android.view.Display; 184 185import dalvik.system.DexFile; 186import dalvik.system.VMRuntime; 187 188import libcore.io.IoUtils; 189import libcore.util.EmptyArray; 190 191import com.android.internal.R; 192import com.android.internal.app.IMediaContainerService; 193import com.android.internal.app.ResolverActivity; 194import com.android.internal.content.NativeLibraryHelper; 195import com.android.internal.content.PackageHelper; 196import com.android.internal.os.IParcelFileDescriptorFactory; 197import com.android.internal.os.SomeArgs; 198import com.android.internal.util.ArrayUtils; 199import com.android.internal.util.FastPrintWriter; 200import com.android.internal.util.FastXmlSerializer; 201import com.android.internal.util.IndentingPrintWriter; 202import com.android.internal.util.Preconditions; 203import com.android.server.EventLogTags; 204import com.android.server.FgThread; 205import com.android.server.IntentResolver; 206import com.android.server.LocalServices; 207import com.android.server.ServiceThread; 208import com.android.server.SystemConfig; 209import com.android.server.Watchdog; 210import com.android.server.pm.Settings.DatabaseVersion; 211import com.android.server.pm.PermissionsState.PermissionState; 212import com.android.server.storage.DeviceStorageMonitorInternal; 213 214import org.xmlpull.v1.XmlPullParser; 215import org.xmlpull.v1.XmlSerializer; 216 217import java.io.BufferedInputStream; 218import java.io.BufferedOutputStream; 219import java.io.BufferedReader; 220import java.io.ByteArrayInputStream; 221import java.io.ByteArrayOutputStream; 222import java.io.File; 223import java.io.FileDescriptor; 224import java.io.FileNotFoundException; 225import java.io.FileOutputStream; 226import java.io.FileReader; 227import java.io.FilenameFilter; 228import java.io.IOException; 229import java.io.InputStream; 230import java.io.PrintWriter; 231import java.nio.charset.StandardCharsets; 232import java.security.NoSuchAlgorithmException; 233import java.security.PublicKey; 234import java.security.cert.CertificateEncodingException; 235import java.security.cert.CertificateException; 236import java.text.SimpleDateFormat; 237import java.util.ArrayList; 238import java.util.Arrays; 239import java.util.Collection; 240import java.util.Collections; 241import java.util.Comparator; 242import java.util.Date; 243import java.util.Iterator; 244import java.util.List; 245import java.util.Map; 246import java.util.Objects; 247import java.util.Set; 248import java.util.concurrent.CountDownLatch; 249import java.util.concurrent.TimeUnit; 250import java.util.concurrent.atomic.AtomicBoolean; 251import java.util.concurrent.atomic.AtomicInteger; 252import java.util.concurrent.atomic.AtomicLong; 253 254/** 255 * Keep track of all those .apks everywhere. 256 * 257 * This is very central to the platform's security; please run the unit 258 * tests whenever making modifications here: 259 * 260mmm frameworks/base/tests/AndroidTests 261adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 262adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 263 * 264 * {@hide} 265 */ 266public class PackageManagerService extends IPackageManager.Stub { 267 static final String TAG = "PackageManager"; 268 static final boolean DEBUG_SETTINGS = false; 269 static final boolean DEBUG_PREFERRED = false; 270 static final boolean DEBUG_UPGRADE = false; 271 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 272 private static final boolean DEBUG_BACKUP = true; 273 private static final boolean DEBUG_INSTALL = false; 274 private static final boolean DEBUG_REMOVE = false; 275 private static final boolean DEBUG_BROADCASTS = false; 276 private static final boolean DEBUG_SHOW_INFO = false; 277 private static final boolean DEBUG_PACKAGE_INFO = false; 278 private static final boolean DEBUG_INTENT_MATCHING = false; 279 private static final boolean DEBUG_PACKAGE_SCANNING = false; 280 private static final boolean DEBUG_VERIFY = false; 281 private static final boolean DEBUG_DEXOPT = false; 282 private static final boolean DEBUG_ABI_SELECTION = false; 283 284 private static final int RADIO_UID = Process.PHONE_UID; 285 private static final int LOG_UID = Process.LOG_UID; 286 private static final int NFC_UID = Process.NFC_UID; 287 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 288 private static final int SHELL_UID = Process.SHELL_UID; 289 290 // Cap the size of permission trees that 3rd party apps can define 291 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 292 293 // Suffix used during package installation when copying/moving 294 // package apks to install directory. 295 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 296 297 static final int SCAN_NO_DEX = 1<<1; 298 static final int SCAN_FORCE_DEX = 1<<2; 299 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 300 static final int SCAN_NEW_INSTALL = 1<<4; 301 static final int SCAN_NO_PATHS = 1<<5; 302 static final int SCAN_UPDATE_TIME = 1<<6; 303 static final int SCAN_DEFER_DEX = 1<<7; 304 static final int SCAN_BOOTING = 1<<8; 305 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 306 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 307 static final int SCAN_REQUIRE_KNOWN = 1<<12; 308 static final int SCAN_MOVE = 1<<13; 309 static final int SCAN_INITIAL = 1<<14; 310 311 static final int REMOVE_CHATTY = 1<<16; 312 313 private static final int[] EMPTY_INT_ARRAY = new int[0]; 314 315 /** 316 * Timeout (in milliseconds) after which the watchdog should declare that 317 * our handler thread is wedged. The usual default for such things is one 318 * minute but we sometimes do very lengthy I/O operations on this thread, 319 * such as installing multi-gigabyte applications, so ours needs to be longer. 320 */ 321 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 322 323 /** 324 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 325 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 326 * settings entry if available, otherwise we use the hardcoded default. If it's been 327 * more than this long since the last fstrim, we force one during the boot sequence. 328 * 329 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 330 * one gets run at the next available charging+idle time. This final mandatory 331 * no-fstrim check kicks in only of the other scheduling criteria is never met. 332 */ 333 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 334 335 /** 336 * Whether verification is enabled by default. 337 */ 338 private static final boolean DEFAULT_VERIFY_ENABLE = true; 339 340 /** 341 * The default maximum time to wait for the verification agent to return in 342 * milliseconds. 343 */ 344 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 345 346 /** 347 * The default response for package verification timeout. 348 * 349 * This can be either PackageManager.VERIFICATION_ALLOW or 350 * PackageManager.VERIFICATION_REJECT. 351 */ 352 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 353 354 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 355 356 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 357 DEFAULT_CONTAINER_PACKAGE, 358 "com.android.defcontainer.DefaultContainerService"); 359 360 private static final String KILL_APP_REASON_GIDS_CHANGED = 361 "permission grant or revoke changed gids"; 362 363 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 364 "permissions revoked"; 365 366 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 367 368 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 369 370 /** Permission grant: not grant the permission. */ 371 private static final int GRANT_DENIED = 1; 372 373 /** Permission grant: grant the permission as an install permission. */ 374 private static final int GRANT_INSTALL = 2; 375 376 /** Permission grant: grant the permission as an install permission for a legacy app. */ 377 private static final int GRANT_INSTALL_LEGACY = 3; 378 379 /** Permission grant: grant the permission as a runtime one. */ 380 private static final int GRANT_RUNTIME = 4; 381 382 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 383 private static final int GRANT_UPGRADE = 5; 384 385 final ServiceThread mHandlerThread; 386 387 final PackageHandler mHandler; 388 389 /** 390 * Messages for {@link #mHandler} that need to wait for system ready before 391 * being dispatched. 392 */ 393 private ArrayList<Message> mPostSystemReadyMessages; 394 395 final int mSdkVersion = Build.VERSION.SDK_INT; 396 397 final Context mContext; 398 final boolean mFactoryTest; 399 final boolean mOnlyCore; 400 final boolean mLazyDexOpt; 401 final long mDexOptLRUThresholdInMills; 402 final DisplayMetrics mMetrics; 403 final int mDefParseFlags; 404 final String[] mSeparateProcesses; 405 final boolean mIsUpgrade; 406 407 // This is where all application persistent data goes. 408 final File mAppDataDir; 409 410 // This is where all application persistent data goes for secondary users. 411 final File mUserAppDataDir; 412 413 /** The location for ASEC container files on internal storage. */ 414 final String mAsecInternalPath; 415 416 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 417 // LOCK HELD. Can be called with mInstallLock held. 418 final Installer mInstaller; 419 420 /** Directory where installed third-party apps stored */ 421 final File mAppInstallDir; 422 423 /** 424 * Directory to which applications installed internally have their 425 * 32 bit native libraries copied. 426 */ 427 private File mAppLib32InstallDir; 428 429 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 430 // apps. 431 final File mDrmAppPrivateInstallDir; 432 433 // ---------------------------------------------------------------- 434 435 // Lock for state used when installing and doing other long running 436 // operations. Methods that must be called with this lock held have 437 // the suffix "LI". 438 final Object mInstallLock = new Object(); 439 440 // ---------------------------------------------------------------- 441 442 // Keys are String (package name), values are Package. This also serves 443 // as the lock for the global state. Methods that must be called with 444 // this lock held have the prefix "LP". 445 final ArrayMap<String, PackageParser.Package> mPackages = 446 new ArrayMap<String, PackageParser.Package>(); 447 448 // Tracks available target package names -> overlay package paths. 449 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 450 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 451 452 final Settings mSettings; 453 boolean mRestoredSettings; 454 455 // System configuration read by SystemConfig. 456 final int[] mGlobalGids; 457 final SparseArray<ArraySet<String>> mSystemPermissions; 458 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 459 460 // If mac_permissions.xml was found for seinfo labeling. 461 boolean mFoundPolicyFile; 462 463 // If a recursive restorecon of /data/data/<pkg> is needed. 464 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 465 466 public static final class SharedLibraryEntry { 467 public final String path; 468 public final String apk; 469 470 SharedLibraryEntry(String _path, String _apk) { 471 path = _path; 472 apk = _apk; 473 } 474 } 475 476 // Currently known shared libraries. 477 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 478 new ArrayMap<String, SharedLibraryEntry>(); 479 480 // All available activities, for your resolving pleasure. 481 final ActivityIntentResolver mActivities = 482 new ActivityIntentResolver(); 483 484 // All available receivers, for your resolving pleasure. 485 final ActivityIntentResolver mReceivers = 486 new ActivityIntentResolver(); 487 488 // All available services, for your resolving pleasure. 489 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 490 491 // All available providers, for your resolving pleasure. 492 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 493 494 // Mapping from provider base names (first directory in content URI codePath) 495 // to the provider information. 496 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 497 new ArrayMap<String, PackageParser.Provider>(); 498 499 // Mapping from instrumentation class names to info about them. 500 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 501 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 502 503 // Mapping from permission names to info about them. 504 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 505 new ArrayMap<String, PackageParser.PermissionGroup>(); 506 507 // Packages whose data we have transfered into another package, thus 508 // should no longer exist. 509 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 510 511 // Broadcast actions that are only available to the system. 512 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 513 514 /** List of packages waiting for verification. */ 515 final SparseArray<PackageVerificationState> mPendingVerification 516 = new SparseArray<PackageVerificationState>(); 517 518 /** Set of packages associated with each app op permission. */ 519 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 520 521 final PackageInstallerService mInstallerService; 522 523 private final PackageDexOptimizer mPackageDexOptimizer; 524 525 private AtomicInteger mNextMoveId = new AtomicInteger(); 526 private final MoveCallbacks mMoveCallbacks; 527 528 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 529 530 // Cache of users who need badging. 531 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 532 533 /** Token for keys in mPendingVerification. */ 534 private int mPendingVerificationToken = 0; 535 536 volatile boolean mSystemReady; 537 volatile boolean mSafeMode; 538 volatile boolean mHasSystemUidErrors; 539 540 ApplicationInfo mAndroidApplication; 541 final ActivityInfo mResolveActivity = new ActivityInfo(); 542 final ResolveInfo mResolveInfo = new ResolveInfo(); 543 ComponentName mResolveComponentName; 544 PackageParser.Package mPlatformPackage; 545 ComponentName mCustomResolverComponentName; 546 547 boolean mResolverReplaced = false; 548 549 private final ComponentName mIntentFilterVerifierComponent; 550 private int mIntentFilterVerificationToken = 0; 551 552 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 553 = new SparseArray<IntentFilterVerificationState>(); 554 555 private interface IntentFilterVerifier<T extends IntentFilter> { 556 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 557 T filter, String packageName); 558 void startVerifications(int userId); 559 void receiveVerificationResponse(int verificationId); 560 } 561 562 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 563 private Context mContext; 564 private ComponentName mIntentFilterVerifierComponent; 565 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 566 567 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 568 mContext = context; 569 mIntentFilterVerifierComponent = verifierComponent; 570 } 571 572 private String getDefaultScheme() { 573 return IntentFilter.SCHEME_HTTPS; 574 } 575 576 @Override 577 public void startVerifications(int userId) { 578 // Launch verifications requests 579 int count = mCurrentIntentFilterVerifications.size(); 580 for (int n=0; n<count; n++) { 581 int verificationId = mCurrentIntentFilterVerifications.get(n); 582 final IntentFilterVerificationState ivs = 583 mIntentFilterVerificationStates.get(verificationId); 584 585 String packageName = ivs.getPackageName(); 586 587 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 588 final int filterCount = filters.size(); 589 ArraySet<String> domainsSet = new ArraySet<>(); 590 for (int m=0; m<filterCount; m++) { 591 PackageParser.ActivityIntentInfo filter = filters.get(m); 592 domainsSet.addAll(filter.getHostsList()); 593 } 594 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 595 synchronized (mPackages) { 596 if (mSettings.createIntentFilterVerificationIfNeededLPw( 597 packageName, domainsList) != null) { 598 scheduleWriteSettingsLocked(); 599 } 600 } 601 sendVerificationRequest(userId, verificationId, ivs); 602 } 603 mCurrentIntentFilterVerifications.clear(); 604 } 605 606 private void sendVerificationRequest(int userId, int verificationId, 607 IntentFilterVerificationState ivs) { 608 609 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 610 verificationIntent.putExtra( 611 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 612 verificationId); 613 verificationIntent.putExtra( 614 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 615 getDefaultScheme()); 616 verificationIntent.putExtra( 617 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 618 ivs.getHostsString()); 619 verificationIntent.putExtra( 620 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 621 ivs.getPackageName()); 622 verificationIntent.setComponent(mIntentFilterVerifierComponent); 623 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 624 625 UserHandle user = new UserHandle(userId); 626 mContext.sendBroadcastAsUser(verificationIntent, user); 627 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 628 "Sending IntenFilter verification broadcast"); 629 } 630 631 public void receiveVerificationResponse(int verificationId) { 632 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 633 634 final boolean verified = ivs.isVerified(); 635 636 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 637 final int count = filters.size(); 638 for (int n=0; n<count; n++) { 639 PackageParser.ActivityIntentInfo filter = filters.get(n); 640 filter.setVerified(verified); 641 642 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 643 + " verified with result:" + verified + " and hosts:" 644 + ivs.getHostsString()); 645 } 646 647 mIntentFilterVerificationStates.remove(verificationId); 648 649 final String packageName = ivs.getPackageName(); 650 IntentFilterVerificationInfo ivi = null; 651 652 synchronized (mPackages) { 653 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 654 } 655 if (ivi == null) { 656 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 657 + verificationId + " packageName:" + packageName); 658 return; 659 } 660 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 661 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 662 663 synchronized (mPackages) { 664 if (verified) { 665 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 666 } else { 667 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 668 } 669 scheduleWriteSettingsLocked(); 670 671 final int userId = ivs.getUserId(); 672 if (userId != UserHandle.USER_ALL) { 673 final int userStatus = 674 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 675 676 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 677 boolean needUpdate = false; 678 679 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 680 // already been set by the User thru the Disambiguation dialog 681 switch (userStatus) { 682 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 683 if (verified) { 684 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 685 } else { 686 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 687 } 688 needUpdate = true; 689 break; 690 691 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 692 if (verified) { 693 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 694 needUpdate = true; 695 } 696 break; 697 698 default: 699 // Nothing to do 700 } 701 702 if (needUpdate) { 703 mSettings.updateIntentFilterVerificationStatusLPw( 704 packageName, updatedStatus, userId); 705 scheduleWritePackageRestrictionsLocked(userId); 706 } 707 } 708 } 709 } 710 711 @Override 712 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 713 ActivityIntentInfo filter, String packageName) { 714 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 715 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 716 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 717 "IntentFilter does not contain HTTP nor HTTPS data scheme"); 718 return false; 719 } 720 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 721 if (ivs == null) { 722 ivs = createDomainVerificationState(verifierId, userId, verificationId, 723 packageName); 724 } 725 if (!hasValidDomains(filter)) { 726 return false; 727 } 728 ivs.addFilter(filter); 729 return true; 730 } 731 732 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 733 int userId, int verificationId, String packageName) { 734 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 735 verifierId, userId, packageName); 736 ivs.setPendingState(); 737 synchronized (mPackages) { 738 mIntentFilterVerificationStates.append(verificationId, ivs); 739 mCurrentIntentFilterVerifications.add(verificationId); 740 } 741 return ivs; 742 } 743 } 744 745 private static boolean hasValidDomains(ActivityIntentInfo filter) { 746 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 747 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 748 if (!hasHTTPorHTTPS) { 749 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 750 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 751 return false; 752 } 753 return true; 754 } 755 756 private IntentFilterVerifier mIntentFilterVerifier; 757 758 // Set of pending broadcasts for aggregating enable/disable of components. 759 static class PendingPackageBroadcasts { 760 // for each user id, a map of <package name -> components within that package> 761 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 762 763 public PendingPackageBroadcasts() { 764 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 765 } 766 767 public ArrayList<String> get(int userId, String packageName) { 768 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 769 return packages.get(packageName); 770 } 771 772 public void put(int userId, String packageName, ArrayList<String> components) { 773 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 774 packages.put(packageName, components); 775 } 776 777 public void remove(int userId, String packageName) { 778 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 779 if (packages != null) { 780 packages.remove(packageName); 781 } 782 } 783 784 public void remove(int userId) { 785 mUidMap.remove(userId); 786 } 787 788 public int userIdCount() { 789 return mUidMap.size(); 790 } 791 792 public int userIdAt(int n) { 793 return mUidMap.keyAt(n); 794 } 795 796 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 797 return mUidMap.get(userId); 798 } 799 800 public int size() { 801 // total number of pending broadcast entries across all userIds 802 int num = 0; 803 for (int i = 0; i< mUidMap.size(); i++) { 804 num += mUidMap.valueAt(i).size(); 805 } 806 return num; 807 } 808 809 public void clear() { 810 mUidMap.clear(); 811 } 812 813 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 814 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 815 if (map == null) { 816 map = new ArrayMap<String, ArrayList<String>>(); 817 mUidMap.put(userId, map); 818 } 819 return map; 820 } 821 } 822 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 823 824 // Service Connection to remote media container service to copy 825 // package uri's from external media onto secure containers 826 // or internal storage. 827 private IMediaContainerService mContainerService = null; 828 829 static final int SEND_PENDING_BROADCAST = 1; 830 static final int MCS_BOUND = 3; 831 static final int END_COPY = 4; 832 static final int INIT_COPY = 5; 833 static final int MCS_UNBIND = 6; 834 static final int START_CLEANING_PACKAGE = 7; 835 static final int FIND_INSTALL_LOC = 8; 836 static final int POST_INSTALL = 9; 837 static final int MCS_RECONNECT = 10; 838 static final int MCS_GIVE_UP = 11; 839 static final int UPDATED_MEDIA_STATUS = 12; 840 static final int WRITE_SETTINGS = 13; 841 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 842 static final int PACKAGE_VERIFIED = 15; 843 static final int CHECK_PENDING_VERIFICATION = 16; 844 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 845 static final int INTENT_FILTER_VERIFIED = 18; 846 847 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 848 849 // Delay time in millisecs 850 static final int BROADCAST_DELAY = 10 * 1000; 851 852 static UserManagerService sUserManager; 853 854 // Stores a list of users whose package restrictions file needs to be updated 855 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 856 857 final private DefaultContainerConnection mDefContainerConn = 858 new DefaultContainerConnection(); 859 class DefaultContainerConnection implements ServiceConnection { 860 public void onServiceConnected(ComponentName name, IBinder service) { 861 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 862 IMediaContainerService imcs = 863 IMediaContainerService.Stub.asInterface(service); 864 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 865 } 866 867 public void onServiceDisconnected(ComponentName name) { 868 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 869 } 870 }; 871 872 // Recordkeeping of restore-after-install operations that are currently in flight 873 // between the Package Manager and the Backup Manager 874 class PostInstallData { 875 public InstallArgs args; 876 public PackageInstalledInfo res; 877 878 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 879 args = _a; 880 res = _r; 881 } 882 }; 883 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 884 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 885 886 // backup/restore of preferred activity state 887 private static final String TAG_PREFERRED_BACKUP = "pa"; 888 889 private final String mRequiredVerifierPackage; 890 891 private final PackageUsage mPackageUsage = new PackageUsage(); 892 893 private class PackageUsage { 894 private static final int WRITE_INTERVAL 895 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 896 897 private final Object mFileLock = new Object(); 898 private final AtomicLong mLastWritten = new AtomicLong(0); 899 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 900 901 private boolean mIsHistoricalPackageUsageAvailable = true; 902 903 boolean isHistoricalPackageUsageAvailable() { 904 return mIsHistoricalPackageUsageAvailable; 905 } 906 907 void write(boolean force) { 908 if (force) { 909 writeInternal(); 910 return; 911 } 912 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 913 && !DEBUG_DEXOPT) { 914 return; 915 } 916 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 917 new Thread("PackageUsage_DiskWriter") { 918 @Override 919 public void run() { 920 try { 921 writeInternal(); 922 } finally { 923 mBackgroundWriteRunning.set(false); 924 } 925 } 926 }.start(); 927 } 928 } 929 930 private void writeInternal() { 931 synchronized (mPackages) { 932 synchronized (mFileLock) { 933 AtomicFile file = getFile(); 934 FileOutputStream f = null; 935 try { 936 f = file.startWrite(); 937 BufferedOutputStream out = new BufferedOutputStream(f); 938 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 939 StringBuilder sb = new StringBuilder(); 940 for (PackageParser.Package pkg : mPackages.values()) { 941 if (pkg.mLastPackageUsageTimeInMills == 0) { 942 continue; 943 } 944 sb.setLength(0); 945 sb.append(pkg.packageName); 946 sb.append(' '); 947 sb.append((long)pkg.mLastPackageUsageTimeInMills); 948 sb.append('\n'); 949 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 950 } 951 out.flush(); 952 file.finishWrite(f); 953 } catch (IOException e) { 954 if (f != null) { 955 file.failWrite(f); 956 } 957 Log.e(TAG, "Failed to write package usage times", e); 958 } 959 } 960 } 961 mLastWritten.set(SystemClock.elapsedRealtime()); 962 } 963 964 void readLP() { 965 synchronized (mFileLock) { 966 AtomicFile file = getFile(); 967 BufferedInputStream in = null; 968 try { 969 in = new BufferedInputStream(file.openRead()); 970 StringBuffer sb = new StringBuffer(); 971 while (true) { 972 String packageName = readToken(in, sb, ' '); 973 if (packageName == null) { 974 break; 975 } 976 String timeInMillisString = readToken(in, sb, '\n'); 977 if (timeInMillisString == null) { 978 throw new IOException("Failed to find last usage time for package " 979 + packageName); 980 } 981 PackageParser.Package pkg = mPackages.get(packageName); 982 if (pkg == null) { 983 continue; 984 } 985 long timeInMillis; 986 try { 987 timeInMillis = Long.parseLong(timeInMillisString.toString()); 988 } catch (NumberFormatException e) { 989 throw new IOException("Failed to parse " + timeInMillisString 990 + " as a long.", e); 991 } 992 pkg.mLastPackageUsageTimeInMills = timeInMillis; 993 } 994 } catch (FileNotFoundException expected) { 995 mIsHistoricalPackageUsageAvailable = false; 996 } catch (IOException e) { 997 Log.w(TAG, "Failed to read package usage times", e); 998 } finally { 999 IoUtils.closeQuietly(in); 1000 } 1001 } 1002 mLastWritten.set(SystemClock.elapsedRealtime()); 1003 } 1004 1005 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1006 throws IOException { 1007 sb.setLength(0); 1008 while (true) { 1009 int ch = in.read(); 1010 if (ch == -1) { 1011 if (sb.length() == 0) { 1012 return null; 1013 } 1014 throw new IOException("Unexpected EOF"); 1015 } 1016 if (ch == endOfToken) { 1017 return sb.toString(); 1018 } 1019 sb.append((char)ch); 1020 } 1021 } 1022 1023 private AtomicFile getFile() { 1024 File dataDir = Environment.getDataDirectory(); 1025 File systemDir = new File(dataDir, "system"); 1026 File fname = new File(systemDir, "package-usage.list"); 1027 return new AtomicFile(fname); 1028 } 1029 } 1030 1031 class PackageHandler extends Handler { 1032 private boolean mBound = false; 1033 final ArrayList<HandlerParams> mPendingInstalls = 1034 new ArrayList<HandlerParams>(); 1035 1036 private boolean connectToService() { 1037 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1038 " DefaultContainerService"); 1039 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1040 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1041 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1042 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1043 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1044 mBound = true; 1045 return true; 1046 } 1047 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1048 return false; 1049 } 1050 1051 private void disconnectService() { 1052 mContainerService = null; 1053 mBound = false; 1054 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1055 mContext.unbindService(mDefContainerConn); 1056 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1057 } 1058 1059 PackageHandler(Looper looper) { 1060 super(looper); 1061 } 1062 1063 public void handleMessage(Message msg) { 1064 try { 1065 doHandleMessage(msg); 1066 } finally { 1067 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1068 } 1069 } 1070 1071 void doHandleMessage(Message msg) { 1072 switch (msg.what) { 1073 case INIT_COPY: { 1074 HandlerParams params = (HandlerParams) msg.obj; 1075 int idx = mPendingInstalls.size(); 1076 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1077 // If a bind was already initiated we dont really 1078 // need to do anything. The pending install 1079 // will be processed later on. 1080 if (!mBound) { 1081 // If this is the only one pending we might 1082 // have to bind to the service again. 1083 if (!connectToService()) { 1084 Slog.e(TAG, "Failed to bind to media container service"); 1085 params.serviceError(); 1086 return; 1087 } else { 1088 // Once we bind to the service, the first 1089 // pending request will be processed. 1090 mPendingInstalls.add(idx, params); 1091 } 1092 } else { 1093 mPendingInstalls.add(idx, params); 1094 // Already bound to the service. Just make 1095 // sure we trigger off processing the first request. 1096 if (idx == 0) { 1097 mHandler.sendEmptyMessage(MCS_BOUND); 1098 } 1099 } 1100 break; 1101 } 1102 case MCS_BOUND: { 1103 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1104 if (msg.obj != null) { 1105 mContainerService = (IMediaContainerService) msg.obj; 1106 } 1107 if (mContainerService == null) { 1108 // Something seriously wrong. Bail out 1109 Slog.e(TAG, "Cannot bind to media container service"); 1110 for (HandlerParams params : mPendingInstalls) { 1111 // Indicate service bind error 1112 params.serviceError(); 1113 } 1114 mPendingInstalls.clear(); 1115 } else if (mPendingInstalls.size() > 0) { 1116 HandlerParams params = mPendingInstalls.get(0); 1117 if (params != null) { 1118 if (params.startCopy()) { 1119 // We are done... look for more work or to 1120 // go idle. 1121 if (DEBUG_SD_INSTALL) Log.i(TAG, 1122 "Checking for more work or unbind..."); 1123 // Delete pending install 1124 if (mPendingInstalls.size() > 0) { 1125 mPendingInstalls.remove(0); 1126 } 1127 if (mPendingInstalls.size() == 0) { 1128 if (mBound) { 1129 if (DEBUG_SD_INSTALL) Log.i(TAG, 1130 "Posting delayed MCS_UNBIND"); 1131 removeMessages(MCS_UNBIND); 1132 Message ubmsg = obtainMessage(MCS_UNBIND); 1133 // Unbind after a little delay, to avoid 1134 // continual thrashing. 1135 sendMessageDelayed(ubmsg, 10000); 1136 } 1137 } else { 1138 // There are more pending requests in queue. 1139 // Just post MCS_BOUND message to trigger processing 1140 // of next pending install. 1141 if (DEBUG_SD_INSTALL) Log.i(TAG, 1142 "Posting MCS_BOUND for next work"); 1143 mHandler.sendEmptyMessage(MCS_BOUND); 1144 } 1145 } 1146 } 1147 } else { 1148 // Should never happen ideally. 1149 Slog.w(TAG, "Empty queue"); 1150 } 1151 break; 1152 } 1153 case MCS_RECONNECT: { 1154 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1155 if (mPendingInstalls.size() > 0) { 1156 if (mBound) { 1157 disconnectService(); 1158 } 1159 if (!connectToService()) { 1160 Slog.e(TAG, "Failed to bind to media container service"); 1161 for (HandlerParams params : mPendingInstalls) { 1162 // Indicate service bind error 1163 params.serviceError(); 1164 } 1165 mPendingInstalls.clear(); 1166 } 1167 } 1168 break; 1169 } 1170 case MCS_UNBIND: { 1171 // If there is no actual work left, then time to unbind. 1172 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1173 1174 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1175 if (mBound) { 1176 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1177 1178 disconnectService(); 1179 } 1180 } else if (mPendingInstalls.size() > 0) { 1181 // There are more pending requests in queue. 1182 // Just post MCS_BOUND message to trigger processing 1183 // of next pending install. 1184 mHandler.sendEmptyMessage(MCS_BOUND); 1185 } 1186 1187 break; 1188 } 1189 case MCS_GIVE_UP: { 1190 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1191 mPendingInstalls.remove(0); 1192 break; 1193 } 1194 case SEND_PENDING_BROADCAST: { 1195 String packages[]; 1196 ArrayList<String> components[]; 1197 int size = 0; 1198 int uids[]; 1199 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1200 synchronized (mPackages) { 1201 if (mPendingBroadcasts == null) { 1202 return; 1203 } 1204 size = mPendingBroadcasts.size(); 1205 if (size <= 0) { 1206 // Nothing to be done. Just return 1207 return; 1208 } 1209 packages = new String[size]; 1210 components = new ArrayList[size]; 1211 uids = new int[size]; 1212 int i = 0; // filling out the above arrays 1213 1214 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1215 int packageUserId = mPendingBroadcasts.userIdAt(n); 1216 Iterator<Map.Entry<String, ArrayList<String>>> it 1217 = mPendingBroadcasts.packagesForUserId(packageUserId) 1218 .entrySet().iterator(); 1219 while (it.hasNext() && i < size) { 1220 Map.Entry<String, ArrayList<String>> ent = it.next(); 1221 packages[i] = ent.getKey(); 1222 components[i] = ent.getValue(); 1223 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1224 uids[i] = (ps != null) 1225 ? UserHandle.getUid(packageUserId, ps.appId) 1226 : -1; 1227 i++; 1228 } 1229 } 1230 size = i; 1231 mPendingBroadcasts.clear(); 1232 } 1233 // Send broadcasts 1234 for (int i = 0; i < size; i++) { 1235 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1236 } 1237 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1238 break; 1239 } 1240 case START_CLEANING_PACKAGE: { 1241 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1242 final String packageName = (String)msg.obj; 1243 final int userId = msg.arg1; 1244 final boolean andCode = msg.arg2 != 0; 1245 synchronized (mPackages) { 1246 if (userId == UserHandle.USER_ALL) { 1247 int[] users = sUserManager.getUserIds(); 1248 for (int user : users) { 1249 mSettings.addPackageToCleanLPw( 1250 new PackageCleanItem(user, packageName, andCode)); 1251 } 1252 } else { 1253 mSettings.addPackageToCleanLPw( 1254 new PackageCleanItem(userId, packageName, andCode)); 1255 } 1256 } 1257 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1258 startCleaningPackages(); 1259 } break; 1260 case POST_INSTALL: { 1261 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1262 PostInstallData data = mRunningInstalls.get(msg.arg1); 1263 mRunningInstalls.delete(msg.arg1); 1264 boolean deleteOld = false; 1265 1266 if (data != null) { 1267 InstallArgs args = data.args; 1268 PackageInstalledInfo res = data.res; 1269 1270 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1271 res.removedInfo.sendBroadcast(false, true, false); 1272 Bundle extras = new Bundle(1); 1273 extras.putInt(Intent.EXTRA_UID, res.uid); 1274 1275 // Now that we successfully installed the package, grant runtime 1276 // permissions if requested before broadcasting the install. 1277 if ((args.installFlags 1278 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1279 grantRequestedRuntimePermissions(res.pkg, 1280 args.user.getIdentifier()); 1281 } 1282 1283 // Determine the set of users who are adding this 1284 // package for the first time vs. those who are seeing 1285 // an update. 1286 int[] firstUsers; 1287 int[] updateUsers = new int[0]; 1288 if (res.origUsers == null || res.origUsers.length == 0) { 1289 firstUsers = res.newUsers; 1290 } else { 1291 firstUsers = new int[0]; 1292 for (int i=0; i<res.newUsers.length; i++) { 1293 int user = res.newUsers[i]; 1294 boolean isNew = true; 1295 for (int j=0; j<res.origUsers.length; j++) { 1296 if (res.origUsers[j] == user) { 1297 isNew = false; 1298 break; 1299 } 1300 } 1301 if (isNew) { 1302 int[] newFirst = new int[firstUsers.length+1]; 1303 System.arraycopy(firstUsers, 0, newFirst, 0, 1304 firstUsers.length); 1305 newFirst[firstUsers.length] = user; 1306 firstUsers = newFirst; 1307 } else { 1308 int[] newUpdate = new int[updateUsers.length+1]; 1309 System.arraycopy(updateUsers, 0, newUpdate, 0, 1310 updateUsers.length); 1311 newUpdate[updateUsers.length] = user; 1312 updateUsers = newUpdate; 1313 } 1314 } 1315 } 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, firstUsers); 1319 final boolean update = res.removedInfo.removedPackage != null; 1320 if (update) { 1321 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1322 } 1323 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1324 res.pkg.applicationInfo.packageName, 1325 extras, null, null, updateUsers); 1326 if (update) { 1327 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1328 res.pkg.applicationInfo.packageName, 1329 extras, null, null, updateUsers); 1330 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1331 null, null, 1332 res.pkg.applicationInfo.packageName, null, updateUsers); 1333 1334 // treat asec-hosted packages like removable media on upgrade 1335 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1336 if (DEBUG_INSTALL) { 1337 Slog.i(TAG, "upgrading pkg " + res.pkg 1338 + " is ASEC-hosted -> AVAILABLE"); 1339 } 1340 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1341 ArrayList<String> pkgList = new ArrayList<String>(1); 1342 pkgList.add(res.pkg.applicationInfo.packageName); 1343 sendResourcesChangedBroadcast(true, true, 1344 pkgList,uidArray, null); 1345 } 1346 } 1347 if (res.removedInfo.args != null) { 1348 // Remove the replaced package's older resources safely now 1349 deleteOld = true; 1350 } 1351 1352 // Log current value of "unknown sources" setting 1353 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1354 getUnknownSourcesSettings()); 1355 } 1356 // Force a gc to clear up things 1357 Runtime.getRuntime().gc(); 1358 // We delete after a gc for applications on sdcard. 1359 if (deleteOld) { 1360 synchronized (mInstallLock) { 1361 res.removedInfo.args.doPostDeleteLI(true); 1362 } 1363 } 1364 if (args.observer != null) { 1365 try { 1366 Bundle extras = extrasForInstallResult(res); 1367 args.observer.onPackageInstalled(res.name, res.returnCode, 1368 res.returnMsg, extras); 1369 } catch (RemoteException e) { 1370 Slog.i(TAG, "Observer no longer exists."); 1371 } 1372 } 1373 } else { 1374 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1375 } 1376 } break; 1377 case UPDATED_MEDIA_STATUS: { 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1379 boolean reportStatus = msg.arg1 == 1; 1380 boolean doGc = msg.arg2 == 1; 1381 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1382 if (doGc) { 1383 // Force a gc to clear up stale containers. 1384 Runtime.getRuntime().gc(); 1385 } 1386 if (msg.obj != null) { 1387 @SuppressWarnings("unchecked") 1388 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1389 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1390 // Unload containers 1391 unloadAllContainers(args); 1392 } 1393 if (reportStatus) { 1394 try { 1395 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1396 PackageHelper.getMountService().finishMediaUpdate(); 1397 } catch (RemoteException e) { 1398 Log.e(TAG, "MountService not running?"); 1399 } 1400 } 1401 } break; 1402 case WRITE_SETTINGS: { 1403 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1404 synchronized (mPackages) { 1405 removeMessages(WRITE_SETTINGS); 1406 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1407 mSettings.writeLPr(); 1408 mDirtyUsers.clear(); 1409 } 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1411 } break; 1412 case WRITE_PACKAGE_RESTRICTIONS: { 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 synchronized (mPackages) { 1415 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1416 for (int userId : mDirtyUsers) { 1417 mSettings.writePackageRestrictionsLPr(userId); 1418 } 1419 mDirtyUsers.clear(); 1420 } 1421 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1422 } break; 1423 case CHECK_PENDING_VERIFICATION: { 1424 final int verificationId = msg.arg1; 1425 final PackageVerificationState state = mPendingVerification.get(verificationId); 1426 1427 if ((state != null) && !state.timeoutExtended()) { 1428 final InstallArgs args = state.getInstallArgs(); 1429 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1430 1431 Slog.i(TAG, "Verification timed out for " + originUri); 1432 mPendingVerification.remove(verificationId); 1433 1434 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1435 1436 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1437 Slog.i(TAG, "Continuing with installation of " + originUri); 1438 state.setVerifierResponse(Binder.getCallingUid(), 1439 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1440 broadcastPackageVerified(verificationId, originUri, 1441 PackageManager.VERIFICATION_ALLOW, 1442 state.getInstallArgs().getUser()); 1443 try { 1444 ret = args.copyApk(mContainerService, true); 1445 } catch (RemoteException e) { 1446 Slog.e(TAG, "Could not contact the ContainerService"); 1447 } 1448 } else { 1449 broadcastPackageVerified(verificationId, originUri, 1450 PackageManager.VERIFICATION_REJECT, 1451 state.getInstallArgs().getUser()); 1452 } 1453 1454 processPendingInstall(args, ret); 1455 mHandler.sendEmptyMessage(MCS_UNBIND); 1456 } 1457 break; 1458 } 1459 case PACKAGE_VERIFIED: { 1460 final int verificationId = msg.arg1; 1461 1462 final PackageVerificationState state = mPendingVerification.get(verificationId); 1463 if (state == null) { 1464 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1465 break; 1466 } 1467 1468 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1469 1470 state.setVerifierResponse(response.callerUid, response.code); 1471 1472 if (state.isVerificationComplete()) { 1473 mPendingVerification.remove(verificationId); 1474 1475 final InstallArgs args = state.getInstallArgs(); 1476 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1477 1478 int ret; 1479 if (state.isInstallAllowed()) { 1480 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1481 broadcastPackageVerified(verificationId, originUri, 1482 response.code, state.getInstallArgs().getUser()); 1483 try { 1484 ret = args.copyApk(mContainerService, true); 1485 } catch (RemoteException e) { 1486 Slog.e(TAG, "Could not contact the ContainerService"); 1487 } 1488 } else { 1489 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1490 } 1491 1492 processPendingInstall(args, ret); 1493 1494 mHandler.sendEmptyMessage(MCS_UNBIND); 1495 } 1496 1497 break; 1498 } 1499 case START_INTENT_FILTER_VERIFICATIONS: { 1500 int userId = msg.arg1; 1501 int verifierUid = msg.arg2; 1502 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1503 1504 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1505 break; 1506 } 1507 case INTENT_FILTER_VERIFIED: { 1508 final int verificationId = msg.arg1; 1509 1510 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1511 verificationId); 1512 if (state == null) { 1513 Slog.w(TAG, "Invalid IntentFilter verification token " 1514 + verificationId + " received"); 1515 break; 1516 } 1517 1518 final int userId = state.getUserId(); 1519 1520 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1521 "Processing IntentFilter verification with token:" 1522 + verificationId + " and userId:" + userId); 1523 1524 final IntentFilterVerificationResponse response = 1525 (IntentFilterVerificationResponse) msg.obj; 1526 1527 state.setVerifierResponse(response.callerUid, response.code); 1528 1529 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1530 "IntentFilter verification with token:" + verificationId 1531 + " and userId:" + userId 1532 + " is settings verifier response with response code:" 1533 + response.code); 1534 1535 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1536 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1537 + response.getFailedDomainsString()); 1538 } 1539 1540 if (state.isVerificationComplete()) { 1541 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1542 } else { 1543 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1544 "IntentFilter verification with token:" + verificationId 1545 + " was not said to be complete"); 1546 } 1547 1548 break; 1549 } 1550 } 1551 } 1552 } 1553 1554 private StorageEventListener mStorageListener = new StorageEventListener() { 1555 @Override 1556 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1557 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1558 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1559 // TODO: ensure that private directories exist for all active users 1560 // TODO: remove user data whose serial number doesn't match 1561 loadPrivatePackages(vol); 1562 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1563 unloadPrivatePackages(vol); 1564 } 1565 } 1566 1567 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1568 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1569 updateExternalMediaStatus(true, false); 1570 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1571 updateExternalMediaStatus(false, false); 1572 } 1573 } 1574 } 1575 1576 @Override 1577 public void onVolumeForgotten(String fsUuid) { 1578 // TODO: remove all packages hosted on this uuid 1579 } 1580 }; 1581 1582 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1583 if (userId >= UserHandle.USER_OWNER) { 1584 grantRequestedRuntimePermissionsForUser(pkg, userId); 1585 } else if (userId == UserHandle.USER_ALL) { 1586 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1587 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1588 } 1589 } 1590 } 1591 1592 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1593 SettingBase sb = (SettingBase) pkg.mExtras; 1594 if (sb == null) { 1595 return; 1596 } 1597 1598 PermissionsState permissionsState = sb.getPermissionsState(); 1599 1600 for (String permission : pkg.requestedPermissions) { 1601 BasePermission bp = mSettings.mPermissions.get(permission); 1602 if (bp != null && bp.isRuntime()) { 1603 permissionsState.grantRuntimePermission(bp, userId); 1604 } 1605 } 1606 } 1607 1608 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1609 Bundle extras = null; 1610 switch (res.returnCode) { 1611 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1612 extras = new Bundle(); 1613 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1614 res.origPermission); 1615 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1616 res.origPackage); 1617 break; 1618 } 1619 case PackageManager.INSTALL_SUCCEEDED: { 1620 extras = new Bundle(); 1621 extras.putBoolean(Intent.EXTRA_REPLACING, 1622 res.removedInfo != null && res.removedInfo.removedPackage != null); 1623 break; 1624 } 1625 } 1626 return extras; 1627 } 1628 1629 void scheduleWriteSettingsLocked() { 1630 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1631 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1632 } 1633 } 1634 1635 void scheduleWritePackageRestrictionsLocked(int userId) { 1636 if (!sUserManager.exists(userId)) return; 1637 mDirtyUsers.add(userId); 1638 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1639 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1640 } 1641 } 1642 1643 public static PackageManagerService main(Context context, Installer installer, 1644 boolean factoryTest, boolean onlyCore) { 1645 PackageManagerService m = new PackageManagerService(context, installer, 1646 factoryTest, onlyCore); 1647 ServiceManager.addService("package", m); 1648 return m; 1649 } 1650 1651 static String[] splitString(String str, char sep) { 1652 int count = 1; 1653 int i = 0; 1654 while ((i=str.indexOf(sep, i)) >= 0) { 1655 count++; 1656 i++; 1657 } 1658 1659 String[] res = new String[count]; 1660 i=0; 1661 count = 0; 1662 int lastI=0; 1663 while ((i=str.indexOf(sep, i)) >= 0) { 1664 res[count] = str.substring(lastI, i); 1665 count++; 1666 i++; 1667 lastI = i; 1668 } 1669 res[count] = str.substring(lastI, str.length()); 1670 return res; 1671 } 1672 1673 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1674 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1675 Context.DISPLAY_SERVICE); 1676 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1677 } 1678 1679 public PackageManagerService(Context context, Installer installer, 1680 boolean factoryTest, boolean onlyCore) { 1681 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1682 SystemClock.uptimeMillis()); 1683 1684 if (mSdkVersion <= 0) { 1685 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1686 } 1687 1688 mContext = context; 1689 mFactoryTest = factoryTest; 1690 mOnlyCore = onlyCore; 1691 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1692 mMetrics = new DisplayMetrics(); 1693 mSettings = new Settings(mPackages); 1694 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1695 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1696 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1697 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1698 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1699 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1700 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1701 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1702 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1703 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1704 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1705 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1706 1707 // TODO: add a property to control this? 1708 long dexOptLRUThresholdInMinutes; 1709 if (mLazyDexOpt) { 1710 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1711 } else { 1712 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1713 } 1714 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1715 1716 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1717 if (separateProcesses != null && separateProcesses.length() > 0) { 1718 if ("*".equals(separateProcesses)) { 1719 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1720 mSeparateProcesses = null; 1721 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1722 } else { 1723 mDefParseFlags = 0; 1724 mSeparateProcesses = separateProcesses.split(","); 1725 Slog.w(TAG, "Running with debug.separate_processes: " 1726 + separateProcesses); 1727 } 1728 } else { 1729 mDefParseFlags = 0; 1730 mSeparateProcesses = null; 1731 } 1732 1733 mInstaller = installer; 1734 mPackageDexOptimizer = new PackageDexOptimizer(this); 1735 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1736 1737 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1738 FgThread.get().getLooper()); 1739 1740 getDefaultDisplayMetrics(context, mMetrics); 1741 1742 SystemConfig systemConfig = SystemConfig.getInstance(); 1743 mGlobalGids = systemConfig.getGlobalGids(); 1744 mSystemPermissions = systemConfig.getSystemPermissions(); 1745 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1746 1747 synchronized (mInstallLock) { 1748 // writer 1749 synchronized (mPackages) { 1750 mHandlerThread = new ServiceThread(TAG, 1751 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1752 mHandlerThread.start(); 1753 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1754 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1755 1756 File dataDir = Environment.getDataDirectory(); 1757 mAppDataDir = new File(dataDir, "data"); 1758 mAppInstallDir = new File(dataDir, "app"); 1759 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1760 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1761 mUserAppDataDir = new File(dataDir, "user"); 1762 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1763 1764 sUserManager = new UserManagerService(context, this, 1765 mInstallLock, mPackages); 1766 1767 // Propagate permission configuration in to package manager. 1768 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1769 = systemConfig.getPermissions(); 1770 for (int i=0; i<permConfig.size(); i++) { 1771 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1772 BasePermission bp = mSettings.mPermissions.get(perm.name); 1773 if (bp == null) { 1774 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1775 mSettings.mPermissions.put(perm.name, bp); 1776 } 1777 if (perm.gids != null) { 1778 bp.setGids(perm.gids, perm.perUser); 1779 } 1780 } 1781 1782 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1783 for (int i=0; i<libConfig.size(); i++) { 1784 mSharedLibraries.put(libConfig.keyAt(i), 1785 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1786 } 1787 1788 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1789 1790 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1791 mSdkVersion, mOnlyCore); 1792 1793 String customResolverActivity = Resources.getSystem().getString( 1794 R.string.config_customResolverActivity); 1795 if (TextUtils.isEmpty(customResolverActivity)) { 1796 customResolverActivity = null; 1797 } else { 1798 mCustomResolverComponentName = ComponentName.unflattenFromString( 1799 customResolverActivity); 1800 } 1801 1802 long startTime = SystemClock.uptimeMillis(); 1803 1804 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1805 startTime); 1806 1807 // Set flag to monitor and not change apk file paths when 1808 // scanning install directories. 1809 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 1810 1811 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1812 1813 /** 1814 * Add everything in the in the boot class path to the 1815 * list of process files because dexopt will have been run 1816 * if necessary during zygote startup. 1817 */ 1818 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1819 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1820 1821 if (bootClassPath != null) { 1822 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1823 for (String element : bootClassPathElements) { 1824 alreadyDexOpted.add(element); 1825 } 1826 } else { 1827 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1828 } 1829 1830 if (systemServerClassPath != null) { 1831 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1832 for (String element : systemServerClassPathElements) { 1833 alreadyDexOpted.add(element); 1834 } 1835 } else { 1836 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1837 } 1838 1839 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1840 final String[] dexCodeInstructionSets = 1841 getDexCodeInstructionSets( 1842 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1843 1844 /** 1845 * Ensure all external libraries have had dexopt run on them. 1846 */ 1847 if (mSharedLibraries.size() > 0) { 1848 // NOTE: For now, we're compiling these system "shared libraries" 1849 // (and framework jars) into all available architectures. It's possible 1850 // to compile them only when we come across an app that uses them (there's 1851 // already logic for that in scanPackageLI) but that adds some complexity. 1852 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1853 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1854 final String lib = libEntry.path; 1855 if (lib == null) { 1856 continue; 1857 } 1858 1859 try { 1860 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1861 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1862 alreadyDexOpted.add(lib); 1863 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1864 } 1865 } catch (FileNotFoundException e) { 1866 Slog.w(TAG, "Library not found: " + lib); 1867 } catch (IOException e) { 1868 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1869 + e.getMessage()); 1870 } 1871 } 1872 } 1873 } 1874 1875 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1876 1877 // Gross hack for now: we know this file doesn't contain any 1878 // code, so don't dexopt it to avoid the resulting log spew. 1879 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1880 1881 // Gross hack for now: we know this file is only part of 1882 // the boot class path for art, so don't dexopt it to 1883 // avoid the resulting log spew. 1884 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1885 1886 /** 1887 * There are a number of commands implemented in Java, which 1888 * we currently need to do the dexopt on so that they can be 1889 * run from a non-root shell. 1890 */ 1891 String[] frameworkFiles = frameworkDir.list(); 1892 if (frameworkFiles != null) { 1893 // TODO: We could compile these only for the most preferred ABI. We should 1894 // first double check that the dex files for these commands are not referenced 1895 // by other system apps. 1896 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1897 for (int i=0; i<frameworkFiles.length; i++) { 1898 File libPath = new File(frameworkDir, frameworkFiles[i]); 1899 String path = libPath.getPath(); 1900 // Skip the file if we already did it. 1901 if (alreadyDexOpted.contains(path)) { 1902 continue; 1903 } 1904 // Skip the file if it is not a type we want to dexopt. 1905 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1906 continue; 1907 } 1908 try { 1909 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1910 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1911 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1912 } 1913 } catch (FileNotFoundException e) { 1914 Slog.w(TAG, "Jar not found: " + path); 1915 } catch (IOException e) { 1916 Slog.w(TAG, "Exception reading jar: " + path, e); 1917 } 1918 } 1919 } 1920 } 1921 1922 // Collect vendor overlay packages. 1923 // (Do this before scanning any apps.) 1924 // For security and version matching reason, only consider 1925 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1926 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1927 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1928 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1929 1930 // Find base frameworks (resource packages without code). 1931 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR 1933 | PackageParser.PARSE_IS_PRIVILEGED, 1934 scanFlags | SCAN_NO_DEX, 0); 1935 1936 // Collected privileged system packages. 1937 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1938 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1939 | PackageParser.PARSE_IS_SYSTEM_DIR 1940 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1941 1942 // Collect ordinary system packages. 1943 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1944 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1945 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1946 1947 // Collect all vendor packages. 1948 File vendorAppDir = new File("/vendor/app"); 1949 try { 1950 vendorAppDir = vendorAppDir.getCanonicalFile(); 1951 } catch (IOException e) { 1952 // failed to look up canonical path, continue with original one 1953 } 1954 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1955 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1956 1957 // Collect all OEM packages. 1958 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1959 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1960 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1961 1962 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1963 mInstaller.moveFiles(); 1964 1965 // Prune any system packages that no longer exist. 1966 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1967 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1968 if (!mOnlyCore) { 1969 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1970 while (psit.hasNext()) { 1971 PackageSetting ps = psit.next(); 1972 1973 /* 1974 * If this is not a system app, it can't be a 1975 * disable system app. 1976 */ 1977 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1978 continue; 1979 } 1980 1981 /* 1982 * If the package is scanned, it's not erased. 1983 */ 1984 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1985 if (scannedPkg != null) { 1986 /* 1987 * If the system app is both scanned and in the 1988 * disabled packages list, then it must have been 1989 * added via OTA. Remove it from the currently 1990 * scanned package so the previously user-installed 1991 * application can be scanned. 1992 */ 1993 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1994 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1995 + ps.name + "; removing system app. Last known codePath=" 1996 + ps.codePathString + ", installStatus=" + ps.installStatus 1997 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1998 + scannedPkg.mVersionCode); 1999 removePackageLI(ps, true); 2000 expectingBetter.put(ps.name, ps.codePath); 2001 } 2002 2003 continue; 2004 } 2005 2006 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2007 psit.remove(); 2008 logCriticalInfo(Log.WARN, "System package " + ps.name 2009 + " no longer exists; wiping its data"); 2010 removeDataDirsLI(null, ps.name); 2011 } else { 2012 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2013 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2014 possiblyDeletedUpdatedSystemApps.add(ps.name); 2015 } 2016 } 2017 } 2018 } 2019 2020 //look for any incomplete package installations 2021 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2022 //clean up list 2023 for(int i = 0; i < deletePkgsList.size(); i++) { 2024 //clean up here 2025 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2026 } 2027 //delete tmp files 2028 deleteTempPackageFiles(); 2029 2030 // Remove any shared userIDs that have no associated packages 2031 mSettings.pruneSharedUsersLPw(); 2032 2033 if (!mOnlyCore) { 2034 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2035 SystemClock.uptimeMillis()); 2036 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2037 2038 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2039 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2040 2041 /** 2042 * Remove disable package settings for any updated system 2043 * apps that were removed via an OTA. If they're not a 2044 * previously-updated app, remove them completely. 2045 * Otherwise, just revoke their system-level permissions. 2046 */ 2047 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2048 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2049 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2050 2051 String msg; 2052 if (deletedPkg == null) { 2053 msg = "Updated system package " + deletedAppName 2054 + " no longer exists; wiping its data"; 2055 removeDataDirsLI(null, deletedAppName); 2056 } else { 2057 msg = "Updated system app + " + deletedAppName 2058 + " no longer present; removing system privileges for " 2059 + deletedAppName; 2060 2061 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2062 2063 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2064 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2065 } 2066 logCriticalInfo(Log.WARN, msg); 2067 } 2068 2069 /** 2070 * Make sure all system apps that we expected to appear on 2071 * the userdata partition actually showed up. If they never 2072 * appeared, crawl back and revive the system version. 2073 */ 2074 for (int i = 0; i < expectingBetter.size(); i++) { 2075 final String packageName = expectingBetter.keyAt(i); 2076 if (!mPackages.containsKey(packageName)) { 2077 final File scanFile = expectingBetter.valueAt(i); 2078 2079 logCriticalInfo(Log.WARN, "Expected better " + packageName 2080 + " but never showed up; reverting to system"); 2081 2082 final int reparseFlags; 2083 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2084 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2085 | PackageParser.PARSE_IS_SYSTEM_DIR 2086 | PackageParser.PARSE_IS_PRIVILEGED; 2087 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2088 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2089 | PackageParser.PARSE_IS_SYSTEM_DIR; 2090 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2091 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2092 | PackageParser.PARSE_IS_SYSTEM_DIR; 2093 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2094 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2095 | PackageParser.PARSE_IS_SYSTEM_DIR; 2096 } else { 2097 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2098 continue; 2099 } 2100 2101 mSettings.enableSystemPackageLPw(packageName); 2102 2103 try { 2104 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2105 } catch (PackageManagerException e) { 2106 Slog.e(TAG, "Failed to parse original system package: " 2107 + e.getMessage()); 2108 } 2109 } 2110 } 2111 } 2112 2113 // Now that we know all of the shared libraries, update all clients to have 2114 // the correct library paths. 2115 updateAllSharedLibrariesLPw(); 2116 2117 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2118 // NOTE: We ignore potential failures here during a system scan (like 2119 // the rest of the commands above) because there's precious little we 2120 // can do about it. A settings error is reported, though. 2121 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2122 false /* force dexopt */, false /* defer dexopt */); 2123 } 2124 2125 // Now that we know all the packages we are keeping, 2126 // read and update their last usage times. 2127 mPackageUsage.readLP(); 2128 2129 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2130 SystemClock.uptimeMillis()); 2131 Slog.i(TAG, "Time to scan packages: " 2132 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2133 + " seconds"); 2134 2135 // If the platform SDK has changed since the last time we booted, 2136 // we need to re-grant app permission to catch any new ones that 2137 // appear. This is really a hack, and means that apps can in some 2138 // cases get permissions that the user didn't initially explicitly 2139 // allow... it would be nice to have some better way to handle 2140 // this situation. 2141 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2142 != mSdkVersion; 2143 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2144 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2145 + "; regranting permissions for internal storage"); 2146 mSettings.mInternalSdkPlatform = mSdkVersion; 2147 2148 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2149 | (regrantPermissions 2150 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2151 : 0)); 2152 2153 // If this is the first boot, and it is a normal boot, then 2154 // we need to initialize the default preferred apps. 2155 if (!mRestoredSettings && !onlyCore) { 2156 mSettings.readDefaultPreferredAppsLPw(this, 0); 2157 } 2158 2159 // If this is first boot after an OTA, and a normal boot, then 2160 // we need to clear code cache directories. 2161 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2162 if (mIsUpgrade && !onlyCore) { 2163 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2164 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2165 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2166 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2167 } 2168 mSettings.mFingerprint = Build.FINGERPRINT; 2169 } 2170 2171 primeDomainVerificationsLPw(); 2172 checkDefaultBrowser(); 2173 2174 // All the changes are done during package scanning. 2175 mSettings.updateInternalDatabaseVersion(); 2176 2177 // can downgrade to reader 2178 mSettings.writeLPr(); 2179 2180 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2181 SystemClock.uptimeMillis()); 2182 2183 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2184 2185 mInstallerService = new PackageInstallerService(context, this); 2186 2187 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2188 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2189 mIntentFilterVerifierComponent); 2190 2191 } // synchronized (mPackages) 2192 } // synchronized (mInstallLock) 2193 2194 // Now after opening every single application zip, make sure they 2195 // are all flushed. Not really needed, but keeps things nice and 2196 // tidy. 2197 Runtime.getRuntime().gc(); 2198 } 2199 2200 @Override 2201 public boolean isFirstBoot() { 2202 return !mRestoredSettings; 2203 } 2204 2205 @Override 2206 public boolean isOnlyCoreApps() { 2207 return mOnlyCore; 2208 } 2209 2210 @Override 2211 public boolean isUpgrade() { 2212 return mIsUpgrade; 2213 } 2214 2215 private String getRequiredVerifierLPr() { 2216 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2217 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2218 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2219 2220 String requiredVerifier = null; 2221 2222 final int N = receivers.size(); 2223 for (int i = 0; i < N; i++) { 2224 final ResolveInfo info = receivers.get(i); 2225 2226 if (info.activityInfo == null) { 2227 continue; 2228 } 2229 2230 final String packageName = info.activityInfo.packageName; 2231 2232 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2233 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2234 continue; 2235 } 2236 2237 if (requiredVerifier != null) { 2238 throw new RuntimeException("There can be only one required verifier"); 2239 } 2240 2241 requiredVerifier = packageName; 2242 } 2243 2244 return requiredVerifier; 2245 } 2246 2247 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2248 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2249 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2250 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2251 2252 ComponentName verifierComponentName = null; 2253 2254 int priority = -1000; 2255 final int N = receivers.size(); 2256 for (int i = 0; i < N; i++) { 2257 final ResolveInfo info = receivers.get(i); 2258 2259 if (info.activityInfo == null) { 2260 continue; 2261 } 2262 2263 final String packageName = info.activityInfo.packageName; 2264 2265 final PackageSetting ps = mSettings.mPackages.get(packageName); 2266 if (ps == null) { 2267 continue; 2268 } 2269 2270 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2271 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2272 continue; 2273 } 2274 2275 // Select the IntentFilterVerifier with the highest priority 2276 if (priority < info.priority) { 2277 priority = info.priority; 2278 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2279 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2280 + verifierComponentName + " with priority: " + info.priority); 2281 } 2282 } 2283 2284 return verifierComponentName; 2285 } 2286 2287 private void primeDomainVerificationsLPw() { 2288 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2289 boolean updated = false; 2290 ArraySet<String> allHostsSet = new ArraySet<>(); 2291 for (PackageParser.Package pkg : mPackages.values()) { 2292 final String packageName = pkg.packageName; 2293 if (!hasDomainURLs(pkg)) { 2294 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2295 "package with no domain URLs: " + packageName); 2296 continue; 2297 } 2298 if (!pkg.isSystemApp()) { 2299 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2300 "No priming domain verifications for a non system package : " + 2301 packageName); 2302 continue; 2303 } 2304 for (PackageParser.Activity a : pkg.activities) { 2305 for (ActivityIntentInfo filter : a.intents) { 2306 if (hasValidDomains(filter)) { 2307 allHostsSet.addAll(filter.getHostsList()); 2308 } 2309 } 2310 } 2311 if (allHostsSet.size() == 0) { 2312 allHostsSet.add("*"); 2313 } 2314 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2315 IntentFilterVerificationInfo ivi = 2316 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2317 if (ivi != null) { 2318 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2319 "Priming domain verifications for package: " + packageName + 2320 " with hosts:" + ivi.getDomainsString()); 2321 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2322 updated = true; 2323 } 2324 else { 2325 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2326 "No priming domain verifications for package: " + packageName); 2327 } 2328 allHostsSet.clear(); 2329 } 2330 if (updated) { 2331 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2332 "Will need to write primed domain verifications"); 2333 } 2334 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2335 } 2336 2337 private void checkDefaultBrowser() { 2338 final int myUserId = UserHandle.myUserId(); 2339 final String packageName = getDefaultBrowserPackageName(myUserId); 2340 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2341 if (info == null) { 2342 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2343 packageName); 2344 setDefaultBrowserPackageName(null, myUserId); 2345 } 2346 } 2347 2348 @Override 2349 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2350 throws RemoteException { 2351 try { 2352 return super.onTransact(code, data, reply, flags); 2353 } catch (RuntimeException e) { 2354 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2355 Slog.wtf(TAG, "Package Manager Crash", e); 2356 } 2357 throw e; 2358 } 2359 } 2360 2361 void cleanupInstallFailedPackage(PackageSetting ps) { 2362 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2363 2364 removeDataDirsLI(ps.volumeUuid, ps.name); 2365 if (ps.codePath != null) { 2366 if (ps.codePath.isDirectory()) { 2367 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2368 } else { 2369 ps.codePath.delete(); 2370 } 2371 } 2372 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2373 if (ps.resourcePath.isDirectory()) { 2374 FileUtils.deleteContents(ps.resourcePath); 2375 } 2376 ps.resourcePath.delete(); 2377 } 2378 mSettings.removePackageLPw(ps.name); 2379 } 2380 2381 static int[] appendInts(int[] cur, int[] add) { 2382 if (add == null) return cur; 2383 if (cur == null) return add; 2384 final int N = add.length; 2385 for (int i=0; i<N; i++) { 2386 cur = appendInt(cur, add[i]); 2387 } 2388 return cur; 2389 } 2390 2391 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2392 if (!sUserManager.exists(userId)) return null; 2393 final PackageSetting ps = (PackageSetting) p.mExtras; 2394 if (ps == null) { 2395 return null; 2396 } 2397 2398 final PermissionsState permissionsState = ps.getPermissionsState(); 2399 2400 final int[] gids = permissionsState.computeGids(userId); 2401 final Set<String> permissions = permissionsState.getPermissions(userId); 2402 final PackageUserState state = ps.readUserState(userId); 2403 2404 return PackageParser.generatePackageInfo(p, gids, flags, 2405 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2406 } 2407 2408 @Override 2409 public boolean isPackageFrozen(String packageName) { 2410 synchronized (mPackages) { 2411 final PackageSetting ps = mSettings.mPackages.get(packageName); 2412 if (ps != null) { 2413 return ps.frozen; 2414 } 2415 } 2416 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2417 return true; 2418 } 2419 2420 @Override 2421 public boolean isPackageAvailable(String packageName, int userId) { 2422 if (!sUserManager.exists(userId)) return false; 2423 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2424 synchronized (mPackages) { 2425 PackageParser.Package p = mPackages.get(packageName); 2426 if (p != null) { 2427 final PackageSetting ps = (PackageSetting) p.mExtras; 2428 if (ps != null) { 2429 final PackageUserState state = ps.readUserState(userId); 2430 if (state != null) { 2431 return PackageParser.isAvailable(state); 2432 } 2433 } 2434 } 2435 } 2436 return false; 2437 } 2438 2439 @Override 2440 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2441 if (!sUserManager.exists(userId)) return null; 2442 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2443 // reader 2444 synchronized (mPackages) { 2445 PackageParser.Package p = mPackages.get(packageName); 2446 if (DEBUG_PACKAGE_INFO) 2447 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2448 if (p != null) { 2449 return generatePackageInfo(p, flags, userId); 2450 } 2451 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2452 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2453 } 2454 } 2455 return null; 2456 } 2457 2458 @Override 2459 public String[] currentToCanonicalPackageNames(String[] names) { 2460 String[] out = new String[names.length]; 2461 // reader 2462 synchronized (mPackages) { 2463 for (int i=names.length-1; i>=0; i--) { 2464 PackageSetting ps = mSettings.mPackages.get(names[i]); 2465 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2466 } 2467 } 2468 return out; 2469 } 2470 2471 @Override 2472 public String[] canonicalToCurrentPackageNames(String[] names) { 2473 String[] out = new String[names.length]; 2474 // reader 2475 synchronized (mPackages) { 2476 for (int i=names.length-1; i>=0; i--) { 2477 String cur = mSettings.mRenamedPackages.get(names[i]); 2478 out[i] = cur != null ? cur : names[i]; 2479 } 2480 } 2481 return out; 2482 } 2483 2484 @Override 2485 public int getPackageUid(String packageName, int userId) { 2486 if (!sUserManager.exists(userId)) return -1; 2487 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2488 2489 // reader 2490 synchronized (mPackages) { 2491 PackageParser.Package p = mPackages.get(packageName); 2492 if(p != null) { 2493 return UserHandle.getUid(userId, p.applicationInfo.uid); 2494 } 2495 PackageSetting ps = mSettings.mPackages.get(packageName); 2496 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2497 return -1; 2498 } 2499 p = ps.pkg; 2500 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2501 } 2502 } 2503 2504 @Override 2505 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2506 if (!sUserManager.exists(userId)) { 2507 return null; 2508 } 2509 2510 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2511 "getPackageGids"); 2512 2513 // reader 2514 synchronized (mPackages) { 2515 PackageParser.Package p = mPackages.get(packageName); 2516 if (DEBUG_PACKAGE_INFO) { 2517 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2518 } 2519 if (p != null) { 2520 PackageSetting ps = (PackageSetting) p.mExtras; 2521 return ps.getPermissionsState().computeGids(userId); 2522 } 2523 } 2524 2525 return null; 2526 } 2527 2528 static PermissionInfo generatePermissionInfo( 2529 BasePermission bp, int flags) { 2530 if (bp.perm != null) { 2531 return PackageParser.generatePermissionInfo(bp.perm, flags); 2532 } 2533 PermissionInfo pi = new PermissionInfo(); 2534 pi.name = bp.name; 2535 pi.packageName = bp.sourcePackage; 2536 pi.nonLocalizedLabel = bp.name; 2537 pi.protectionLevel = bp.protectionLevel; 2538 return pi; 2539 } 2540 2541 @Override 2542 public PermissionInfo getPermissionInfo(String name, int flags) { 2543 // reader 2544 synchronized (mPackages) { 2545 final BasePermission p = mSettings.mPermissions.get(name); 2546 if (p != null) { 2547 return generatePermissionInfo(p, flags); 2548 } 2549 return null; 2550 } 2551 } 2552 2553 @Override 2554 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2555 // reader 2556 synchronized (mPackages) { 2557 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2558 for (BasePermission p : mSettings.mPermissions.values()) { 2559 if (group == null) { 2560 if (p.perm == null || p.perm.info.group == null) { 2561 out.add(generatePermissionInfo(p, flags)); 2562 } 2563 } else { 2564 if (p.perm != null && group.equals(p.perm.info.group)) { 2565 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2566 } 2567 } 2568 } 2569 2570 if (out.size() > 0) { 2571 return out; 2572 } 2573 return mPermissionGroups.containsKey(group) ? out : null; 2574 } 2575 } 2576 2577 @Override 2578 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2579 // reader 2580 synchronized (mPackages) { 2581 return PackageParser.generatePermissionGroupInfo( 2582 mPermissionGroups.get(name), flags); 2583 } 2584 } 2585 2586 @Override 2587 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2588 // reader 2589 synchronized (mPackages) { 2590 final int N = mPermissionGroups.size(); 2591 ArrayList<PermissionGroupInfo> out 2592 = new ArrayList<PermissionGroupInfo>(N); 2593 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2594 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2595 } 2596 return out; 2597 } 2598 } 2599 2600 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2601 int userId) { 2602 if (!sUserManager.exists(userId)) return null; 2603 PackageSetting ps = mSettings.mPackages.get(packageName); 2604 if (ps != null) { 2605 if (ps.pkg == null) { 2606 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2607 flags, userId); 2608 if (pInfo != null) { 2609 return pInfo.applicationInfo; 2610 } 2611 return null; 2612 } 2613 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2614 ps.readUserState(userId), userId); 2615 } 2616 return null; 2617 } 2618 2619 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2620 int userId) { 2621 if (!sUserManager.exists(userId)) return null; 2622 PackageSetting ps = mSettings.mPackages.get(packageName); 2623 if (ps != null) { 2624 PackageParser.Package pkg = ps.pkg; 2625 if (pkg == null) { 2626 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2627 return null; 2628 } 2629 // Only data remains, so we aren't worried about code paths 2630 pkg = new PackageParser.Package(packageName); 2631 pkg.applicationInfo.packageName = packageName; 2632 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2633 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2634 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2635 packageName, userId).getAbsolutePath(); 2636 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2637 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2638 } 2639 return generatePackageInfo(pkg, flags, userId); 2640 } 2641 return null; 2642 } 2643 2644 @Override 2645 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2646 if (!sUserManager.exists(userId)) return null; 2647 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2648 // writer 2649 synchronized (mPackages) { 2650 PackageParser.Package p = mPackages.get(packageName); 2651 if (DEBUG_PACKAGE_INFO) Log.v( 2652 TAG, "getApplicationInfo " + packageName 2653 + ": " + p); 2654 if (p != null) { 2655 PackageSetting ps = mSettings.mPackages.get(packageName); 2656 if (ps == null) return null; 2657 // Note: isEnabledLP() does not apply here - always return info 2658 return PackageParser.generateApplicationInfo( 2659 p, flags, ps.readUserState(userId), userId); 2660 } 2661 if ("android".equals(packageName)||"system".equals(packageName)) { 2662 return mAndroidApplication; 2663 } 2664 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2665 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2666 } 2667 } 2668 return null; 2669 } 2670 2671 @Override 2672 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2673 final IPackageDataObserver observer) { 2674 mContext.enforceCallingOrSelfPermission( 2675 android.Manifest.permission.CLEAR_APP_CACHE, null); 2676 // Queue up an async operation since clearing cache may take a little while. 2677 mHandler.post(new Runnable() { 2678 public void run() { 2679 mHandler.removeCallbacks(this); 2680 int retCode = -1; 2681 synchronized (mInstallLock) { 2682 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2683 if (retCode < 0) { 2684 Slog.w(TAG, "Couldn't clear application caches"); 2685 } 2686 } 2687 if (observer != null) { 2688 try { 2689 observer.onRemoveCompleted(null, (retCode >= 0)); 2690 } catch (RemoteException e) { 2691 Slog.w(TAG, "RemoveException when invoking call back"); 2692 } 2693 } 2694 } 2695 }); 2696 } 2697 2698 @Override 2699 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2700 final IntentSender pi) { 2701 mContext.enforceCallingOrSelfPermission( 2702 android.Manifest.permission.CLEAR_APP_CACHE, null); 2703 // Queue up an async operation since clearing cache may take a little while. 2704 mHandler.post(new Runnable() { 2705 public void run() { 2706 mHandler.removeCallbacks(this); 2707 int retCode = -1; 2708 synchronized (mInstallLock) { 2709 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2710 if (retCode < 0) { 2711 Slog.w(TAG, "Couldn't clear application caches"); 2712 } 2713 } 2714 if(pi != null) { 2715 try { 2716 // Callback via pending intent 2717 int code = (retCode >= 0) ? 1 : 0; 2718 pi.sendIntent(null, code, null, 2719 null, null); 2720 } catch (SendIntentException e1) { 2721 Slog.i(TAG, "Failed to send pending intent"); 2722 } 2723 } 2724 } 2725 }); 2726 } 2727 2728 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2729 synchronized (mInstallLock) { 2730 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2731 throw new IOException("Failed to free enough space"); 2732 } 2733 } 2734 } 2735 2736 @Override 2737 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2738 if (!sUserManager.exists(userId)) return null; 2739 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2740 synchronized (mPackages) { 2741 PackageParser.Activity a = mActivities.mActivities.get(component); 2742 2743 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2744 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2745 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2746 if (ps == null) return null; 2747 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2748 userId); 2749 } 2750 if (mResolveComponentName.equals(component)) { 2751 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2752 new PackageUserState(), userId); 2753 } 2754 } 2755 return null; 2756 } 2757 2758 @Override 2759 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2760 String resolvedType) { 2761 synchronized (mPackages) { 2762 PackageParser.Activity a = mActivities.mActivities.get(component); 2763 if (a == null) { 2764 return false; 2765 } 2766 for (int i=0; i<a.intents.size(); i++) { 2767 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2768 intent.getData(), intent.getCategories(), TAG) >= 0) { 2769 return true; 2770 } 2771 } 2772 return false; 2773 } 2774 } 2775 2776 @Override 2777 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2778 if (!sUserManager.exists(userId)) return null; 2779 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2780 synchronized (mPackages) { 2781 PackageParser.Activity a = mReceivers.mActivities.get(component); 2782 if (DEBUG_PACKAGE_INFO) Log.v( 2783 TAG, "getReceiverInfo " + component + ": " + a); 2784 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2785 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2786 if (ps == null) return null; 2787 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2788 userId); 2789 } 2790 } 2791 return null; 2792 } 2793 2794 @Override 2795 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2796 if (!sUserManager.exists(userId)) return null; 2797 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2798 synchronized (mPackages) { 2799 PackageParser.Service s = mServices.mServices.get(component); 2800 if (DEBUG_PACKAGE_INFO) Log.v( 2801 TAG, "getServiceInfo " + component + ": " + s); 2802 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2803 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2804 if (ps == null) return null; 2805 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2806 userId); 2807 } 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2814 if (!sUserManager.exists(userId)) return null; 2815 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2816 synchronized (mPackages) { 2817 PackageParser.Provider p = mProviders.mProviders.get(component); 2818 if (DEBUG_PACKAGE_INFO) Log.v( 2819 TAG, "getProviderInfo " + component + ": " + p); 2820 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2821 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2822 if (ps == null) return null; 2823 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2824 userId); 2825 } 2826 } 2827 return null; 2828 } 2829 2830 @Override 2831 public String[] getSystemSharedLibraryNames() { 2832 Set<String> libSet; 2833 synchronized (mPackages) { 2834 libSet = mSharedLibraries.keySet(); 2835 int size = libSet.size(); 2836 if (size > 0) { 2837 String[] libs = new String[size]; 2838 libSet.toArray(libs); 2839 return libs; 2840 } 2841 } 2842 return null; 2843 } 2844 2845 /** 2846 * @hide 2847 */ 2848 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2849 synchronized (mPackages) { 2850 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2851 if (lib != null && lib.apk != null) { 2852 return mPackages.get(lib.apk); 2853 } 2854 } 2855 return null; 2856 } 2857 2858 @Override 2859 public FeatureInfo[] getSystemAvailableFeatures() { 2860 Collection<FeatureInfo> featSet; 2861 synchronized (mPackages) { 2862 featSet = mAvailableFeatures.values(); 2863 int size = featSet.size(); 2864 if (size > 0) { 2865 FeatureInfo[] features = new FeatureInfo[size+1]; 2866 featSet.toArray(features); 2867 FeatureInfo fi = new FeatureInfo(); 2868 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2869 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2870 features[size] = fi; 2871 return features; 2872 } 2873 } 2874 return null; 2875 } 2876 2877 @Override 2878 public boolean hasSystemFeature(String name) { 2879 synchronized (mPackages) { 2880 return mAvailableFeatures.containsKey(name); 2881 } 2882 } 2883 2884 private void checkValidCaller(int uid, int userId) { 2885 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2886 return; 2887 2888 throw new SecurityException("Caller uid=" + uid 2889 + " is not privileged to communicate with user=" + userId); 2890 } 2891 2892 @Override 2893 public int checkPermission(String permName, String pkgName, int userId) { 2894 if (!sUserManager.exists(userId)) { 2895 return PackageManager.PERMISSION_DENIED; 2896 } 2897 2898 synchronized (mPackages) { 2899 final PackageParser.Package p = mPackages.get(pkgName); 2900 if (p != null && p.mExtras != null) { 2901 final PackageSetting ps = (PackageSetting) p.mExtras; 2902 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2903 return PackageManager.PERMISSION_GRANTED; 2904 } 2905 } 2906 } 2907 2908 return PackageManager.PERMISSION_DENIED; 2909 } 2910 2911 @Override 2912 public int checkUidPermission(String permName, int uid) { 2913 final int userId = UserHandle.getUserId(uid); 2914 2915 if (!sUserManager.exists(userId)) { 2916 return PackageManager.PERMISSION_DENIED; 2917 } 2918 2919 synchronized (mPackages) { 2920 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2921 if (obj != null) { 2922 final SettingBase ps = (SettingBase) obj; 2923 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2924 return PackageManager.PERMISSION_GRANTED; 2925 } 2926 } else { 2927 ArraySet<String> perms = mSystemPermissions.get(uid); 2928 if (perms != null && perms.contains(permName)) { 2929 return PackageManager.PERMISSION_GRANTED; 2930 } 2931 } 2932 } 2933 2934 return PackageManager.PERMISSION_DENIED; 2935 } 2936 2937 /** 2938 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2939 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2940 * @param checkShell TODO(yamasani): 2941 * @param message the message to log on security exception 2942 */ 2943 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2944 boolean checkShell, String message) { 2945 if (userId < 0) { 2946 throw new IllegalArgumentException("Invalid userId " + userId); 2947 } 2948 if (checkShell) { 2949 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2950 } 2951 if (userId == UserHandle.getUserId(callingUid)) return; 2952 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2953 if (requireFullPermission) { 2954 mContext.enforceCallingOrSelfPermission( 2955 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2956 } else { 2957 try { 2958 mContext.enforceCallingOrSelfPermission( 2959 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2960 } catch (SecurityException se) { 2961 mContext.enforceCallingOrSelfPermission( 2962 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2963 } 2964 } 2965 } 2966 } 2967 2968 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2969 if (callingUid == Process.SHELL_UID) { 2970 if (userHandle >= 0 2971 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2972 throw new SecurityException("Shell does not have permission to access user " 2973 + userHandle); 2974 } else if (userHandle < 0) { 2975 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2976 + Debug.getCallers(3)); 2977 } 2978 } 2979 } 2980 2981 private BasePermission findPermissionTreeLP(String permName) { 2982 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2983 if (permName.startsWith(bp.name) && 2984 permName.length() > bp.name.length() && 2985 permName.charAt(bp.name.length()) == '.') { 2986 return bp; 2987 } 2988 } 2989 return null; 2990 } 2991 2992 private BasePermission checkPermissionTreeLP(String permName) { 2993 if (permName != null) { 2994 BasePermission bp = findPermissionTreeLP(permName); 2995 if (bp != null) { 2996 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2997 return bp; 2998 } 2999 throw new SecurityException("Calling uid " 3000 + Binder.getCallingUid() 3001 + " is not allowed to add to permission tree " 3002 + bp.name + " owned by uid " + bp.uid); 3003 } 3004 } 3005 throw new SecurityException("No permission tree found for " + permName); 3006 } 3007 3008 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3009 if (s1 == null) { 3010 return s2 == null; 3011 } 3012 if (s2 == null) { 3013 return false; 3014 } 3015 if (s1.getClass() != s2.getClass()) { 3016 return false; 3017 } 3018 return s1.equals(s2); 3019 } 3020 3021 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3022 if (pi1.icon != pi2.icon) return false; 3023 if (pi1.logo != pi2.logo) return false; 3024 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3025 if (!compareStrings(pi1.name, pi2.name)) return false; 3026 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3027 // We'll take care of setting this one. 3028 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3029 // These are not currently stored in settings. 3030 //if (!compareStrings(pi1.group, pi2.group)) return false; 3031 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3032 //if (pi1.labelRes != pi2.labelRes) return false; 3033 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3034 return true; 3035 } 3036 3037 int permissionInfoFootprint(PermissionInfo info) { 3038 int size = info.name.length(); 3039 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3040 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3041 return size; 3042 } 3043 3044 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3045 int size = 0; 3046 for (BasePermission perm : mSettings.mPermissions.values()) { 3047 if (perm.uid == tree.uid) { 3048 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3049 } 3050 } 3051 return size; 3052 } 3053 3054 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3055 // We calculate the max size of permissions defined by this uid and throw 3056 // if that plus the size of 'info' would exceed our stated maximum. 3057 if (tree.uid != Process.SYSTEM_UID) { 3058 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3059 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3060 throw new SecurityException("Permission tree size cap exceeded"); 3061 } 3062 } 3063 } 3064 3065 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3066 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3067 throw new SecurityException("Label must be specified in permission"); 3068 } 3069 BasePermission tree = checkPermissionTreeLP(info.name); 3070 BasePermission bp = mSettings.mPermissions.get(info.name); 3071 boolean added = bp == null; 3072 boolean changed = true; 3073 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3074 if (added) { 3075 enforcePermissionCapLocked(info, tree); 3076 bp = new BasePermission(info.name, tree.sourcePackage, 3077 BasePermission.TYPE_DYNAMIC); 3078 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3079 throw new SecurityException( 3080 "Not allowed to modify non-dynamic permission " 3081 + info.name); 3082 } else { 3083 if (bp.protectionLevel == fixedLevel 3084 && bp.perm.owner.equals(tree.perm.owner) 3085 && bp.uid == tree.uid 3086 && comparePermissionInfos(bp.perm.info, info)) { 3087 changed = false; 3088 } 3089 } 3090 bp.protectionLevel = fixedLevel; 3091 info = new PermissionInfo(info); 3092 info.protectionLevel = fixedLevel; 3093 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3094 bp.perm.info.packageName = tree.perm.info.packageName; 3095 bp.uid = tree.uid; 3096 if (added) { 3097 mSettings.mPermissions.put(info.name, bp); 3098 } 3099 if (changed) { 3100 if (!async) { 3101 mSettings.writeLPr(); 3102 } else { 3103 scheduleWriteSettingsLocked(); 3104 } 3105 } 3106 return added; 3107 } 3108 3109 @Override 3110 public boolean addPermission(PermissionInfo info) { 3111 synchronized (mPackages) { 3112 return addPermissionLocked(info, false); 3113 } 3114 } 3115 3116 @Override 3117 public boolean addPermissionAsync(PermissionInfo info) { 3118 synchronized (mPackages) { 3119 return addPermissionLocked(info, true); 3120 } 3121 } 3122 3123 @Override 3124 public void removePermission(String name) { 3125 synchronized (mPackages) { 3126 checkPermissionTreeLP(name); 3127 BasePermission bp = mSettings.mPermissions.get(name); 3128 if (bp != null) { 3129 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3130 throw new SecurityException( 3131 "Not allowed to modify non-dynamic permission " 3132 + name); 3133 } 3134 mSettings.mPermissions.remove(name); 3135 mSettings.writeLPr(); 3136 } 3137 } 3138 } 3139 3140 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3141 BasePermission bp) { 3142 int index = pkg.requestedPermissions.indexOf(bp.name); 3143 if (index == -1) { 3144 throw new SecurityException("Package " + pkg.packageName 3145 + " has not requested permission " + bp.name); 3146 } 3147 if (!bp.isRuntime()) { 3148 throw new SecurityException("Permission " + bp.name 3149 + " is not a changeable permission type"); 3150 } 3151 } 3152 3153 @Override 3154 public void grantRuntimePermission(String packageName, String name, int userId) { 3155 if (!sUserManager.exists(userId)) { 3156 Log.e(TAG, "No such user:" + userId); 3157 return; 3158 } 3159 3160 mContext.enforceCallingOrSelfPermission( 3161 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3162 "grantRuntimePermission"); 3163 3164 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3165 "grantRuntimePermission"); 3166 3167 boolean gidsChanged = false; 3168 final SettingBase sb; 3169 3170 synchronized (mPackages) { 3171 final PackageParser.Package pkg = mPackages.get(packageName); 3172 if (pkg == null) { 3173 throw new IllegalArgumentException("Unknown package: " + packageName); 3174 } 3175 3176 final BasePermission bp = mSettings.mPermissions.get(name); 3177 if (bp == null) { 3178 throw new IllegalArgumentException("Unknown permission: " + name); 3179 } 3180 3181 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3182 3183 sb = (SettingBase) pkg.mExtras; 3184 if (sb == null) { 3185 throw new IllegalArgumentException("Unknown package: " + packageName); 3186 } 3187 3188 final PermissionsState permissionsState = sb.getPermissionsState(); 3189 3190 final int flags = permissionsState.getPermissionFlags(name, userId); 3191 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3192 throw new SecurityException("Cannot grant system fixed permission: " 3193 + name + " for package: " + packageName); 3194 } 3195 3196 final int result = permissionsState.grantRuntimePermission(bp, userId); 3197 switch (result) { 3198 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3199 return; 3200 } 3201 3202 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3203 gidsChanged = true; 3204 } break; 3205 } 3206 3207 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3208 3209 // Not critical if that is lost - app has to request again. 3210 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3211 } 3212 3213 if (gidsChanged) { 3214 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3215 } 3216 } 3217 3218 @Override 3219 public void revokeRuntimePermission(String packageName, String name, int userId) { 3220 if (!sUserManager.exists(userId)) { 3221 Log.e(TAG, "No such user:" + userId); 3222 return; 3223 } 3224 3225 mContext.enforceCallingOrSelfPermission( 3226 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3227 "revokeRuntimePermission"); 3228 3229 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3230 "revokeRuntimePermission"); 3231 3232 final SettingBase sb; 3233 3234 synchronized (mPackages) { 3235 final PackageParser.Package pkg = mPackages.get(packageName); 3236 if (pkg == null) { 3237 throw new IllegalArgumentException("Unknown package: " + packageName); 3238 } 3239 3240 final BasePermission bp = mSettings.mPermissions.get(name); 3241 if (bp == null) { 3242 throw new IllegalArgumentException("Unknown permission: " + name); 3243 } 3244 3245 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3246 3247 sb = (SettingBase) pkg.mExtras; 3248 if (sb == null) { 3249 throw new IllegalArgumentException("Unknown package: " + packageName); 3250 } 3251 3252 final PermissionsState permissionsState = sb.getPermissionsState(); 3253 3254 final int flags = permissionsState.getPermissionFlags(name, userId); 3255 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3256 throw new SecurityException("Cannot revoke system fixed permission: " 3257 + name + " for package: " + packageName); 3258 } 3259 3260 if (permissionsState.revokeRuntimePermission(bp, userId) == 3261 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3262 return; 3263 } 3264 3265 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3266 3267 // Critical, after this call app should never have the permission. 3268 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3269 } 3270 3271 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3272 } 3273 3274 @Override 3275 public int getPermissionFlags(String name, String packageName, int userId) { 3276 if (!sUserManager.exists(userId)) { 3277 return 0; 3278 } 3279 3280 mContext.enforceCallingOrSelfPermission( 3281 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3282 "getPermissionFlags"); 3283 3284 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3285 "getPermissionFlags"); 3286 3287 synchronized (mPackages) { 3288 final PackageParser.Package pkg = mPackages.get(packageName); 3289 if (pkg == null) { 3290 throw new IllegalArgumentException("Unknown package: " + packageName); 3291 } 3292 3293 final BasePermission bp = mSettings.mPermissions.get(name); 3294 if (bp == null) { 3295 throw new IllegalArgumentException("Unknown permission: " + name); 3296 } 3297 3298 SettingBase sb = (SettingBase) pkg.mExtras; 3299 if (sb == null) { 3300 throw new IllegalArgumentException("Unknown package: " + packageName); 3301 } 3302 3303 PermissionsState permissionsState = sb.getPermissionsState(); 3304 return permissionsState.getPermissionFlags(name, userId); 3305 } 3306 } 3307 3308 @Override 3309 public void updatePermissionFlags(String name, String packageName, int flagMask, 3310 int flagValues, int userId) { 3311 if (!sUserManager.exists(userId)) { 3312 return; 3313 } 3314 3315 mContext.enforceCallingOrSelfPermission( 3316 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3317 "updatePermissionFlags"); 3318 3319 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3320 "updatePermissionFlags"); 3321 3322 // Only the system can change policy flags. 3323 if (getCallingUid() != Process.SYSTEM_UID) { 3324 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3325 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3326 } 3327 3328 // Only the package manager can change system flags. 3329 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3330 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3331 3332 synchronized (mPackages) { 3333 final PackageParser.Package pkg = mPackages.get(packageName); 3334 if (pkg == null) { 3335 throw new IllegalArgumentException("Unknown package: " + packageName); 3336 } 3337 3338 final BasePermission bp = mSettings.mPermissions.get(name); 3339 if (bp == null) { 3340 throw new IllegalArgumentException("Unknown permission: " + name); 3341 } 3342 3343 SettingBase sb = (SettingBase) pkg.mExtras; 3344 if (sb == null) { 3345 throw new IllegalArgumentException("Unknown package: " + packageName); 3346 } 3347 3348 PermissionsState permissionsState = sb.getPermissionsState(); 3349 3350 // Only the package manager can change flags for system component permissions. 3351 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3352 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3353 return; 3354 } 3355 3356 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3357 // Install and runtime permissions are stored in different places, 3358 // so figure out what permission changed and persist the change. 3359 if (permissionsState.getInstallPermissionState(name) != null) { 3360 scheduleWriteSettingsLocked(); 3361 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3362 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3363 } 3364 } 3365 } 3366 } 3367 3368 @Override 3369 public boolean shouldShowRequestPermissionRationale(String permissionName, 3370 String packageName, int userId) { 3371 if (UserHandle.getCallingUserId() != userId) { 3372 mContext.enforceCallingPermission( 3373 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3374 "canShowRequestPermissionRationale for user " + userId); 3375 } 3376 3377 final int uid = getPackageUid(packageName, userId); 3378 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3379 return false; 3380 } 3381 3382 if (checkPermission(permissionName, packageName, userId) 3383 == PackageManager.PERMISSION_GRANTED) { 3384 return false; 3385 } 3386 3387 final int flags; 3388 3389 final long identity = Binder.clearCallingIdentity(); 3390 try { 3391 flags = getPermissionFlags(permissionName, 3392 packageName, userId); 3393 } finally { 3394 Binder.restoreCallingIdentity(identity); 3395 } 3396 3397 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3398 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3399 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3400 3401 if ((flags & fixedFlags) != 0) { 3402 return false; 3403 } 3404 3405 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3406 } 3407 3408 @Override 3409 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3410 mContext.enforceCallingOrSelfPermission( 3411 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3412 "addOnPermissionsChangeListener"); 3413 3414 synchronized (mPackages) { 3415 mOnPermissionChangeListeners.addListenerLocked(listener); 3416 } 3417 } 3418 3419 @Override 3420 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3421 synchronized (mPackages) { 3422 mOnPermissionChangeListeners.removeListenerLocked(listener); 3423 } 3424 } 3425 3426 @Override 3427 public boolean isProtectedBroadcast(String actionName) { 3428 synchronized (mPackages) { 3429 return mProtectedBroadcasts.contains(actionName); 3430 } 3431 } 3432 3433 @Override 3434 public int checkSignatures(String pkg1, String pkg2) { 3435 synchronized (mPackages) { 3436 final PackageParser.Package p1 = mPackages.get(pkg1); 3437 final PackageParser.Package p2 = mPackages.get(pkg2); 3438 if (p1 == null || p1.mExtras == null 3439 || p2 == null || p2.mExtras == null) { 3440 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3441 } 3442 return compareSignatures(p1.mSignatures, p2.mSignatures); 3443 } 3444 } 3445 3446 @Override 3447 public int checkUidSignatures(int uid1, int uid2) { 3448 // Map to base uids. 3449 uid1 = UserHandle.getAppId(uid1); 3450 uid2 = UserHandle.getAppId(uid2); 3451 // reader 3452 synchronized (mPackages) { 3453 Signature[] s1; 3454 Signature[] s2; 3455 Object obj = mSettings.getUserIdLPr(uid1); 3456 if (obj != null) { 3457 if (obj instanceof SharedUserSetting) { 3458 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3459 } else if (obj instanceof PackageSetting) { 3460 s1 = ((PackageSetting)obj).signatures.mSignatures; 3461 } else { 3462 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3463 } 3464 } else { 3465 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3466 } 3467 obj = mSettings.getUserIdLPr(uid2); 3468 if (obj != null) { 3469 if (obj instanceof SharedUserSetting) { 3470 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3471 } else if (obj instanceof PackageSetting) { 3472 s2 = ((PackageSetting)obj).signatures.mSignatures; 3473 } else { 3474 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3475 } 3476 } else { 3477 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3478 } 3479 return compareSignatures(s1, s2); 3480 } 3481 } 3482 3483 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3484 final long identity = Binder.clearCallingIdentity(); 3485 try { 3486 if (sb instanceof SharedUserSetting) { 3487 SharedUserSetting sus = (SharedUserSetting) sb; 3488 final int packageCount = sus.packages.size(); 3489 for (int i = 0; i < packageCount; i++) { 3490 PackageSetting susPs = sus.packages.valueAt(i); 3491 if (userId == UserHandle.USER_ALL) { 3492 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3493 } else { 3494 final int uid = UserHandle.getUid(userId, susPs.appId); 3495 killUid(uid, reason); 3496 } 3497 } 3498 } else if (sb instanceof PackageSetting) { 3499 PackageSetting ps = (PackageSetting) sb; 3500 if (userId == UserHandle.USER_ALL) { 3501 killApplication(ps.pkg.packageName, ps.appId, reason); 3502 } else { 3503 final int uid = UserHandle.getUid(userId, ps.appId); 3504 killUid(uid, reason); 3505 } 3506 } 3507 } finally { 3508 Binder.restoreCallingIdentity(identity); 3509 } 3510 } 3511 3512 private static void killUid(int uid, String reason) { 3513 IActivityManager am = ActivityManagerNative.getDefault(); 3514 if (am != null) { 3515 try { 3516 am.killUid(uid, reason); 3517 } catch (RemoteException e) { 3518 /* ignore - same process */ 3519 } 3520 } 3521 } 3522 3523 /** 3524 * Compares two sets of signatures. Returns: 3525 * <br /> 3526 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3527 * <br /> 3528 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3529 * <br /> 3530 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3531 * <br /> 3532 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3533 * <br /> 3534 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3535 */ 3536 static int compareSignatures(Signature[] s1, Signature[] s2) { 3537 if (s1 == null) { 3538 return s2 == null 3539 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3540 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3541 } 3542 3543 if (s2 == null) { 3544 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3545 } 3546 3547 if (s1.length != s2.length) { 3548 return PackageManager.SIGNATURE_NO_MATCH; 3549 } 3550 3551 // Since both signature sets are of size 1, we can compare without HashSets. 3552 if (s1.length == 1) { 3553 return s1[0].equals(s2[0]) ? 3554 PackageManager.SIGNATURE_MATCH : 3555 PackageManager.SIGNATURE_NO_MATCH; 3556 } 3557 3558 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3559 for (Signature sig : s1) { 3560 set1.add(sig); 3561 } 3562 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3563 for (Signature sig : s2) { 3564 set2.add(sig); 3565 } 3566 // Make sure s2 contains all signatures in s1. 3567 if (set1.equals(set2)) { 3568 return PackageManager.SIGNATURE_MATCH; 3569 } 3570 return PackageManager.SIGNATURE_NO_MATCH; 3571 } 3572 3573 /** 3574 * If the database version for this type of package (internal storage or 3575 * external storage) is less than the version where package signatures 3576 * were updated, return true. 3577 */ 3578 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3579 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3580 DatabaseVersion.SIGNATURE_END_ENTITY)) 3581 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3582 DatabaseVersion.SIGNATURE_END_ENTITY)); 3583 } 3584 3585 /** 3586 * Used for backward compatibility to make sure any packages with 3587 * certificate chains get upgraded to the new style. {@code existingSigs} 3588 * will be in the old format (since they were stored on disk from before the 3589 * system upgrade) and {@code scannedSigs} will be in the newer format. 3590 */ 3591 private int compareSignaturesCompat(PackageSignatures existingSigs, 3592 PackageParser.Package scannedPkg) { 3593 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3594 return PackageManager.SIGNATURE_NO_MATCH; 3595 } 3596 3597 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3598 for (Signature sig : existingSigs.mSignatures) { 3599 existingSet.add(sig); 3600 } 3601 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3602 for (Signature sig : scannedPkg.mSignatures) { 3603 try { 3604 Signature[] chainSignatures = sig.getChainSignatures(); 3605 for (Signature chainSig : chainSignatures) { 3606 scannedCompatSet.add(chainSig); 3607 } 3608 } catch (CertificateEncodingException e) { 3609 scannedCompatSet.add(sig); 3610 } 3611 } 3612 /* 3613 * Make sure the expanded scanned set contains all signatures in the 3614 * existing one. 3615 */ 3616 if (scannedCompatSet.equals(existingSet)) { 3617 // Migrate the old signatures to the new scheme. 3618 existingSigs.assignSignatures(scannedPkg.mSignatures); 3619 // The new KeySets will be re-added later in the scanning process. 3620 synchronized (mPackages) { 3621 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3622 } 3623 return PackageManager.SIGNATURE_MATCH; 3624 } 3625 return PackageManager.SIGNATURE_NO_MATCH; 3626 } 3627 3628 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3629 if (isExternal(scannedPkg)) { 3630 return mSettings.isExternalDatabaseVersionOlderThan( 3631 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3632 } else { 3633 return mSettings.isInternalDatabaseVersionOlderThan( 3634 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3635 } 3636 } 3637 3638 private int compareSignaturesRecover(PackageSignatures existingSigs, 3639 PackageParser.Package scannedPkg) { 3640 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3641 return PackageManager.SIGNATURE_NO_MATCH; 3642 } 3643 3644 String msg = null; 3645 try { 3646 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3647 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3648 + scannedPkg.packageName); 3649 return PackageManager.SIGNATURE_MATCH; 3650 } 3651 } catch (CertificateException e) { 3652 msg = e.getMessage(); 3653 } 3654 3655 logCriticalInfo(Log.INFO, 3656 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3657 return PackageManager.SIGNATURE_NO_MATCH; 3658 } 3659 3660 @Override 3661 public String[] getPackagesForUid(int uid) { 3662 uid = UserHandle.getAppId(uid); 3663 // reader 3664 synchronized (mPackages) { 3665 Object obj = mSettings.getUserIdLPr(uid); 3666 if (obj instanceof SharedUserSetting) { 3667 final SharedUserSetting sus = (SharedUserSetting) obj; 3668 final int N = sus.packages.size(); 3669 final String[] res = new String[N]; 3670 final Iterator<PackageSetting> it = sus.packages.iterator(); 3671 int i = 0; 3672 while (it.hasNext()) { 3673 res[i++] = it.next().name; 3674 } 3675 return res; 3676 } else if (obj instanceof PackageSetting) { 3677 final PackageSetting ps = (PackageSetting) obj; 3678 return new String[] { ps.name }; 3679 } 3680 } 3681 return null; 3682 } 3683 3684 @Override 3685 public String getNameForUid(int uid) { 3686 // reader 3687 synchronized (mPackages) { 3688 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3689 if (obj instanceof SharedUserSetting) { 3690 final SharedUserSetting sus = (SharedUserSetting) obj; 3691 return sus.name + ":" + sus.userId; 3692 } else if (obj instanceof PackageSetting) { 3693 final PackageSetting ps = (PackageSetting) obj; 3694 return ps.name; 3695 } 3696 } 3697 return null; 3698 } 3699 3700 @Override 3701 public int getUidForSharedUser(String sharedUserName) { 3702 if(sharedUserName == null) { 3703 return -1; 3704 } 3705 // reader 3706 synchronized (mPackages) { 3707 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3708 if (suid == null) { 3709 return -1; 3710 } 3711 return suid.userId; 3712 } 3713 } 3714 3715 @Override 3716 public int getFlagsForUid(int uid) { 3717 synchronized (mPackages) { 3718 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3719 if (obj instanceof SharedUserSetting) { 3720 final SharedUserSetting sus = (SharedUserSetting) obj; 3721 return sus.pkgFlags; 3722 } else if (obj instanceof PackageSetting) { 3723 final PackageSetting ps = (PackageSetting) obj; 3724 return ps.pkgFlags; 3725 } 3726 } 3727 return 0; 3728 } 3729 3730 @Override 3731 public int getPrivateFlagsForUid(int uid) { 3732 synchronized (mPackages) { 3733 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3734 if (obj instanceof SharedUserSetting) { 3735 final SharedUserSetting sus = (SharedUserSetting) obj; 3736 return sus.pkgPrivateFlags; 3737 } else if (obj instanceof PackageSetting) { 3738 final PackageSetting ps = (PackageSetting) obj; 3739 return ps.pkgPrivateFlags; 3740 } 3741 } 3742 return 0; 3743 } 3744 3745 @Override 3746 public boolean isUidPrivileged(int uid) { 3747 uid = UserHandle.getAppId(uid); 3748 // reader 3749 synchronized (mPackages) { 3750 Object obj = mSettings.getUserIdLPr(uid); 3751 if (obj instanceof SharedUserSetting) { 3752 final SharedUserSetting sus = (SharedUserSetting) obj; 3753 final Iterator<PackageSetting> it = sus.packages.iterator(); 3754 while (it.hasNext()) { 3755 if (it.next().isPrivileged()) { 3756 return true; 3757 } 3758 } 3759 } else if (obj instanceof PackageSetting) { 3760 final PackageSetting ps = (PackageSetting) obj; 3761 return ps.isPrivileged(); 3762 } 3763 } 3764 return false; 3765 } 3766 3767 @Override 3768 public String[] getAppOpPermissionPackages(String permissionName) { 3769 synchronized (mPackages) { 3770 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3771 if (pkgs == null) { 3772 return null; 3773 } 3774 return pkgs.toArray(new String[pkgs.size()]); 3775 } 3776 } 3777 3778 @Override 3779 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3780 int flags, int userId) { 3781 if (!sUserManager.exists(userId)) return null; 3782 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3783 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3784 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3785 } 3786 3787 @Override 3788 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3789 IntentFilter filter, int match, ComponentName activity) { 3790 final int userId = UserHandle.getCallingUserId(); 3791 if (DEBUG_PREFERRED) { 3792 Log.v(TAG, "setLastChosenActivity intent=" + intent 3793 + " resolvedType=" + resolvedType 3794 + " flags=" + flags 3795 + " filter=" + filter 3796 + " match=" + match 3797 + " activity=" + activity); 3798 filter.dump(new PrintStreamPrinter(System.out), " "); 3799 } 3800 intent.setComponent(null); 3801 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3802 // Find any earlier preferred or last chosen entries and nuke them 3803 findPreferredActivity(intent, resolvedType, 3804 flags, query, 0, false, true, false, userId); 3805 // Add the new activity as the last chosen for this filter 3806 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3807 "Setting last chosen"); 3808 } 3809 3810 @Override 3811 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3812 final int userId = UserHandle.getCallingUserId(); 3813 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3814 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3815 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3816 false, false, false, userId); 3817 } 3818 3819 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3820 int flags, List<ResolveInfo> query, int userId) { 3821 if (query != null) { 3822 final int N = query.size(); 3823 if (N == 1) { 3824 return query.get(0); 3825 } else if (N > 1) { 3826 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3827 // If there is more than one activity with the same priority, 3828 // then let the user decide between them. 3829 ResolveInfo r0 = query.get(0); 3830 ResolveInfo r1 = query.get(1); 3831 if (DEBUG_INTENT_MATCHING || debug) { 3832 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3833 + r1.activityInfo.name + "=" + r1.priority); 3834 } 3835 // If the first activity has a higher priority, or a different 3836 // default, then it is always desireable to pick it. 3837 if (r0.priority != r1.priority 3838 || r0.preferredOrder != r1.preferredOrder 3839 || r0.isDefault != r1.isDefault) { 3840 return query.get(0); 3841 } 3842 // If we have saved a preference for a preferred activity for 3843 // this Intent, use that. 3844 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3845 flags, query, r0.priority, true, false, debug, userId); 3846 if (ri != null) { 3847 return ri; 3848 } 3849 if (userId != 0) { 3850 ri = new ResolveInfo(mResolveInfo); 3851 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3852 ri.activityInfo.applicationInfo = new ApplicationInfo( 3853 ri.activityInfo.applicationInfo); 3854 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3855 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3856 return ri; 3857 } 3858 return mResolveInfo; 3859 } 3860 } 3861 return null; 3862 } 3863 3864 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3865 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3866 final int N = query.size(); 3867 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3868 .get(userId); 3869 // Get the list of persistent preferred activities that handle the intent 3870 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3871 List<PersistentPreferredActivity> pprefs = ppir != null 3872 ? ppir.queryIntent(intent, resolvedType, 3873 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3874 : null; 3875 if (pprefs != null && pprefs.size() > 0) { 3876 final int M = pprefs.size(); 3877 for (int i=0; i<M; i++) { 3878 final PersistentPreferredActivity ppa = pprefs.get(i); 3879 if (DEBUG_PREFERRED || debug) { 3880 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3881 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3882 + "\n component=" + ppa.mComponent); 3883 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3884 } 3885 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3886 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3887 if (DEBUG_PREFERRED || debug) { 3888 Slog.v(TAG, "Found persistent preferred activity:"); 3889 if (ai != null) { 3890 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3891 } else { 3892 Slog.v(TAG, " null"); 3893 } 3894 } 3895 if (ai == null) { 3896 // This previously registered persistent preferred activity 3897 // component is no longer known. Ignore it and do NOT remove it. 3898 continue; 3899 } 3900 for (int j=0; j<N; j++) { 3901 final ResolveInfo ri = query.get(j); 3902 if (!ri.activityInfo.applicationInfo.packageName 3903 .equals(ai.applicationInfo.packageName)) { 3904 continue; 3905 } 3906 if (!ri.activityInfo.name.equals(ai.name)) { 3907 continue; 3908 } 3909 // Found a persistent preference that can handle the intent. 3910 if (DEBUG_PREFERRED || debug) { 3911 Slog.v(TAG, "Returning persistent preferred activity: " + 3912 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3913 } 3914 return ri; 3915 } 3916 } 3917 } 3918 return null; 3919 } 3920 3921 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3922 List<ResolveInfo> query, int priority, boolean always, 3923 boolean removeMatches, boolean debug, int userId) { 3924 if (!sUserManager.exists(userId)) return null; 3925 // writer 3926 synchronized (mPackages) { 3927 if (intent.getSelector() != null) { 3928 intent = intent.getSelector(); 3929 } 3930 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3931 3932 // Try to find a matching persistent preferred activity. 3933 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3934 debug, userId); 3935 3936 // If a persistent preferred activity matched, use it. 3937 if (pri != null) { 3938 return pri; 3939 } 3940 3941 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3942 // Get the list of preferred activities that handle the intent 3943 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3944 List<PreferredActivity> prefs = pir != null 3945 ? pir.queryIntent(intent, resolvedType, 3946 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3947 : null; 3948 if (prefs != null && prefs.size() > 0) { 3949 boolean changed = false; 3950 try { 3951 // First figure out how good the original match set is. 3952 // We will only allow preferred activities that came 3953 // from the same match quality. 3954 int match = 0; 3955 3956 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3957 3958 final int N = query.size(); 3959 for (int j=0; j<N; j++) { 3960 final ResolveInfo ri = query.get(j); 3961 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3962 + ": 0x" + Integer.toHexString(match)); 3963 if (ri.match > match) { 3964 match = ri.match; 3965 } 3966 } 3967 3968 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3969 + Integer.toHexString(match)); 3970 3971 match &= IntentFilter.MATCH_CATEGORY_MASK; 3972 final int M = prefs.size(); 3973 for (int i=0; i<M; i++) { 3974 final PreferredActivity pa = prefs.get(i); 3975 if (DEBUG_PREFERRED || debug) { 3976 Slog.v(TAG, "Checking PreferredActivity ds=" 3977 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3978 + "\n component=" + pa.mPref.mComponent); 3979 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3980 } 3981 if (pa.mPref.mMatch != match) { 3982 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3983 + Integer.toHexString(pa.mPref.mMatch)); 3984 continue; 3985 } 3986 // If it's not an "always" type preferred activity and that's what we're 3987 // looking for, skip it. 3988 if (always && !pa.mPref.mAlways) { 3989 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3990 continue; 3991 } 3992 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3993 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3994 if (DEBUG_PREFERRED || debug) { 3995 Slog.v(TAG, "Found preferred activity:"); 3996 if (ai != null) { 3997 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3998 } else { 3999 Slog.v(TAG, " null"); 4000 } 4001 } 4002 if (ai == null) { 4003 // This previously registered preferred activity 4004 // component is no longer known. Most likely an update 4005 // to the app was installed and in the new version this 4006 // component no longer exists. Clean it up by removing 4007 // it from the preferred activities list, and skip it. 4008 Slog.w(TAG, "Removing dangling preferred activity: " 4009 + pa.mPref.mComponent); 4010 pir.removeFilter(pa); 4011 changed = true; 4012 continue; 4013 } 4014 for (int j=0; j<N; j++) { 4015 final ResolveInfo ri = query.get(j); 4016 if (!ri.activityInfo.applicationInfo.packageName 4017 .equals(ai.applicationInfo.packageName)) { 4018 continue; 4019 } 4020 if (!ri.activityInfo.name.equals(ai.name)) { 4021 continue; 4022 } 4023 4024 if (removeMatches) { 4025 pir.removeFilter(pa); 4026 changed = true; 4027 if (DEBUG_PREFERRED) { 4028 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4029 } 4030 break; 4031 } 4032 4033 // Okay we found a previously set preferred or last chosen app. 4034 // If the result set is different from when this 4035 // was created, we need to clear it and re-ask the 4036 // user their preference, if we're looking for an "always" type entry. 4037 if (always && !pa.mPref.sameSet(query)) { 4038 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4039 + intent + " type " + resolvedType); 4040 if (DEBUG_PREFERRED) { 4041 Slog.v(TAG, "Removing preferred activity since set changed " 4042 + pa.mPref.mComponent); 4043 } 4044 pir.removeFilter(pa); 4045 // Re-add the filter as a "last chosen" entry (!always) 4046 PreferredActivity lastChosen = new PreferredActivity( 4047 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4048 pir.addFilter(lastChosen); 4049 changed = true; 4050 return null; 4051 } 4052 4053 // Yay! Either the set matched or we're looking for the last chosen 4054 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4055 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4056 return ri; 4057 } 4058 } 4059 } finally { 4060 if (changed) { 4061 if (DEBUG_PREFERRED) { 4062 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4063 } 4064 scheduleWritePackageRestrictionsLocked(userId); 4065 } 4066 } 4067 } 4068 } 4069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4070 return null; 4071 } 4072 4073 /* 4074 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4075 */ 4076 @Override 4077 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4078 int targetUserId) { 4079 mContext.enforceCallingOrSelfPermission( 4080 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4081 List<CrossProfileIntentFilter> matches = 4082 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4083 if (matches != null) { 4084 int size = matches.size(); 4085 for (int i = 0; i < size; i++) { 4086 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4087 } 4088 } 4089 return false; 4090 } 4091 4092 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4093 String resolvedType, int userId) { 4094 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4095 if (resolver != null) { 4096 return resolver.queryIntent(intent, resolvedType, false, userId); 4097 } 4098 return null; 4099 } 4100 4101 @Override 4102 public List<ResolveInfo> queryIntentActivities(Intent intent, 4103 String resolvedType, int flags, int userId) { 4104 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4105 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4106 ComponentName comp = intent.getComponent(); 4107 if (comp == null) { 4108 if (intent.getSelector() != null) { 4109 intent = intent.getSelector(); 4110 comp = intent.getComponent(); 4111 } 4112 } 4113 4114 if (comp != null) { 4115 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4116 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4117 if (ai != null) { 4118 final ResolveInfo ri = new ResolveInfo(); 4119 ri.activityInfo = ai; 4120 list.add(ri); 4121 } 4122 return list; 4123 } 4124 4125 // reader 4126 synchronized (mPackages) { 4127 final String pkgName = intent.getPackage(); 4128 if (pkgName == null) { 4129 List<CrossProfileIntentFilter> matchingFilters = 4130 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4131 // Check for results that need to skip the current profile. 4132 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4133 resolvedType, flags, userId); 4134 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4135 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4136 result.add(resolveInfo); 4137 return filterIfNotPrimaryUser(result, userId); 4138 } 4139 4140 // Check for results in the current profile. 4141 List<ResolveInfo> result = mActivities.queryIntent( 4142 intent, resolvedType, flags, userId); 4143 4144 // Check for cross profile results. 4145 resolveInfo = queryCrossProfileIntents( 4146 matchingFilters, intent, resolvedType, flags, userId); 4147 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4148 result.add(resolveInfo); 4149 Collections.sort(result, mResolvePrioritySorter); 4150 } 4151 result = filterIfNotPrimaryUser(result, userId); 4152 if (result.size() > 1 && hasWebURI(intent)) { 4153 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4154 } 4155 return result; 4156 } 4157 final PackageParser.Package pkg = mPackages.get(pkgName); 4158 if (pkg != null) { 4159 return filterIfNotPrimaryUser( 4160 mActivities.queryIntentForPackage( 4161 intent, resolvedType, flags, pkg.activities, userId), 4162 userId); 4163 } 4164 return new ArrayList<ResolveInfo>(); 4165 } 4166 } 4167 4168 private boolean isUserEnabled(int userId) { 4169 long callingId = Binder.clearCallingIdentity(); 4170 try { 4171 UserInfo userInfo = sUserManager.getUserInfo(userId); 4172 return userInfo != null && userInfo.isEnabled(); 4173 } finally { 4174 Binder.restoreCallingIdentity(callingId); 4175 } 4176 } 4177 4178 /** 4179 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4180 * 4181 * @return filtered list 4182 */ 4183 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4184 if (userId == UserHandle.USER_OWNER) { 4185 return resolveInfos; 4186 } 4187 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4188 ResolveInfo info = resolveInfos.get(i); 4189 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4190 resolveInfos.remove(i); 4191 } 4192 } 4193 return resolveInfos; 4194 } 4195 4196 private static boolean hasWebURI(Intent intent) { 4197 if (intent.getData() == null) { 4198 return false; 4199 } 4200 final String scheme = intent.getScheme(); 4201 if (TextUtils.isEmpty(scheme)) { 4202 return false; 4203 } 4204 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4205 } 4206 4207 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4208 int flags, List<ResolveInfo> candidates) { 4209 if (DEBUG_PREFERRED) { 4210 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4211 candidates.size()); 4212 } 4213 4214 final int userId = UserHandle.getCallingUserId(); 4215 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4216 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4217 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4218 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4219 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4220 4221 synchronized (mPackages) { 4222 final int count = candidates.size(); 4223 // First, try to use the domain prefered App. Partition the candidates into four lists: 4224 // one for the final results, one for the "do not use ever", one for "undefined status" 4225 // and finally one for "Browser App type". 4226 for (int n=0; n<count; n++) { 4227 ResolveInfo info = candidates.get(n); 4228 String packageName = info.activityInfo.packageName; 4229 PackageSetting ps = mSettings.mPackages.get(packageName); 4230 if (ps != null) { 4231 // Add to the special match all list (Browser use case) 4232 if (info.handleAllWebDataURI) { 4233 matchAllList.add(info); 4234 continue; 4235 } 4236 // Try to get the status from User settings first 4237 int status = getDomainVerificationStatusLPr(ps, userId); 4238 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4239 alwaysList.add(info); 4240 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4241 neverList.add(info); 4242 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4243 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4244 undefinedList.add(info); 4245 } 4246 } 4247 } 4248 // First try to add the "always" if there is any 4249 if (alwaysList.size() > 0) { 4250 result.addAll(alwaysList); 4251 } else { 4252 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4253 result.addAll(undefinedList); 4254 // Also add Browsers (all of them or only the default one) 4255 if ((flags & MATCH_ALL) != 0) { 4256 result.addAll(matchAllList); 4257 } else { 4258 // Try to add the Default Browser if we can 4259 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4260 UserHandle.myUserId()); 4261 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4262 boolean defaultBrowserFound = false; 4263 final int browserCount = matchAllList.size(); 4264 for (int n=0; n<browserCount; n++) { 4265 ResolveInfo browser = matchAllList.get(n); 4266 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4267 result.add(browser); 4268 defaultBrowserFound = true; 4269 break; 4270 } 4271 } 4272 if (!defaultBrowserFound) { 4273 result.addAll(matchAllList); 4274 } 4275 } else { 4276 result.addAll(matchAllList); 4277 } 4278 } 4279 4280 // If there is nothing selected, add all candidates and remove the ones that the User 4281 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4282 if (result.size() == 0) { 4283 result.addAll(candidates); 4284 result.removeAll(neverList); 4285 } 4286 } 4287 } 4288 if (DEBUG_PREFERRED) { 4289 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4290 result.size()); 4291 } 4292 return result; 4293 } 4294 4295 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4296 int status = ps.getDomainVerificationStatusForUser(userId); 4297 // if none available, get the master status 4298 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4299 if (ps.getIntentFilterVerificationInfo() != null) { 4300 status = ps.getIntentFilterVerificationInfo().getStatus(); 4301 } 4302 } 4303 return status; 4304 } 4305 4306 private ResolveInfo querySkipCurrentProfileIntents( 4307 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4308 int flags, int sourceUserId) { 4309 if (matchingFilters != null) { 4310 int size = matchingFilters.size(); 4311 for (int i = 0; i < size; i ++) { 4312 CrossProfileIntentFilter filter = matchingFilters.get(i); 4313 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4314 // Checking if there are activities in the target user that can handle the 4315 // intent. 4316 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4317 flags, sourceUserId); 4318 if (resolveInfo != null) { 4319 return resolveInfo; 4320 } 4321 } 4322 } 4323 } 4324 return null; 4325 } 4326 4327 // Return matching ResolveInfo if any for skip current profile intent filters. 4328 private ResolveInfo queryCrossProfileIntents( 4329 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4330 int flags, int sourceUserId) { 4331 if (matchingFilters != null) { 4332 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4333 // match the same intent. For performance reasons, it is better not to 4334 // run queryIntent twice for the same userId 4335 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4336 int size = matchingFilters.size(); 4337 for (int i = 0; i < size; i++) { 4338 CrossProfileIntentFilter filter = matchingFilters.get(i); 4339 int targetUserId = filter.getTargetUserId(); 4340 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4341 && !alreadyTriedUserIds.get(targetUserId)) { 4342 // Checking if there are activities in the target user that can handle the 4343 // intent. 4344 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4345 flags, sourceUserId); 4346 if (resolveInfo != null) return resolveInfo; 4347 alreadyTriedUserIds.put(targetUserId, true); 4348 } 4349 } 4350 } 4351 return null; 4352 } 4353 4354 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4355 String resolvedType, int flags, int sourceUserId) { 4356 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4357 resolvedType, flags, filter.getTargetUserId()); 4358 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4359 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4360 } 4361 return null; 4362 } 4363 4364 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4365 int sourceUserId, int targetUserId) { 4366 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4367 String className; 4368 if (targetUserId == UserHandle.USER_OWNER) { 4369 className = FORWARD_INTENT_TO_USER_OWNER; 4370 } else { 4371 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4372 } 4373 ComponentName forwardingActivityComponentName = new ComponentName( 4374 mAndroidApplication.packageName, className); 4375 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4376 sourceUserId); 4377 if (targetUserId == UserHandle.USER_OWNER) { 4378 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4379 forwardingResolveInfo.noResourceId = true; 4380 } 4381 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4382 forwardingResolveInfo.priority = 0; 4383 forwardingResolveInfo.preferredOrder = 0; 4384 forwardingResolveInfo.match = 0; 4385 forwardingResolveInfo.isDefault = true; 4386 forwardingResolveInfo.filter = filter; 4387 forwardingResolveInfo.targetUserId = targetUserId; 4388 return forwardingResolveInfo; 4389 } 4390 4391 @Override 4392 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4393 Intent[] specifics, String[] specificTypes, Intent intent, 4394 String resolvedType, int flags, int userId) { 4395 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4396 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4397 false, "query intent activity options"); 4398 final String resultsAction = intent.getAction(); 4399 4400 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4401 | PackageManager.GET_RESOLVED_FILTER, userId); 4402 4403 if (DEBUG_INTENT_MATCHING) { 4404 Log.v(TAG, "Query " + intent + ": " + results); 4405 } 4406 4407 int specificsPos = 0; 4408 int N; 4409 4410 // todo: note that the algorithm used here is O(N^2). This 4411 // isn't a problem in our current environment, but if we start running 4412 // into situations where we have more than 5 or 10 matches then this 4413 // should probably be changed to something smarter... 4414 4415 // First we go through and resolve each of the specific items 4416 // that were supplied, taking care of removing any corresponding 4417 // duplicate items in the generic resolve list. 4418 if (specifics != null) { 4419 for (int i=0; i<specifics.length; i++) { 4420 final Intent sintent = specifics[i]; 4421 if (sintent == null) { 4422 continue; 4423 } 4424 4425 if (DEBUG_INTENT_MATCHING) { 4426 Log.v(TAG, "Specific #" + i + ": " + sintent); 4427 } 4428 4429 String action = sintent.getAction(); 4430 if (resultsAction != null && resultsAction.equals(action)) { 4431 // If this action was explicitly requested, then don't 4432 // remove things that have it. 4433 action = null; 4434 } 4435 4436 ResolveInfo ri = null; 4437 ActivityInfo ai = null; 4438 4439 ComponentName comp = sintent.getComponent(); 4440 if (comp == null) { 4441 ri = resolveIntent( 4442 sintent, 4443 specificTypes != null ? specificTypes[i] : null, 4444 flags, userId); 4445 if (ri == null) { 4446 continue; 4447 } 4448 if (ri == mResolveInfo) { 4449 // ACK! Must do something better with this. 4450 } 4451 ai = ri.activityInfo; 4452 comp = new ComponentName(ai.applicationInfo.packageName, 4453 ai.name); 4454 } else { 4455 ai = getActivityInfo(comp, flags, userId); 4456 if (ai == null) { 4457 continue; 4458 } 4459 } 4460 4461 // Look for any generic query activities that are duplicates 4462 // of this specific one, and remove them from the results. 4463 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4464 N = results.size(); 4465 int j; 4466 for (j=specificsPos; j<N; j++) { 4467 ResolveInfo sri = results.get(j); 4468 if ((sri.activityInfo.name.equals(comp.getClassName()) 4469 && sri.activityInfo.applicationInfo.packageName.equals( 4470 comp.getPackageName())) 4471 || (action != null && sri.filter.matchAction(action))) { 4472 results.remove(j); 4473 if (DEBUG_INTENT_MATCHING) Log.v( 4474 TAG, "Removing duplicate item from " + j 4475 + " due to specific " + specificsPos); 4476 if (ri == null) { 4477 ri = sri; 4478 } 4479 j--; 4480 N--; 4481 } 4482 } 4483 4484 // Add this specific item to its proper place. 4485 if (ri == null) { 4486 ri = new ResolveInfo(); 4487 ri.activityInfo = ai; 4488 } 4489 results.add(specificsPos, ri); 4490 ri.specificIndex = i; 4491 specificsPos++; 4492 } 4493 } 4494 4495 // Now we go through the remaining generic results and remove any 4496 // duplicate actions that are found here. 4497 N = results.size(); 4498 for (int i=specificsPos; i<N-1; i++) { 4499 final ResolveInfo rii = results.get(i); 4500 if (rii.filter == null) { 4501 continue; 4502 } 4503 4504 // Iterate over all of the actions of this result's intent 4505 // filter... typically this should be just one. 4506 final Iterator<String> it = rii.filter.actionsIterator(); 4507 if (it == null) { 4508 continue; 4509 } 4510 while (it.hasNext()) { 4511 final String action = it.next(); 4512 if (resultsAction != null && resultsAction.equals(action)) { 4513 // If this action was explicitly requested, then don't 4514 // remove things that have it. 4515 continue; 4516 } 4517 for (int j=i+1; j<N; j++) { 4518 final ResolveInfo rij = results.get(j); 4519 if (rij.filter != null && rij.filter.hasAction(action)) { 4520 results.remove(j); 4521 if (DEBUG_INTENT_MATCHING) Log.v( 4522 TAG, "Removing duplicate item from " + j 4523 + " due to action " + action + " at " + i); 4524 j--; 4525 N--; 4526 } 4527 } 4528 } 4529 4530 // If the caller didn't request filter information, drop it now 4531 // so we don't have to marshall/unmarshall it. 4532 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4533 rii.filter = null; 4534 } 4535 } 4536 4537 // Filter out the caller activity if so requested. 4538 if (caller != null) { 4539 N = results.size(); 4540 for (int i=0; i<N; i++) { 4541 ActivityInfo ainfo = results.get(i).activityInfo; 4542 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4543 && caller.getClassName().equals(ainfo.name)) { 4544 results.remove(i); 4545 break; 4546 } 4547 } 4548 } 4549 4550 // If the caller didn't request filter information, 4551 // drop them now so we don't have to 4552 // marshall/unmarshall it. 4553 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4554 N = results.size(); 4555 for (int i=0; i<N; i++) { 4556 results.get(i).filter = null; 4557 } 4558 } 4559 4560 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4561 return results; 4562 } 4563 4564 @Override 4565 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4566 int userId) { 4567 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4568 ComponentName comp = intent.getComponent(); 4569 if (comp == null) { 4570 if (intent.getSelector() != null) { 4571 intent = intent.getSelector(); 4572 comp = intent.getComponent(); 4573 } 4574 } 4575 if (comp != null) { 4576 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4577 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4578 if (ai != null) { 4579 ResolveInfo ri = new ResolveInfo(); 4580 ri.activityInfo = ai; 4581 list.add(ri); 4582 } 4583 return list; 4584 } 4585 4586 // reader 4587 synchronized (mPackages) { 4588 String pkgName = intent.getPackage(); 4589 if (pkgName == null) { 4590 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4591 } 4592 final PackageParser.Package pkg = mPackages.get(pkgName); 4593 if (pkg != null) { 4594 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4595 userId); 4596 } 4597 return null; 4598 } 4599 } 4600 4601 @Override 4602 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4603 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4604 if (!sUserManager.exists(userId)) return null; 4605 if (query != null) { 4606 if (query.size() >= 1) { 4607 // If there is more than one service with the same priority, 4608 // just arbitrarily pick the first one. 4609 return query.get(0); 4610 } 4611 } 4612 return null; 4613 } 4614 4615 @Override 4616 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4617 int userId) { 4618 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4619 ComponentName comp = intent.getComponent(); 4620 if (comp == null) { 4621 if (intent.getSelector() != null) { 4622 intent = intent.getSelector(); 4623 comp = intent.getComponent(); 4624 } 4625 } 4626 if (comp != null) { 4627 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4628 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4629 if (si != null) { 4630 final ResolveInfo ri = new ResolveInfo(); 4631 ri.serviceInfo = si; 4632 list.add(ri); 4633 } 4634 return list; 4635 } 4636 4637 // reader 4638 synchronized (mPackages) { 4639 String pkgName = intent.getPackage(); 4640 if (pkgName == null) { 4641 return mServices.queryIntent(intent, resolvedType, flags, userId); 4642 } 4643 final PackageParser.Package pkg = mPackages.get(pkgName); 4644 if (pkg != null) { 4645 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4646 userId); 4647 } 4648 return null; 4649 } 4650 } 4651 4652 @Override 4653 public List<ResolveInfo> queryIntentContentProviders( 4654 Intent intent, String resolvedType, int flags, int userId) { 4655 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4656 ComponentName comp = intent.getComponent(); 4657 if (comp == null) { 4658 if (intent.getSelector() != null) { 4659 intent = intent.getSelector(); 4660 comp = intent.getComponent(); 4661 } 4662 } 4663 if (comp != null) { 4664 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4665 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4666 if (pi != null) { 4667 final ResolveInfo ri = new ResolveInfo(); 4668 ri.providerInfo = pi; 4669 list.add(ri); 4670 } 4671 return list; 4672 } 4673 4674 // reader 4675 synchronized (mPackages) { 4676 String pkgName = intent.getPackage(); 4677 if (pkgName == null) { 4678 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4679 } 4680 final PackageParser.Package pkg = mPackages.get(pkgName); 4681 if (pkg != null) { 4682 return mProviders.queryIntentForPackage( 4683 intent, resolvedType, flags, pkg.providers, userId); 4684 } 4685 return null; 4686 } 4687 } 4688 4689 @Override 4690 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4691 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4692 4693 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4694 4695 // writer 4696 synchronized (mPackages) { 4697 ArrayList<PackageInfo> list; 4698 if (listUninstalled) { 4699 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4700 for (PackageSetting ps : mSettings.mPackages.values()) { 4701 PackageInfo pi; 4702 if (ps.pkg != null) { 4703 pi = generatePackageInfo(ps.pkg, flags, userId); 4704 } else { 4705 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4706 } 4707 if (pi != null) { 4708 list.add(pi); 4709 } 4710 } 4711 } else { 4712 list = new ArrayList<PackageInfo>(mPackages.size()); 4713 for (PackageParser.Package p : mPackages.values()) { 4714 PackageInfo pi = generatePackageInfo(p, flags, userId); 4715 if (pi != null) { 4716 list.add(pi); 4717 } 4718 } 4719 } 4720 4721 return new ParceledListSlice<PackageInfo>(list); 4722 } 4723 } 4724 4725 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4726 String[] permissions, boolean[] tmp, int flags, int userId) { 4727 int numMatch = 0; 4728 final PermissionsState permissionsState = ps.getPermissionsState(); 4729 for (int i=0; i<permissions.length; i++) { 4730 final String permission = permissions[i]; 4731 if (permissionsState.hasPermission(permission, userId)) { 4732 tmp[i] = true; 4733 numMatch++; 4734 } else { 4735 tmp[i] = false; 4736 } 4737 } 4738 if (numMatch == 0) { 4739 return; 4740 } 4741 PackageInfo pi; 4742 if (ps.pkg != null) { 4743 pi = generatePackageInfo(ps.pkg, flags, userId); 4744 } else { 4745 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4746 } 4747 // The above might return null in cases of uninstalled apps or install-state 4748 // skew across users/profiles. 4749 if (pi != null) { 4750 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4751 if (numMatch == permissions.length) { 4752 pi.requestedPermissions = permissions; 4753 } else { 4754 pi.requestedPermissions = new String[numMatch]; 4755 numMatch = 0; 4756 for (int i=0; i<permissions.length; i++) { 4757 if (tmp[i]) { 4758 pi.requestedPermissions[numMatch] = permissions[i]; 4759 numMatch++; 4760 } 4761 } 4762 } 4763 } 4764 list.add(pi); 4765 } 4766 } 4767 4768 @Override 4769 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4770 String[] permissions, int flags, int userId) { 4771 if (!sUserManager.exists(userId)) return null; 4772 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4773 4774 // writer 4775 synchronized (mPackages) { 4776 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4777 boolean[] tmpBools = new boolean[permissions.length]; 4778 if (listUninstalled) { 4779 for (PackageSetting ps : mSettings.mPackages.values()) { 4780 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4781 } 4782 } else { 4783 for (PackageParser.Package pkg : mPackages.values()) { 4784 PackageSetting ps = (PackageSetting)pkg.mExtras; 4785 if (ps != null) { 4786 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4787 userId); 4788 } 4789 } 4790 } 4791 4792 return new ParceledListSlice<PackageInfo>(list); 4793 } 4794 } 4795 4796 @Override 4797 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4798 if (!sUserManager.exists(userId)) return null; 4799 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4800 4801 // writer 4802 synchronized (mPackages) { 4803 ArrayList<ApplicationInfo> list; 4804 if (listUninstalled) { 4805 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4806 for (PackageSetting ps : mSettings.mPackages.values()) { 4807 ApplicationInfo ai; 4808 if (ps.pkg != null) { 4809 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4810 ps.readUserState(userId), userId); 4811 } else { 4812 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4813 } 4814 if (ai != null) { 4815 list.add(ai); 4816 } 4817 } 4818 } else { 4819 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4820 for (PackageParser.Package p : mPackages.values()) { 4821 if (p.mExtras != null) { 4822 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4823 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4824 if (ai != null) { 4825 list.add(ai); 4826 } 4827 } 4828 } 4829 } 4830 4831 return new ParceledListSlice<ApplicationInfo>(list); 4832 } 4833 } 4834 4835 public List<ApplicationInfo> getPersistentApplications(int flags) { 4836 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4837 4838 // reader 4839 synchronized (mPackages) { 4840 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4841 final int userId = UserHandle.getCallingUserId(); 4842 while (i.hasNext()) { 4843 final PackageParser.Package p = i.next(); 4844 if (p.applicationInfo != null 4845 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4846 && (!mSafeMode || isSystemApp(p))) { 4847 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4848 if (ps != null) { 4849 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4850 ps.readUserState(userId), userId); 4851 if (ai != null) { 4852 finalList.add(ai); 4853 } 4854 } 4855 } 4856 } 4857 } 4858 4859 return finalList; 4860 } 4861 4862 @Override 4863 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4864 if (!sUserManager.exists(userId)) return null; 4865 // reader 4866 synchronized (mPackages) { 4867 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4868 PackageSetting ps = provider != null 4869 ? mSettings.mPackages.get(provider.owner.packageName) 4870 : null; 4871 return ps != null 4872 && mSettings.isEnabledLPr(provider.info, flags, userId) 4873 && (!mSafeMode || (provider.info.applicationInfo.flags 4874 &ApplicationInfo.FLAG_SYSTEM) != 0) 4875 ? PackageParser.generateProviderInfo(provider, flags, 4876 ps.readUserState(userId), userId) 4877 : null; 4878 } 4879 } 4880 4881 /** 4882 * @deprecated 4883 */ 4884 @Deprecated 4885 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4886 // reader 4887 synchronized (mPackages) { 4888 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4889 .entrySet().iterator(); 4890 final int userId = UserHandle.getCallingUserId(); 4891 while (i.hasNext()) { 4892 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4893 PackageParser.Provider p = entry.getValue(); 4894 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4895 4896 if (ps != null && p.syncable 4897 && (!mSafeMode || (p.info.applicationInfo.flags 4898 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4899 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4900 ps.readUserState(userId), userId); 4901 if (info != null) { 4902 outNames.add(entry.getKey()); 4903 outInfo.add(info); 4904 } 4905 } 4906 } 4907 } 4908 } 4909 4910 @Override 4911 public List<ProviderInfo> queryContentProviders(String processName, 4912 int uid, int flags) { 4913 ArrayList<ProviderInfo> finalList = null; 4914 // reader 4915 synchronized (mPackages) { 4916 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4917 final int userId = processName != null ? 4918 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4919 while (i.hasNext()) { 4920 final PackageParser.Provider p = i.next(); 4921 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4922 if (ps != null && p.info.authority != null 4923 && (processName == null 4924 || (p.info.processName.equals(processName) 4925 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4926 && mSettings.isEnabledLPr(p.info, flags, userId) 4927 && (!mSafeMode 4928 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4929 if (finalList == null) { 4930 finalList = new ArrayList<ProviderInfo>(3); 4931 } 4932 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4933 ps.readUserState(userId), userId); 4934 if (info != null) { 4935 finalList.add(info); 4936 } 4937 } 4938 } 4939 } 4940 4941 if (finalList != null) { 4942 Collections.sort(finalList, mProviderInitOrderSorter); 4943 } 4944 4945 return finalList; 4946 } 4947 4948 @Override 4949 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4950 int flags) { 4951 // reader 4952 synchronized (mPackages) { 4953 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4954 return PackageParser.generateInstrumentationInfo(i, flags); 4955 } 4956 } 4957 4958 @Override 4959 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4960 int flags) { 4961 ArrayList<InstrumentationInfo> finalList = 4962 new ArrayList<InstrumentationInfo>(); 4963 4964 // reader 4965 synchronized (mPackages) { 4966 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4967 while (i.hasNext()) { 4968 final PackageParser.Instrumentation p = i.next(); 4969 if (targetPackage == null 4970 || targetPackage.equals(p.info.targetPackage)) { 4971 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4972 flags); 4973 if (ii != null) { 4974 finalList.add(ii); 4975 } 4976 } 4977 } 4978 } 4979 4980 return finalList; 4981 } 4982 4983 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4984 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4985 if (overlays == null) { 4986 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4987 return; 4988 } 4989 for (PackageParser.Package opkg : overlays.values()) { 4990 // Not much to do if idmap fails: we already logged the error 4991 // and we certainly don't want to abort installation of pkg simply 4992 // because an overlay didn't fit properly. For these reasons, 4993 // ignore the return value of createIdmapForPackagePairLI. 4994 createIdmapForPackagePairLI(pkg, opkg); 4995 } 4996 } 4997 4998 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4999 PackageParser.Package opkg) { 5000 if (!opkg.mTrustedOverlay) { 5001 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5002 opkg.baseCodePath + ": overlay not trusted"); 5003 return false; 5004 } 5005 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5006 if (overlaySet == null) { 5007 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5008 opkg.baseCodePath + " but target package has no known overlays"); 5009 return false; 5010 } 5011 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5012 // TODO: generate idmap for split APKs 5013 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5014 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5015 + opkg.baseCodePath); 5016 return false; 5017 } 5018 PackageParser.Package[] overlayArray = 5019 overlaySet.values().toArray(new PackageParser.Package[0]); 5020 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5021 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5022 return p1.mOverlayPriority - p2.mOverlayPriority; 5023 } 5024 }; 5025 Arrays.sort(overlayArray, cmp); 5026 5027 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5028 int i = 0; 5029 for (PackageParser.Package p : overlayArray) { 5030 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5031 } 5032 return true; 5033 } 5034 5035 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5036 final File[] files = dir.listFiles(); 5037 if (ArrayUtils.isEmpty(files)) { 5038 Log.d(TAG, "No files in app dir " + dir); 5039 return; 5040 } 5041 5042 if (DEBUG_PACKAGE_SCANNING) { 5043 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5044 + " flags=0x" + Integer.toHexString(parseFlags)); 5045 } 5046 5047 for (File file : files) { 5048 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5049 && !PackageInstallerService.isStageName(file.getName()); 5050 if (!isPackage) { 5051 // Ignore entries which are not packages 5052 continue; 5053 } 5054 try { 5055 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5056 scanFlags, currentTime, null); 5057 } catch (PackageManagerException e) { 5058 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5059 5060 // Delete invalid userdata apps 5061 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5062 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5063 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5064 if (file.isDirectory()) { 5065 mInstaller.rmPackageDir(file.getAbsolutePath()); 5066 } else { 5067 file.delete(); 5068 } 5069 } 5070 } 5071 } 5072 } 5073 5074 private static File getSettingsProblemFile() { 5075 File dataDir = Environment.getDataDirectory(); 5076 File systemDir = new File(dataDir, "system"); 5077 File fname = new File(systemDir, "uiderrors.txt"); 5078 return fname; 5079 } 5080 5081 static void reportSettingsProblem(int priority, String msg) { 5082 logCriticalInfo(priority, msg); 5083 } 5084 5085 static void logCriticalInfo(int priority, String msg) { 5086 Slog.println(priority, TAG, msg); 5087 EventLogTags.writePmCriticalInfo(msg); 5088 try { 5089 File fname = getSettingsProblemFile(); 5090 FileOutputStream out = new FileOutputStream(fname, true); 5091 PrintWriter pw = new FastPrintWriter(out); 5092 SimpleDateFormat formatter = new SimpleDateFormat(); 5093 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5094 pw.println(dateString + ": " + msg); 5095 pw.close(); 5096 FileUtils.setPermissions( 5097 fname.toString(), 5098 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5099 -1, -1); 5100 } catch (java.io.IOException e) { 5101 } 5102 } 5103 5104 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5105 PackageParser.Package pkg, File srcFile, int parseFlags) 5106 throws PackageManagerException { 5107 if (ps != null 5108 && ps.codePath.equals(srcFile) 5109 && ps.timeStamp == srcFile.lastModified() 5110 && !isCompatSignatureUpdateNeeded(pkg) 5111 && !isRecoverSignatureUpdateNeeded(pkg)) { 5112 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5113 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5114 ArraySet<PublicKey> signingKs; 5115 synchronized (mPackages) { 5116 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5117 } 5118 if (ps.signatures.mSignatures != null 5119 && ps.signatures.mSignatures.length != 0 5120 && signingKs != null) { 5121 // Optimization: reuse the existing cached certificates 5122 // if the package appears to be unchanged. 5123 pkg.mSignatures = ps.signatures.mSignatures; 5124 pkg.mSigningKeys = signingKs; 5125 return; 5126 } 5127 5128 Slog.w(TAG, "PackageSetting for " + ps.name 5129 + " is missing signatures. Collecting certs again to recover them."); 5130 } else { 5131 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5132 } 5133 5134 try { 5135 pp.collectCertificates(pkg, parseFlags); 5136 pp.collectManifestDigest(pkg); 5137 } catch (PackageParserException e) { 5138 throw PackageManagerException.from(e); 5139 } 5140 } 5141 5142 /* 5143 * Scan a package and return the newly parsed package. 5144 * Returns null in case of errors and the error code is stored in mLastScanError 5145 */ 5146 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5147 long currentTime, UserHandle user) throws PackageManagerException { 5148 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5149 parseFlags |= mDefParseFlags; 5150 PackageParser pp = new PackageParser(); 5151 pp.setSeparateProcesses(mSeparateProcesses); 5152 pp.setOnlyCoreApps(mOnlyCore); 5153 pp.setDisplayMetrics(mMetrics); 5154 5155 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5156 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5157 } 5158 5159 final PackageParser.Package pkg; 5160 try { 5161 pkg = pp.parsePackage(scanFile, parseFlags); 5162 } catch (PackageParserException e) { 5163 throw PackageManagerException.from(e); 5164 } 5165 5166 PackageSetting ps = null; 5167 PackageSetting updatedPkg; 5168 // reader 5169 synchronized (mPackages) { 5170 // Look to see if we already know about this package. 5171 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5172 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5173 // This package has been renamed to its original name. Let's 5174 // use that. 5175 ps = mSettings.peekPackageLPr(oldName); 5176 } 5177 // If there was no original package, see one for the real package name. 5178 if (ps == null) { 5179 ps = mSettings.peekPackageLPr(pkg.packageName); 5180 } 5181 // Check to see if this package could be hiding/updating a system 5182 // package. Must look for it either under the original or real 5183 // package name depending on our state. 5184 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5185 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5186 } 5187 boolean updatedPkgBetter = false; 5188 // First check if this is a system package that may involve an update 5189 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5190 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5191 // it needs to drop FLAG_PRIVILEGED. 5192 if (locationIsPrivileged(scanFile)) { 5193 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5194 } else { 5195 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5196 } 5197 5198 if (ps != null && !ps.codePath.equals(scanFile)) { 5199 // The path has changed from what was last scanned... check the 5200 // version of the new path against what we have stored to determine 5201 // what to do. 5202 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5203 if (pkg.mVersionCode <= ps.versionCode) { 5204 // The system package has been updated and the code path does not match 5205 // Ignore entry. Skip it. 5206 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5207 + " ignored: updated version " + ps.versionCode 5208 + " better than this " + pkg.mVersionCode); 5209 if (!updatedPkg.codePath.equals(scanFile)) { 5210 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5211 + ps.name + " changing from " + updatedPkg.codePathString 5212 + " to " + scanFile); 5213 updatedPkg.codePath = scanFile; 5214 updatedPkg.codePathString = scanFile.toString(); 5215 updatedPkg.resourcePath = scanFile; 5216 updatedPkg.resourcePathString = scanFile.toString(); 5217 } 5218 updatedPkg.pkg = pkg; 5219 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5220 } else { 5221 // The current app on the system partition is better than 5222 // what we have updated to on the data partition; switch 5223 // back to the system partition version. 5224 // At this point, its safely assumed that package installation for 5225 // apps in system partition will go through. If not there won't be a working 5226 // version of the app 5227 // writer 5228 synchronized (mPackages) { 5229 // Just remove the loaded entries from package lists. 5230 mPackages.remove(ps.name); 5231 } 5232 5233 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5234 + " reverting from " + ps.codePathString 5235 + ": new version " + pkg.mVersionCode 5236 + " better than installed " + ps.versionCode); 5237 5238 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5239 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5240 synchronized (mInstallLock) { 5241 args.cleanUpResourcesLI(); 5242 } 5243 synchronized (mPackages) { 5244 mSettings.enableSystemPackageLPw(ps.name); 5245 } 5246 updatedPkgBetter = true; 5247 } 5248 } 5249 } 5250 5251 if (updatedPkg != null) { 5252 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5253 // initially 5254 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5255 5256 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5257 // flag set initially 5258 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5259 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5260 } 5261 } 5262 5263 // Verify certificates against what was last scanned 5264 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5265 5266 /* 5267 * A new system app appeared, but we already had a non-system one of the 5268 * same name installed earlier. 5269 */ 5270 boolean shouldHideSystemApp = false; 5271 if (updatedPkg == null && ps != null 5272 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5273 /* 5274 * Check to make sure the signatures match first. If they don't, 5275 * wipe the installed application and its data. 5276 */ 5277 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5278 != PackageManager.SIGNATURE_MATCH) { 5279 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5280 + " signatures don't match existing userdata copy; removing"); 5281 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5282 ps = null; 5283 } else { 5284 /* 5285 * If the newly-added system app is an older version than the 5286 * already installed version, hide it. It will be scanned later 5287 * and re-added like an update. 5288 */ 5289 if (pkg.mVersionCode <= ps.versionCode) { 5290 shouldHideSystemApp = true; 5291 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5292 + " but new version " + pkg.mVersionCode + " better than installed " 5293 + ps.versionCode + "; hiding system"); 5294 } else { 5295 /* 5296 * The newly found system app is a newer version that the 5297 * one previously installed. Simply remove the 5298 * already-installed application and replace it with our own 5299 * while keeping the application data. 5300 */ 5301 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5302 + " reverting from " + ps.codePathString + ": new version " 5303 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5304 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5305 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5306 synchronized (mInstallLock) { 5307 args.cleanUpResourcesLI(); 5308 } 5309 } 5310 } 5311 } 5312 5313 // The apk is forward locked (not public) if its code and resources 5314 // are kept in different files. (except for app in either system or 5315 // vendor path). 5316 // TODO grab this value from PackageSettings 5317 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5318 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5319 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5320 } 5321 } 5322 5323 // TODO: extend to support forward-locked splits 5324 String resourcePath = null; 5325 String baseResourcePath = null; 5326 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5327 if (ps != null && ps.resourcePathString != null) { 5328 resourcePath = ps.resourcePathString; 5329 baseResourcePath = ps.resourcePathString; 5330 } else { 5331 // Should not happen at all. Just log an error. 5332 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5333 } 5334 } else { 5335 resourcePath = pkg.codePath; 5336 baseResourcePath = pkg.baseCodePath; 5337 } 5338 5339 // Set application objects path explicitly. 5340 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5341 pkg.applicationInfo.setCodePath(pkg.codePath); 5342 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5343 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5344 pkg.applicationInfo.setResourcePath(resourcePath); 5345 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5346 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5347 5348 // Note that we invoke the following method only if we are about to unpack an application 5349 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5350 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5351 5352 /* 5353 * If the system app should be overridden by a previously installed 5354 * data, hide the system app now and let the /data/app scan pick it up 5355 * again. 5356 */ 5357 if (shouldHideSystemApp) { 5358 synchronized (mPackages) { 5359 /* 5360 * We have to grant systems permissions before we hide, because 5361 * grantPermissions will assume the package update is trying to 5362 * expand its permissions. 5363 */ 5364 grantPermissionsLPw(pkg, true, pkg.packageName); 5365 mSettings.disableSystemPackageLPw(pkg.packageName); 5366 } 5367 } 5368 5369 return scannedPkg; 5370 } 5371 5372 private static String fixProcessName(String defProcessName, 5373 String processName, int uid) { 5374 if (processName == null) { 5375 return defProcessName; 5376 } 5377 return processName; 5378 } 5379 5380 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5381 throws PackageManagerException { 5382 if (pkgSetting.signatures.mSignatures != null) { 5383 // Already existing package. Make sure signatures match 5384 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5385 == PackageManager.SIGNATURE_MATCH; 5386 if (!match) { 5387 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5388 == PackageManager.SIGNATURE_MATCH; 5389 } 5390 if (!match) { 5391 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5392 == PackageManager.SIGNATURE_MATCH; 5393 } 5394 if (!match) { 5395 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5396 + pkg.packageName + " signatures do not match the " 5397 + "previously installed version; ignoring!"); 5398 } 5399 } 5400 5401 // Check for shared user signatures 5402 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5403 // Already existing package. Make sure signatures match 5404 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5405 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5406 if (!match) { 5407 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5408 == PackageManager.SIGNATURE_MATCH; 5409 } 5410 if (!match) { 5411 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5412 == PackageManager.SIGNATURE_MATCH; 5413 } 5414 if (!match) { 5415 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5416 "Package " + pkg.packageName 5417 + " has no signatures that match those in shared user " 5418 + pkgSetting.sharedUser.name + "; ignoring!"); 5419 } 5420 } 5421 } 5422 5423 /** 5424 * Enforces that only the system UID or root's UID can call a method exposed 5425 * via Binder. 5426 * 5427 * @param message used as message if SecurityException is thrown 5428 * @throws SecurityException if the caller is not system or root 5429 */ 5430 private static final void enforceSystemOrRoot(String message) { 5431 final int uid = Binder.getCallingUid(); 5432 if (uid != Process.SYSTEM_UID && uid != 0) { 5433 throw new SecurityException(message); 5434 } 5435 } 5436 5437 @Override 5438 public void performBootDexOpt() { 5439 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5440 5441 // Before everything else, see whether we need to fstrim. 5442 try { 5443 IMountService ms = PackageHelper.getMountService(); 5444 if (ms != null) { 5445 final boolean isUpgrade = isUpgrade(); 5446 boolean doTrim = isUpgrade; 5447 if (doTrim) { 5448 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5449 } else { 5450 final long interval = android.provider.Settings.Global.getLong( 5451 mContext.getContentResolver(), 5452 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5453 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5454 if (interval > 0) { 5455 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5456 if (timeSinceLast > interval) { 5457 doTrim = true; 5458 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5459 + "; running immediately"); 5460 } 5461 } 5462 } 5463 if (doTrim) { 5464 if (!isFirstBoot()) { 5465 try { 5466 ActivityManagerNative.getDefault().showBootMessage( 5467 mContext.getResources().getString( 5468 R.string.android_upgrading_fstrim), true); 5469 } catch (RemoteException e) { 5470 } 5471 } 5472 ms.runMaintenance(); 5473 } 5474 } else { 5475 Slog.e(TAG, "Mount service unavailable!"); 5476 } 5477 } catch (RemoteException e) { 5478 // Can't happen; MountService is local 5479 } 5480 5481 final ArraySet<PackageParser.Package> pkgs; 5482 synchronized (mPackages) { 5483 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5484 } 5485 5486 if (pkgs != null) { 5487 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5488 // in case the device runs out of space. 5489 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5490 // Give priority to core apps. 5491 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5492 PackageParser.Package pkg = it.next(); 5493 if (pkg.coreApp) { 5494 if (DEBUG_DEXOPT) { 5495 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5496 } 5497 sortedPkgs.add(pkg); 5498 it.remove(); 5499 } 5500 } 5501 // Give priority to system apps that listen for pre boot complete. 5502 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5503 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5504 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5505 PackageParser.Package pkg = it.next(); 5506 if (pkgNames.contains(pkg.packageName)) { 5507 if (DEBUG_DEXOPT) { 5508 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5509 } 5510 sortedPkgs.add(pkg); 5511 it.remove(); 5512 } 5513 } 5514 // Give priority to system apps. 5515 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5516 PackageParser.Package pkg = it.next(); 5517 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5518 if (DEBUG_DEXOPT) { 5519 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5520 } 5521 sortedPkgs.add(pkg); 5522 it.remove(); 5523 } 5524 } 5525 // Give priority to updated system apps. 5526 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5527 PackageParser.Package pkg = it.next(); 5528 if (pkg.isUpdatedSystemApp()) { 5529 if (DEBUG_DEXOPT) { 5530 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5531 } 5532 sortedPkgs.add(pkg); 5533 it.remove(); 5534 } 5535 } 5536 // Give priority to apps that listen for boot complete. 5537 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5538 pkgNames = getPackageNamesForIntent(intent); 5539 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5540 PackageParser.Package pkg = it.next(); 5541 if (pkgNames.contains(pkg.packageName)) { 5542 if (DEBUG_DEXOPT) { 5543 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5544 } 5545 sortedPkgs.add(pkg); 5546 it.remove(); 5547 } 5548 } 5549 // Filter out packages that aren't recently used. 5550 filterRecentlyUsedApps(pkgs); 5551 // Add all remaining apps. 5552 for (PackageParser.Package pkg : pkgs) { 5553 if (DEBUG_DEXOPT) { 5554 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5555 } 5556 sortedPkgs.add(pkg); 5557 } 5558 5559 // If we want to be lazy, filter everything that wasn't recently used. 5560 if (mLazyDexOpt) { 5561 filterRecentlyUsedApps(sortedPkgs); 5562 } 5563 5564 int i = 0; 5565 int total = sortedPkgs.size(); 5566 File dataDir = Environment.getDataDirectory(); 5567 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5568 if (lowThreshold == 0) { 5569 throw new IllegalStateException("Invalid low memory threshold"); 5570 } 5571 for (PackageParser.Package pkg : sortedPkgs) { 5572 long usableSpace = dataDir.getUsableSpace(); 5573 if (usableSpace < lowThreshold) { 5574 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5575 break; 5576 } 5577 performBootDexOpt(pkg, ++i, total); 5578 } 5579 } 5580 } 5581 5582 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5583 // Filter out packages that aren't recently used. 5584 // 5585 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5586 // should do a full dexopt. 5587 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5588 int total = pkgs.size(); 5589 int skipped = 0; 5590 long now = System.currentTimeMillis(); 5591 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5592 PackageParser.Package pkg = i.next(); 5593 long then = pkg.mLastPackageUsageTimeInMills; 5594 if (then + mDexOptLRUThresholdInMills < now) { 5595 if (DEBUG_DEXOPT) { 5596 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5597 ((then == 0) ? "never" : new Date(then))); 5598 } 5599 i.remove(); 5600 skipped++; 5601 } 5602 } 5603 if (DEBUG_DEXOPT) { 5604 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5605 } 5606 } 5607 } 5608 5609 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5610 List<ResolveInfo> ris = null; 5611 try { 5612 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5613 intent, null, 0, UserHandle.USER_OWNER); 5614 } catch (RemoteException e) { 5615 } 5616 ArraySet<String> pkgNames = new ArraySet<String>(); 5617 if (ris != null) { 5618 for (ResolveInfo ri : ris) { 5619 pkgNames.add(ri.activityInfo.packageName); 5620 } 5621 } 5622 return pkgNames; 5623 } 5624 5625 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5626 if (DEBUG_DEXOPT) { 5627 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5628 } 5629 if (!isFirstBoot()) { 5630 try { 5631 ActivityManagerNative.getDefault().showBootMessage( 5632 mContext.getResources().getString(R.string.android_upgrading_apk, 5633 curr, total), true); 5634 } catch (RemoteException e) { 5635 } 5636 } 5637 PackageParser.Package p = pkg; 5638 synchronized (mInstallLock) { 5639 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5640 false /* force dex */, false /* defer */, true /* include dependencies */); 5641 } 5642 } 5643 5644 @Override 5645 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5646 return performDexOpt(packageName, instructionSet, false); 5647 } 5648 5649 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5650 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5651 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5652 if (!dexopt && !updateUsage) { 5653 // We aren't going to dexopt or update usage, so bail early. 5654 return false; 5655 } 5656 PackageParser.Package p; 5657 final String targetInstructionSet; 5658 synchronized (mPackages) { 5659 p = mPackages.get(packageName); 5660 if (p == null) { 5661 return false; 5662 } 5663 if (updateUsage) { 5664 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5665 } 5666 mPackageUsage.write(false); 5667 if (!dexopt) { 5668 // We aren't going to dexopt, so bail early. 5669 return false; 5670 } 5671 5672 targetInstructionSet = instructionSet != null ? instructionSet : 5673 getPrimaryInstructionSet(p.applicationInfo); 5674 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5675 return false; 5676 } 5677 } 5678 5679 synchronized (mInstallLock) { 5680 final String[] instructionSets = new String[] { targetInstructionSet }; 5681 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5682 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5683 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5684 } 5685 } 5686 5687 public ArraySet<String> getPackagesThatNeedDexOpt() { 5688 ArraySet<String> pkgs = null; 5689 synchronized (mPackages) { 5690 for (PackageParser.Package p : mPackages.values()) { 5691 if (DEBUG_DEXOPT) { 5692 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5693 } 5694 if (!p.mDexOptPerformed.isEmpty()) { 5695 continue; 5696 } 5697 if (pkgs == null) { 5698 pkgs = new ArraySet<String>(); 5699 } 5700 pkgs.add(p.packageName); 5701 } 5702 } 5703 return pkgs; 5704 } 5705 5706 public void shutdown() { 5707 mPackageUsage.write(true); 5708 } 5709 5710 @Override 5711 public void forceDexOpt(String packageName) { 5712 enforceSystemOrRoot("forceDexOpt"); 5713 5714 PackageParser.Package pkg; 5715 synchronized (mPackages) { 5716 pkg = mPackages.get(packageName); 5717 if (pkg == null) { 5718 throw new IllegalArgumentException("Missing package: " + packageName); 5719 } 5720 } 5721 5722 synchronized (mInstallLock) { 5723 final String[] instructionSets = new String[] { 5724 getPrimaryInstructionSet(pkg.applicationInfo) }; 5725 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5726 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5727 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5728 throw new IllegalStateException("Failed to dexopt: " + res); 5729 } 5730 } 5731 } 5732 5733 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5734 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5735 Slog.w(TAG, "Unable to update from " + oldPkg.name 5736 + " to " + newPkg.packageName 5737 + ": old package not in system partition"); 5738 return false; 5739 } else if (mPackages.get(oldPkg.name) != null) { 5740 Slog.w(TAG, "Unable to update from " + oldPkg.name 5741 + " to " + newPkg.packageName 5742 + ": old package still exists"); 5743 return false; 5744 } 5745 return true; 5746 } 5747 5748 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5749 int[] users = sUserManager.getUserIds(); 5750 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5751 if (res < 0) { 5752 return res; 5753 } 5754 for (int user : users) { 5755 if (user != 0) { 5756 res = mInstaller.createUserData(volumeUuid, packageName, 5757 UserHandle.getUid(user, uid), user, seinfo); 5758 if (res < 0) { 5759 return res; 5760 } 5761 } 5762 } 5763 return res; 5764 } 5765 5766 private int removeDataDirsLI(String volumeUuid, String packageName) { 5767 int[] users = sUserManager.getUserIds(); 5768 int res = 0; 5769 for (int user : users) { 5770 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5771 if (resInner < 0) { 5772 res = resInner; 5773 } 5774 } 5775 5776 return res; 5777 } 5778 5779 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5780 int[] users = sUserManager.getUserIds(); 5781 int res = 0; 5782 for (int user : users) { 5783 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5784 if (resInner < 0) { 5785 res = resInner; 5786 } 5787 } 5788 return res; 5789 } 5790 5791 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5792 PackageParser.Package changingLib) { 5793 if (file.path != null) { 5794 usesLibraryFiles.add(file.path); 5795 return; 5796 } 5797 PackageParser.Package p = mPackages.get(file.apk); 5798 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5799 // If we are doing this while in the middle of updating a library apk, 5800 // then we need to make sure to use that new apk for determining the 5801 // dependencies here. (We haven't yet finished committing the new apk 5802 // to the package manager state.) 5803 if (p == null || p.packageName.equals(changingLib.packageName)) { 5804 p = changingLib; 5805 } 5806 } 5807 if (p != null) { 5808 usesLibraryFiles.addAll(p.getAllCodePaths()); 5809 } 5810 } 5811 5812 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5813 PackageParser.Package changingLib) throws PackageManagerException { 5814 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5815 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5816 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5817 for (int i=0; i<N; i++) { 5818 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5819 if (file == null) { 5820 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5821 "Package " + pkg.packageName + " requires unavailable shared library " 5822 + pkg.usesLibraries.get(i) + "; failing!"); 5823 } 5824 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5825 } 5826 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5827 for (int i=0; i<N; i++) { 5828 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5829 if (file == null) { 5830 Slog.w(TAG, "Package " + pkg.packageName 5831 + " desires unavailable shared library " 5832 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5833 } else { 5834 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5835 } 5836 } 5837 N = usesLibraryFiles.size(); 5838 if (N > 0) { 5839 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5840 } else { 5841 pkg.usesLibraryFiles = null; 5842 } 5843 } 5844 } 5845 5846 private static boolean hasString(List<String> list, List<String> which) { 5847 if (list == null) { 5848 return false; 5849 } 5850 for (int i=list.size()-1; i>=0; i--) { 5851 for (int j=which.size()-1; j>=0; j--) { 5852 if (which.get(j).equals(list.get(i))) { 5853 return true; 5854 } 5855 } 5856 } 5857 return false; 5858 } 5859 5860 private void updateAllSharedLibrariesLPw() { 5861 for (PackageParser.Package pkg : mPackages.values()) { 5862 try { 5863 updateSharedLibrariesLPw(pkg, null); 5864 } catch (PackageManagerException e) { 5865 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5866 } 5867 } 5868 } 5869 5870 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5871 PackageParser.Package changingPkg) { 5872 ArrayList<PackageParser.Package> res = null; 5873 for (PackageParser.Package pkg : mPackages.values()) { 5874 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5875 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5876 if (res == null) { 5877 res = new ArrayList<PackageParser.Package>(); 5878 } 5879 res.add(pkg); 5880 try { 5881 updateSharedLibrariesLPw(pkg, changingPkg); 5882 } catch (PackageManagerException e) { 5883 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5884 } 5885 } 5886 } 5887 return res; 5888 } 5889 5890 /** 5891 * Derive the value of the {@code cpuAbiOverride} based on the provided 5892 * value and an optional stored value from the package settings. 5893 */ 5894 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5895 String cpuAbiOverride = null; 5896 5897 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5898 cpuAbiOverride = null; 5899 } else if (abiOverride != null) { 5900 cpuAbiOverride = abiOverride; 5901 } else if (settings != null) { 5902 cpuAbiOverride = settings.cpuAbiOverrideString; 5903 } 5904 5905 return cpuAbiOverride; 5906 } 5907 5908 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5909 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5910 boolean success = false; 5911 try { 5912 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5913 currentTime, user); 5914 success = true; 5915 return res; 5916 } finally { 5917 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5918 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5919 } 5920 } 5921 } 5922 5923 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5924 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5925 final File scanFile = new File(pkg.codePath); 5926 if (pkg.applicationInfo.getCodePath() == null || 5927 pkg.applicationInfo.getResourcePath() == null) { 5928 // Bail out. The resource and code paths haven't been set. 5929 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5930 "Code and resource paths haven't been set correctly"); 5931 } 5932 5933 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5934 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5935 } else { 5936 // Only allow system apps to be flagged as core apps. 5937 pkg.coreApp = false; 5938 } 5939 5940 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5941 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5942 } 5943 5944 if (mCustomResolverComponentName != null && 5945 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5946 setUpCustomResolverActivity(pkg); 5947 } 5948 5949 if (pkg.packageName.equals("android")) { 5950 synchronized (mPackages) { 5951 if (mAndroidApplication != null) { 5952 Slog.w(TAG, "*************************************************"); 5953 Slog.w(TAG, "Core android package being redefined. Skipping."); 5954 Slog.w(TAG, " file=" + scanFile); 5955 Slog.w(TAG, "*************************************************"); 5956 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5957 "Core android package being redefined. Skipping."); 5958 } 5959 5960 // Set up information for our fall-back user intent resolution activity. 5961 mPlatformPackage = pkg; 5962 pkg.mVersionCode = mSdkVersion; 5963 mAndroidApplication = pkg.applicationInfo; 5964 5965 if (!mResolverReplaced) { 5966 mResolveActivity.applicationInfo = mAndroidApplication; 5967 mResolveActivity.name = ResolverActivity.class.getName(); 5968 mResolveActivity.packageName = mAndroidApplication.packageName; 5969 mResolveActivity.processName = "system:ui"; 5970 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5971 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5972 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5973 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5974 mResolveActivity.exported = true; 5975 mResolveActivity.enabled = true; 5976 mResolveInfo.activityInfo = mResolveActivity; 5977 mResolveInfo.priority = 0; 5978 mResolveInfo.preferredOrder = 0; 5979 mResolveInfo.match = 0; 5980 mResolveComponentName = new ComponentName( 5981 mAndroidApplication.packageName, mResolveActivity.name); 5982 } 5983 } 5984 } 5985 5986 if (DEBUG_PACKAGE_SCANNING) { 5987 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5988 Log.d(TAG, "Scanning package " + pkg.packageName); 5989 } 5990 5991 if (mPackages.containsKey(pkg.packageName) 5992 || mSharedLibraries.containsKey(pkg.packageName)) { 5993 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5994 "Application package " + pkg.packageName 5995 + " already installed. Skipping duplicate."); 5996 } 5997 5998 // If we're only installing presumed-existing packages, require that the 5999 // scanned APK is both already known and at the path previously established 6000 // for it. Previously unknown packages we pick up normally, but if we have an 6001 // a priori expectation about this package's install presence, enforce it. 6002 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6003 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6004 if (known != null) { 6005 if (DEBUG_PACKAGE_SCANNING) { 6006 Log.d(TAG, "Examining " + pkg.codePath 6007 + " and requiring known paths " + known.codePathString 6008 + " & " + known.resourcePathString); 6009 } 6010 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6011 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6012 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6013 "Application package " + pkg.packageName 6014 + " found at " + pkg.applicationInfo.getCodePath() 6015 + " but expected at " + known.codePathString + "; ignoring."); 6016 } 6017 } 6018 } 6019 6020 // Initialize package source and resource directories 6021 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6022 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6023 6024 SharedUserSetting suid = null; 6025 PackageSetting pkgSetting = null; 6026 6027 if (!isSystemApp(pkg)) { 6028 // Only system apps can use these features. 6029 pkg.mOriginalPackages = null; 6030 pkg.mRealPackage = null; 6031 pkg.mAdoptPermissions = null; 6032 } 6033 6034 // writer 6035 synchronized (mPackages) { 6036 if (pkg.mSharedUserId != null) { 6037 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6038 if (suid == null) { 6039 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6040 "Creating application package " + pkg.packageName 6041 + " for shared user failed"); 6042 } 6043 if (DEBUG_PACKAGE_SCANNING) { 6044 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6045 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6046 + "): packages=" + suid.packages); 6047 } 6048 } 6049 6050 // Check if we are renaming from an original package name. 6051 PackageSetting origPackage = null; 6052 String realName = null; 6053 if (pkg.mOriginalPackages != null) { 6054 // This package may need to be renamed to a previously 6055 // installed name. Let's check on that... 6056 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6057 if (pkg.mOriginalPackages.contains(renamed)) { 6058 // This package had originally been installed as the 6059 // original name, and we have already taken care of 6060 // transitioning to the new one. Just update the new 6061 // one to continue using the old name. 6062 realName = pkg.mRealPackage; 6063 if (!pkg.packageName.equals(renamed)) { 6064 // Callers into this function may have already taken 6065 // care of renaming the package; only do it here if 6066 // it is not already done. 6067 pkg.setPackageName(renamed); 6068 } 6069 6070 } else { 6071 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6072 if ((origPackage = mSettings.peekPackageLPr( 6073 pkg.mOriginalPackages.get(i))) != null) { 6074 // We do have the package already installed under its 6075 // original name... should we use it? 6076 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6077 // New package is not compatible with original. 6078 origPackage = null; 6079 continue; 6080 } else if (origPackage.sharedUser != null) { 6081 // Make sure uid is compatible between packages. 6082 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6083 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6084 + " to " + pkg.packageName + ": old uid " 6085 + origPackage.sharedUser.name 6086 + " differs from " + pkg.mSharedUserId); 6087 origPackage = null; 6088 continue; 6089 } 6090 } else { 6091 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6092 + pkg.packageName + " to old name " + origPackage.name); 6093 } 6094 break; 6095 } 6096 } 6097 } 6098 } 6099 6100 if (mTransferedPackages.contains(pkg.packageName)) { 6101 Slog.w(TAG, "Package " + pkg.packageName 6102 + " was transferred to another, but its .apk remains"); 6103 } 6104 6105 // Just create the setting, don't add it yet. For already existing packages 6106 // the PkgSetting exists already and doesn't have to be created. 6107 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6108 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6109 pkg.applicationInfo.primaryCpuAbi, 6110 pkg.applicationInfo.secondaryCpuAbi, 6111 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6112 user, false); 6113 if (pkgSetting == null) { 6114 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6115 "Creating application package " + pkg.packageName + " failed"); 6116 } 6117 6118 if (pkgSetting.origPackage != null) { 6119 // If we are first transitioning from an original package, 6120 // fix up the new package's name now. We need to do this after 6121 // looking up the package under its new name, so getPackageLP 6122 // can take care of fiddling things correctly. 6123 pkg.setPackageName(origPackage.name); 6124 6125 // File a report about this. 6126 String msg = "New package " + pkgSetting.realName 6127 + " renamed to replace old package " + pkgSetting.name; 6128 reportSettingsProblem(Log.WARN, msg); 6129 6130 // Make a note of it. 6131 mTransferedPackages.add(origPackage.name); 6132 6133 // No longer need to retain this. 6134 pkgSetting.origPackage = null; 6135 } 6136 6137 if (realName != null) { 6138 // Make a note of it. 6139 mTransferedPackages.add(pkg.packageName); 6140 } 6141 6142 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6143 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6144 } 6145 6146 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6147 // Check all shared libraries and map to their actual file path. 6148 // We only do this here for apps not on a system dir, because those 6149 // are the only ones that can fail an install due to this. We 6150 // will take care of the system apps by updating all of their 6151 // library paths after the scan is done. 6152 updateSharedLibrariesLPw(pkg, null); 6153 } 6154 6155 if (mFoundPolicyFile) { 6156 SELinuxMMAC.assignSeinfoValue(pkg); 6157 } 6158 6159 pkg.applicationInfo.uid = pkgSetting.appId; 6160 pkg.mExtras = pkgSetting; 6161 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6162 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6163 // We just determined the app is signed correctly, so bring 6164 // over the latest parsed certs. 6165 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6166 } else { 6167 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6168 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6169 "Package " + pkg.packageName + " upgrade keys do not match the " 6170 + "previously installed version"); 6171 } else { 6172 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6173 String msg = "System package " + pkg.packageName 6174 + " signature changed; retaining data."; 6175 reportSettingsProblem(Log.WARN, msg); 6176 } 6177 } 6178 } else { 6179 try { 6180 verifySignaturesLP(pkgSetting, pkg); 6181 // We just determined the app is signed correctly, so bring 6182 // over the latest parsed certs. 6183 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6184 } catch (PackageManagerException e) { 6185 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6186 throw e; 6187 } 6188 // The signature has changed, but this package is in the system 6189 // image... let's recover! 6190 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6191 // However... if this package is part of a shared user, but it 6192 // doesn't match the signature of the shared user, let's fail. 6193 // What this means is that you can't change the signatures 6194 // associated with an overall shared user, which doesn't seem all 6195 // that unreasonable. 6196 if (pkgSetting.sharedUser != null) { 6197 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6198 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6199 throw new PackageManagerException( 6200 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6201 "Signature mismatch for shared user : " 6202 + pkgSetting.sharedUser); 6203 } 6204 } 6205 // File a report about this. 6206 String msg = "System package " + pkg.packageName 6207 + " signature changed; retaining data."; 6208 reportSettingsProblem(Log.WARN, msg); 6209 } 6210 } 6211 // Verify that this new package doesn't have any content providers 6212 // that conflict with existing packages. Only do this if the 6213 // package isn't already installed, since we don't want to break 6214 // things that are installed. 6215 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6216 final int N = pkg.providers.size(); 6217 int i; 6218 for (i=0; i<N; i++) { 6219 PackageParser.Provider p = pkg.providers.get(i); 6220 if (p.info.authority != null) { 6221 String names[] = p.info.authority.split(";"); 6222 for (int j = 0; j < names.length; j++) { 6223 if (mProvidersByAuthority.containsKey(names[j])) { 6224 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6225 final String otherPackageName = 6226 ((other != null && other.getComponentName() != null) ? 6227 other.getComponentName().getPackageName() : "?"); 6228 throw new PackageManagerException( 6229 INSTALL_FAILED_CONFLICTING_PROVIDER, 6230 "Can't install because provider name " + names[j] 6231 + " (in package " + pkg.applicationInfo.packageName 6232 + ") is already used by " + otherPackageName); 6233 } 6234 } 6235 } 6236 } 6237 } 6238 6239 if (pkg.mAdoptPermissions != null) { 6240 // This package wants to adopt ownership of permissions from 6241 // another package. 6242 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6243 final String origName = pkg.mAdoptPermissions.get(i); 6244 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6245 if (orig != null) { 6246 if (verifyPackageUpdateLPr(orig, pkg)) { 6247 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6248 + pkg.packageName); 6249 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6250 } 6251 } 6252 } 6253 } 6254 } 6255 6256 final String pkgName = pkg.packageName; 6257 6258 final long scanFileTime = scanFile.lastModified(); 6259 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6260 pkg.applicationInfo.processName = fixProcessName( 6261 pkg.applicationInfo.packageName, 6262 pkg.applicationInfo.processName, 6263 pkg.applicationInfo.uid); 6264 6265 File dataPath; 6266 if (mPlatformPackage == pkg) { 6267 // The system package is special. 6268 dataPath = new File(Environment.getDataDirectory(), "system"); 6269 6270 pkg.applicationInfo.dataDir = dataPath.getPath(); 6271 6272 } else { 6273 // This is a normal package, need to make its data directory. 6274 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6275 UserHandle.USER_OWNER); 6276 6277 boolean uidError = false; 6278 if (dataPath.exists()) { 6279 int currentUid = 0; 6280 try { 6281 StructStat stat = Os.stat(dataPath.getPath()); 6282 currentUid = stat.st_uid; 6283 } catch (ErrnoException e) { 6284 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6285 } 6286 6287 // If we have mismatched owners for the data path, we have a problem. 6288 if (currentUid != pkg.applicationInfo.uid) { 6289 boolean recovered = false; 6290 if (currentUid == 0) { 6291 // The directory somehow became owned by root. Wow. 6292 // This is probably because the system was stopped while 6293 // installd was in the middle of messing with its libs 6294 // directory. Ask installd to fix that. 6295 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6296 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6297 if (ret >= 0) { 6298 recovered = true; 6299 String msg = "Package " + pkg.packageName 6300 + " unexpectedly changed to uid 0; recovered to " + 6301 + pkg.applicationInfo.uid; 6302 reportSettingsProblem(Log.WARN, msg); 6303 } 6304 } 6305 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6306 || (scanFlags&SCAN_BOOTING) != 0)) { 6307 // If this is a system app, we can at least delete its 6308 // current data so the application will still work. 6309 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6310 if (ret >= 0) { 6311 // TODO: Kill the processes first 6312 // Old data gone! 6313 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6314 ? "System package " : "Third party package "; 6315 String msg = prefix + pkg.packageName 6316 + " has changed from uid: " 6317 + currentUid + " to " 6318 + pkg.applicationInfo.uid + "; old data erased"; 6319 reportSettingsProblem(Log.WARN, msg); 6320 recovered = true; 6321 6322 // And now re-install the app. 6323 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6324 pkg.applicationInfo.seinfo); 6325 if (ret == -1) { 6326 // Ack should not happen! 6327 msg = prefix + pkg.packageName 6328 + " could not have data directory re-created after delete."; 6329 reportSettingsProblem(Log.WARN, msg); 6330 throw new PackageManagerException( 6331 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6332 } 6333 } 6334 if (!recovered) { 6335 mHasSystemUidErrors = true; 6336 } 6337 } else if (!recovered) { 6338 // If we allow this install to proceed, we will be broken. 6339 // Abort, abort! 6340 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6341 "scanPackageLI"); 6342 } 6343 if (!recovered) { 6344 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6345 + pkg.applicationInfo.uid + "/fs_" 6346 + currentUid; 6347 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6348 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6349 String msg = "Package " + pkg.packageName 6350 + " has mismatched uid: " 6351 + currentUid + " on disk, " 6352 + pkg.applicationInfo.uid + " in settings"; 6353 // writer 6354 synchronized (mPackages) { 6355 mSettings.mReadMessages.append(msg); 6356 mSettings.mReadMessages.append('\n'); 6357 uidError = true; 6358 if (!pkgSetting.uidError) { 6359 reportSettingsProblem(Log.ERROR, msg); 6360 } 6361 } 6362 } 6363 } 6364 pkg.applicationInfo.dataDir = dataPath.getPath(); 6365 if (mShouldRestoreconData) { 6366 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6367 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6368 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6369 } 6370 } else { 6371 if (DEBUG_PACKAGE_SCANNING) { 6372 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6373 Log.v(TAG, "Want this data dir: " + dataPath); 6374 } 6375 //invoke installer to do the actual installation 6376 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6377 pkg.applicationInfo.seinfo); 6378 if (ret < 0) { 6379 // Error from installer 6380 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6381 "Unable to create data dirs [errorCode=" + ret + "]"); 6382 } 6383 6384 if (dataPath.exists()) { 6385 pkg.applicationInfo.dataDir = dataPath.getPath(); 6386 } else { 6387 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6388 pkg.applicationInfo.dataDir = null; 6389 } 6390 } 6391 6392 pkgSetting.uidError = uidError; 6393 } 6394 6395 final String path = scanFile.getPath(); 6396 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6397 6398 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6399 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6400 6401 // Some system apps still use directory structure for native libraries 6402 // in which case we might end up not detecting abi solely based on apk 6403 // structure. Try to detect abi based on directory structure. 6404 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6405 pkg.applicationInfo.primaryCpuAbi == null) { 6406 setBundledAppAbisAndRoots(pkg, pkgSetting); 6407 setNativeLibraryPaths(pkg); 6408 } 6409 6410 } else { 6411 if ((scanFlags & SCAN_MOVE) != 0) { 6412 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6413 // but we already have this packages package info in the PackageSetting. We just 6414 // use that and derive the native library path based on the new codepath. 6415 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6416 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6417 } 6418 6419 // Set native library paths again. For moves, the path will be updated based on the 6420 // ABIs we've determined above. For non-moves, the path will be updated based on the 6421 // ABIs we determined during compilation, but the path will depend on the final 6422 // package path (after the rename away from the stage path). 6423 setNativeLibraryPaths(pkg); 6424 } 6425 6426 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6427 final int[] userIds = sUserManager.getUserIds(); 6428 synchronized (mInstallLock) { 6429 // Create a native library symlink only if we have native libraries 6430 // and if the native libraries are 32 bit libraries. We do not provide 6431 // this symlink for 64 bit libraries. 6432 if (pkg.applicationInfo.primaryCpuAbi != null && 6433 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6434 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6435 for (int userId : userIds) { 6436 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6437 nativeLibPath, userId) < 0) { 6438 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6439 "Failed linking native library dir (user=" + userId + ")"); 6440 } 6441 } 6442 } 6443 } 6444 6445 // This is a special case for the "system" package, where the ABI is 6446 // dictated by the zygote configuration (and init.rc). We should keep track 6447 // of this ABI so that we can deal with "normal" applications that run under 6448 // the same UID correctly. 6449 if (mPlatformPackage == pkg) { 6450 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6451 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6452 } 6453 6454 // If there's a mismatch between the abi-override in the package setting 6455 // and the abiOverride specified for the install. Warn about this because we 6456 // would've already compiled the app without taking the package setting into 6457 // account. 6458 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6459 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6460 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6461 " for package: " + pkg.packageName); 6462 } 6463 } 6464 6465 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6466 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6467 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6468 6469 // Copy the derived override back to the parsed package, so that we can 6470 // update the package settings accordingly. 6471 pkg.cpuAbiOverride = cpuAbiOverride; 6472 6473 if (DEBUG_ABI_SELECTION) { 6474 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6475 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6476 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6477 } 6478 6479 // Push the derived path down into PackageSettings so we know what to 6480 // clean up at uninstall time. 6481 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6482 6483 if (DEBUG_ABI_SELECTION) { 6484 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6485 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6486 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6487 } 6488 6489 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6490 // We don't do this here during boot because we can do it all 6491 // at once after scanning all existing packages. 6492 // 6493 // We also do this *before* we perform dexopt on this package, so that 6494 // we can avoid redundant dexopts, and also to make sure we've got the 6495 // code and package path correct. 6496 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6497 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6498 } 6499 6500 if ((scanFlags & SCAN_NO_DEX) == 0) { 6501 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6502 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6503 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6504 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6505 } 6506 } 6507 if (mFactoryTest && pkg.requestedPermissions.contains( 6508 android.Manifest.permission.FACTORY_TEST)) { 6509 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6510 } 6511 6512 ArrayList<PackageParser.Package> clientLibPkgs = null; 6513 6514 // writer 6515 synchronized (mPackages) { 6516 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6517 // Only system apps can add new shared libraries. 6518 if (pkg.libraryNames != null) { 6519 for (int i=0; i<pkg.libraryNames.size(); i++) { 6520 String name = pkg.libraryNames.get(i); 6521 boolean allowed = false; 6522 if (pkg.isUpdatedSystemApp()) { 6523 // New library entries can only be added through the 6524 // system image. This is important to get rid of a lot 6525 // of nasty edge cases: for example if we allowed a non- 6526 // system update of the app to add a library, then uninstalling 6527 // the update would make the library go away, and assumptions 6528 // we made such as through app install filtering would now 6529 // have allowed apps on the device which aren't compatible 6530 // with it. Better to just have the restriction here, be 6531 // conservative, and create many fewer cases that can negatively 6532 // impact the user experience. 6533 final PackageSetting sysPs = mSettings 6534 .getDisabledSystemPkgLPr(pkg.packageName); 6535 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6536 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6537 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6538 allowed = true; 6539 allowed = true; 6540 break; 6541 } 6542 } 6543 } 6544 } else { 6545 allowed = true; 6546 } 6547 if (allowed) { 6548 if (!mSharedLibraries.containsKey(name)) { 6549 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6550 } else if (!name.equals(pkg.packageName)) { 6551 Slog.w(TAG, "Package " + pkg.packageName + " library " 6552 + name + " already exists; skipping"); 6553 } 6554 } else { 6555 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6556 + name + " that is not declared on system image; skipping"); 6557 } 6558 } 6559 if ((scanFlags&SCAN_BOOTING) == 0) { 6560 // If we are not booting, we need to update any applications 6561 // that are clients of our shared library. If we are booting, 6562 // this will all be done once the scan is complete. 6563 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6564 } 6565 } 6566 } 6567 } 6568 6569 // We also need to dexopt any apps that are dependent on this library. Note that 6570 // if these fail, we should abort the install since installing the library will 6571 // result in some apps being broken. 6572 if (clientLibPkgs != null) { 6573 if ((scanFlags & SCAN_NO_DEX) == 0) { 6574 for (int i = 0; i < clientLibPkgs.size(); i++) { 6575 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6576 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6577 null /* instruction sets */, forceDex, 6578 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6579 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6580 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6581 "scanPackageLI failed to dexopt clientLibPkgs"); 6582 } 6583 } 6584 } 6585 } 6586 6587 // Also need to kill any apps that are dependent on the library. 6588 if (clientLibPkgs != null) { 6589 for (int i=0; i<clientLibPkgs.size(); i++) { 6590 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6591 killApplication(clientPkg.applicationInfo.packageName, 6592 clientPkg.applicationInfo.uid, "update lib"); 6593 } 6594 } 6595 6596 // Make sure we're not adding any bogus keyset info 6597 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6598 ksms.assertScannedPackageValid(pkg); 6599 6600 // writer 6601 synchronized (mPackages) { 6602 // We don't expect installation to fail beyond this point 6603 6604 // Add the new setting to mSettings 6605 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6606 // Add the new setting to mPackages 6607 mPackages.put(pkg.applicationInfo.packageName, pkg); 6608 // Make sure we don't accidentally delete its data. 6609 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6610 while (iter.hasNext()) { 6611 PackageCleanItem item = iter.next(); 6612 if (pkgName.equals(item.packageName)) { 6613 iter.remove(); 6614 } 6615 } 6616 6617 // Take care of first install / last update times. 6618 if (currentTime != 0) { 6619 if (pkgSetting.firstInstallTime == 0) { 6620 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6621 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6622 pkgSetting.lastUpdateTime = currentTime; 6623 } 6624 } else if (pkgSetting.firstInstallTime == 0) { 6625 // We need *something*. Take time time stamp of the file. 6626 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6627 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6628 if (scanFileTime != pkgSetting.timeStamp) { 6629 // A package on the system image has changed; consider this 6630 // to be an update. 6631 pkgSetting.lastUpdateTime = scanFileTime; 6632 } 6633 } 6634 6635 // Add the package's KeySets to the global KeySetManagerService 6636 ksms.addScannedPackageLPw(pkg); 6637 6638 int N = pkg.providers.size(); 6639 StringBuilder r = null; 6640 int i; 6641 for (i=0; i<N; i++) { 6642 PackageParser.Provider p = pkg.providers.get(i); 6643 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6644 p.info.processName, pkg.applicationInfo.uid); 6645 mProviders.addProvider(p); 6646 p.syncable = p.info.isSyncable; 6647 if (p.info.authority != null) { 6648 String names[] = p.info.authority.split(";"); 6649 p.info.authority = null; 6650 for (int j = 0; j < names.length; j++) { 6651 if (j == 1 && p.syncable) { 6652 // We only want the first authority for a provider to possibly be 6653 // syncable, so if we already added this provider using a different 6654 // authority clear the syncable flag. We copy the provider before 6655 // changing it because the mProviders object contains a reference 6656 // to a provider that we don't want to change. 6657 // Only do this for the second authority since the resulting provider 6658 // object can be the same for all future authorities for this provider. 6659 p = new PackageParser.Provider(p); 6660 p.syncable = false; 6661 } 6662 if (!mProvidersByAuthority.containsKey(names[j])) { 6663 mProvidersByAuthority.put(names[j], p); 6664 if (p.info.authority == null) { 6665 p.info.authority = names[j]; 6666 } else { 6667 p.info.authority = p.info.authority + ";" + names[j]; 6668 } 6669 if (DEBUG_PACKAGE_SCANNING) { 6670 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6671 Log.d(TAG, "Registered content provider: " + names[j] 6672 + ", className = " + p.info.name + ", isSyncable = " 6673 + p.info.isSyncable); 6674 } 6675 } else { 6676 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6677 Slog.w(TAG, "Skipping provider name " + names[j] + 6678 " (in package " + pkg.applicationInfo.packageName + 6679 "): name already used by " 6680 + ((other != null && other.getComponentName() != null) 6681 ? other.getComponentName().getPackageName() : "?")); 6682 } 6683 } 6684 } 6685 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6686 if (r == null) { 6687 r = new StringBuilder(256); 6688 } else { 6689 r.append(' '); 6690 } 6691 r.append(p.info.name); 6692 } 6693 } 6694 if (r != null) { 6695 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6696 } 6697 6698 N = pkg.services.size(); 6699 r = null; 6700 for (i=0; i<N; i++) { 6701 PackageParser.Service s = pkg.services.get(i); 6702 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6703 s.info.processName, pkg.applicationInfo.uid); 6704 mServices.addService(s); 6705 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6706 if (r == null) { 6707 r = new StringBuilder(256); 6708 } else { 6709 r.append(' '); 6710 } 6711 r.append(s.info.name); 6712 } 6713 } 6714 if (r != null) { 6715 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6716 } 6717 6718 N = pkg.receivers.size(); 6719 r = null; 6720 for (i=0; i<N; i++) { 6721 PackageParser.Activity a = pkg.receivers.get(i); 6722 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6723 a.info.processName, pkg.applicationInfo.uid); 6724 mReceivers.addActivity(a, "receiver"); 6725 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6726 if (r == null) { 6727 r = new StringBuilder(256); 6728 } else { 6729 r.append(' '); 6730 } 6731 r.append(a.info.name); 6732 } 6733 } 6734 if (r != null) { 6735 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6736 } 6737 6738 N = pkg.activities.size(); 6739 r = null; 6740 for (i=0; i<N; i++) { 6741 PackageParser.Activity a = pkg.activities.get(i); 6742 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6743 a.info.processName, pkg.applicationInfo.uid); 6744 mActivities.addActivity(a, "activity"); 6745 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6746 if (r == null) { 6747 r = new StringBuilder(256); 6748 } else { 6749 r.append(' '); 6750 } 6751 r.append(a.info.name); 6752 } 6753 } 6754 if (r != null) { 6755 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6756 } 6757 6758 N = pkg.permissionGroups.size(); 6759 r = null; 6760 for (i=0; i<N; i++) { 6761 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6762 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6763 if (cur == null) { 6764 mPermissionGroups.put(pg.info.name, pg); 6765 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6766 if (r == null) { 6767 r = new StringBuilder(256); 6768 } else { 6769 r.append(' '); 6770 } 6771 r.append(pg.info.name); 6772 } 6773 } else { 6774 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6775 + pg.info.packageName + " ignored: original from " 6776 + cur.info.packageName); 6777 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6778 if (r == null) { 6779 r = new StringBuilder(256); 6780 } else { 6781 r.append(' '); 6782 } 6783 r.append("DUP:"); 6784 r.append(pg.info.name); 6785 } 6786 } 6787 } 6788 if (r != null) { 6789 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6790 } 6791 6792 N = pkg.permissions.size(); 6793 r = null; 6794 for (i=0; i<N; i++) { 6795 PackageParser.Permission p = pkg.permissions.get(i); 6796 6797 // Now that permission groups have a special meaning, we ignore permission 6798 // groups for legacy apps to prevent unexpected behavior. In particular, 6799 // permissions for one app being granted to someone just becuase they happen 6800 // to be in a group defined by another app (before this had no implications). 6801 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6802 p.group = mPermissionGroups.get(p.info.group); 6803 // Warn for a permission in an unknown group. 6804 if (p.info.group != null && p.group == null) { 6805 Slog.w(TAG, "Permission " + p.info.name + " from package " 6806 + p.info.packageName + " in an unknown group " + p.info.group); 6807 } 6808 } 6809 6810 ArrayMap<String, BasePermission> permissionMap = 6811 p.tree ? mSettings.mPermissionTrees 6812 : mSettings.mPermissions; 6813 BasePermission bp = permissionMap.get(p.info.name); 6814 6815 // Allow system apps to redefine non-system permissions 6816 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6817 final boolean currentOwnerIsSystem = (bp.perm != null 6818 && isSystemApp(bp.perm.owner)); 6819 if (isSystemApp(p.owner)) { 6820 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6821 // It's a built-in permission and no owner, take ownership now 6822 bp.packageSetting = pkgSetting; 6823 bp.perm = p; 6824 bp.uid = pkg.applicationInfo.uid; 6825 bp.sourcePackage = p.info.packageName; 6826 } else if (!currentOwnerIsSystem) { 6827 String msg = "New decl " + p.owner + " of permission " 6828 + p.info.name + " is system; overriding " + bp.sourcePackage; 6829 reportSettingsProblem(Log.WARN, msg); 6830 bp = null; 6831 } 6832 } 6833 } 6834 6835 if (bp == null) { 6836 bp = new BasePermission(p.info.name, p.info.packageName, 6837 BasePermission.TYPE_NORMAL); 6838 permissionMap.put(p.info.name, bp); 6839 } 6840 6841 if (bp.perm == null) { 6842 if (bp.sourcePackage == null 6843 || bp.sourcePackage.equals(p.info.packageName)) { 6844 BasePermission tree = findPermissionTreeLP(p.info.name); 6845 if (tree == null 6846 || tree.sourcePackage.equals(p.info.packageName)) { 6847 bp.packageSetting = pkgSetting; 6848 bp.perm = p; 6849 bp.uid = pkg.applicationInfo.uid; 6850 bp.sourcePackage = p.info.packageName; 6851 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6852 if (r == null) { 6853 r = new StringBuilder(256); 6854 } else { 6855 r.append(' '); 6856 } 6857 r.append(p.info.name); 6858 } 6859 } else { 6860 Slog.w(TAG, "Permission " + p.info.name + " from package " 6861 + p.info.packageName + " ignored: base tree " 6862 + tree.name + " is from package " 6863 + tree.sourcePackage); 6864 } 6865 } else { 6866 Slog.w(TAG, "Permission " + p.info.name + " from package " 6867 + p.info.packageName + " ignored: original from " 6868 + bp.sourcePackage); 6869 } 6870 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6871 if (r == null) { 6872 r = new StringBuilder(256); 6873 } else { 6874 r.append(' '); 6875 } 6876 r.append("DUP:"); 6877 r.append(p.info.name); 6878 } 6879 if (bp.perm == p) { 6880 bp.protectionLevel = p.info.protectionLevel; 6881 } 6882 } 6883 6884 if (r != null) { 6885 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6886 } 6887 6888 N = pkg.instrumentation.size(); 6889 r = null; 6890 for (i=0; i<N; i++) { 6891 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6892 a.info.packageName = pkg.applicationInfo.packageName; 6893 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6894 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6895 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6896 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6897 a.info.dataDir = pkg.applicationInfo.dataDir; 6898 6899 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6900 // need other information about the application, like the ABI and what not ? 6901 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6902 mInstrumentation.put(a.getComponentName(), a); 6903 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6904 if (r == null) { 6905 r = new StringBuilder(256); 6906 } else { 6907 r.append(' '); 6908 } 6909 r.append(a.info.name); 6910 } 6911 } 6912 if (r != null) { 6913 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6914 } 6915 6916 if (pkg.protectedBroadcasts != null) { 6917 N = pkg.protectedBroadcasts.size(); 6918 for (i=0; i<N; i++) { 6919 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6920 } 6921 } 6922 6923 pkgSetting.setTimeStamp(scanFileTime); 6924 6925 // Create idmap files for pairs of (packages, overlay packages). 6926 // Note: "android", ie framework-res.apk, is handled by native layers. 6927 if (pkg.mOverlayTarget != null) { 6928 // This is an overlay package. 6929 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6930 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6931 mOverlays.put(pkg.mOverlayTarget, 6932 new ArrayMap<String, PackageParser.Package>()); 6933 } 6934 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6935 map.put(pkg.packageName, pkg); 6936 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6937 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6938 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6939 "scanPackageLI failed to createIdmap"); 6940 } 6941 } 6942 } else if (mOverlays.containsKey(pkg.packageName) && 6943 !pkg.packageName.equals("android")) { 6944 // This is a regular package, with one or more known overlay packages. 6945 createIdmapsForPackageLI(pkg); 6946 } 6947 } 6948 6949 return pkg; 6950 } 6951 6952 /** 6953 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6954 * is derived purely on the basis of the contents of {@code scanFile} and 6955 * {@code cpuAbiOverride}. 6956 * 6957 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6958 */ 6959 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6960 String cpuAbiOverride, boolean extractLibs) 6961 throws PackageManagerException { 6962 // TODO: We can probably be smarter about this stuff. For installed apps, 6963 // we can calculate this information at install time once and for all. For 6964 // system apps, we can probably assume that this information doesn't change 6965 // after the first boot scan. As things stand, we do lots of unnecessary work. 6966 6967 // Give ourselves some initial paths; we'll come back for another 6968 // pass once we've determined ABI below. 6969 setNativeLibraryPaths(pkg); 6970 6971 // We would never need to extract libs for forward-locked and external packages, 6972 // since the container service will do it for us. We shouldn't attempt to 6973 // extract libs from system app when it was not updated. 6974 if (pkg.isForwardLocked() || isExternal(pkg) || 6975 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 6976 extractLibs = false; 6977 } 6978 6979 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6980 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6981 6982 NativeLibraryHelper.Handle handle = null; 6983 try { 6984 handle = NativeLibraryHelper.Handle.create(scanFile); 6985 // TODO(multiArch): This can be null for apps that didn't go through the 6986 // usual installation process. We can calculate it again, like we 6987 // do during install time. 6988 // 6989 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6990 // unnecessary. 6991 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6992 6993 // Null out the abis so that they can be recalculated. 6994 pkg.applicationInfo.primaryCpuAbi = null; 6995 pkg.applicationInfo.secondaryCpuAbi = null; 6996 if (isMultiArch(pkg.applicationInfo)) { 6997 // Warn if we've set an abiOverride for multi-lib packages.. 6998 // By definition, we need to copy both 32 and 64 bit libraries for 6999 // such packages. 7000 if (pkg.cpuAbiOverride != null 7001 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7002 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7003 } 7004 7005 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7006 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7007 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7008 if (extractLibs) { 7009 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7010 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7011 useIsaSpecificSubdirs); 7012 } else { 7013 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7014 } 7015 } 7016 7017 maybeThrowExceptionForMultiArchCopy( 7018 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7019 7020 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7021 if (extractLibs) { 7022 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7023 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7024 useIsaSpecificSubdirs); 7025 } else { 7026 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7027 } 7028 } 7029 7030 maybeThrowExceptionForMultiArchCopy( 7031 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7032 7033 if (abi64 >= 0) { 7034 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7035 } 7036 7037 if (abi32 >= 0) { 7038 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7039 if (abi64 >= 0) { 7040 pkg.applicationInfo.secondaryCpuAbi = abi; 7041 } else { 7042 pkg.applicationInfo.primaryCpuAbi = abi; 7043 } 7044 } 7045 } else { 7046 String[] abiList = (cpuAbiOverride != null) ? 7047 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7048 7049 // Enable gross and lame hacks for apps that are built with old 7050 // SDK tools. We must scan their APKs for renderscript bitcode and 7051 // not launch them if it's present. Don't bother checking on devices 7052 // that don't have 64 bit support. 7053 boolean needsRenderScriptOverride = false; 7054 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7055 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7056 abiList = Build.SUPPORTED_32_BIT_ABIS; 7057 needsRenderScriptOverride = true; 7058 } 7059 7060 final int copyRet; 7061 if (extractLibs) { 7062 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7063 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7064 } else { 7065 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7066 } 7067 7068 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7069 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7070 "Error unpackaging native libs for app, errorCode=" + copyRet); 7071 } 7072 7073 if (copyRet >= 0) { 7074 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7075 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7076 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7077 } else if (needsRenderScriptOverride) { 7078 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7079 } 7080 } 7081 } catch (IOException ioe) { 7082 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7083 } finally { 7084 IoUtils.closeQuietly(handle); 7085 } 7086 7087 // Now that we've calculated the ABIs and determined if it's an internal app, 7088 // we will go ahead and populate the nativeLibraryPath. 7089 setNativeLibraryPaths(pkg); 7090 } 7091 7092 /** 7093 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7094 * i.e, so that all packages can be run inside a single process if required. 7095 * 7096 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7097 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7098 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7099 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7100 * updating a package that belongs to a shared user. 7101 * 7102 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7103 * adds unnecessary complexity. 7104 */ 7105 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7106 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7107 String requiredInstructionSet = null; 7108 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7109 requiredInstructionSet = VMRuntime.getInstructionSet( 7110 scannedPackage.applicationInfo.primaryCpuAbi); 7111 } 7112 7113 PackageSetting requirer = null; 7114 for (PackageSetting ps : packagesForUser) { 7115 // If packagesForUser contains scannedPackage, we skip it. This will happen 7116 // when scannedPackage is an update of an existing package. Without this check, 7117 // we will never be able to change the ABI of any package belonging to a shared 7118 // user, even if it's compatible with other packages. 7119 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7120 if (ps.primaryCpuAbiString == null) { 7121 continue; 7122 } 7123 7124 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7125 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7126 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7127 // this but there's not much we can do. 7128 String errorMessage = "Instruction set mismatch, " 7129 + ((requirer == null) ? "[caller]" : requirer) 7130 + " requires " + requiredInstructionSet + " whereas " + ps 7131 + " requires " + instructionSet; 7132 Slog.w(TAG, errorMessage); 7133 } 7134 7135 if (requiredInstructionSet == null) { 7136 requiredInstructionSet = instructionSet; 7137 requirer = ps; 7138 } 7139 } 7140 } 7141 7142 if (requiredInstructionSet != null) { 7143 String adjustedAbi; 7144 if (requirer != null) { 7145 // requirer != null implies that either scannedPackage was null or that scannedPackage 7146 // did not require an ABI, in which case we have to adjust scannedPackage to match 7147 // the ABI of the set (which is the same as requirer's ABI) 7148 adjustedAbi = requirer.primaryCpuAbiString; 7149 if (scannedPackage != null) { 7150 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7151 } 7152 } else { 7153 // requirer == null implies that we're updating all ABIs in the set to 7154 // match scannedPackage. 7155 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7156 } 7157 7158 for (PackageSetting ps : packagesForUser) { 7159 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7160 if (ps.primaryCpuAbiString != null) { 7161 continue; 7162 } 7163 7164 ps.primaryCpuAbiString = adjustedAbi; 7165 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7166 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7167 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7168 7169 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7170 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7171 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7172 ps.primaryCpuAbiString = null; 7173 ps.pkg.applicationInfo.primaryCpuAbi = null; 7174 return; 7175 } else { 7176 mInstaller.rmdex(ps.codePathString, 7177 getDexCodeInstructionSet(getPreferredInstructionSet())); 7178 } 7179 } 7180 } 7181 } 7182 } 7183 } 7184 7185 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7186 synchronized (mPackages) { 7187 mResolverReplaced = true; 7188 // Set up information for custom user intent resolution activity. 7189 mResolveActivity.applicationInfo = pkg.applicationInfo; 7190 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7191 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7192 mResolveActivity.processName = pkg.applicationInfo.packageName; 7193 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7194 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7195 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7196 mResolveActivity.theme = 0; 7197 mResolveActivity.exported = true; 7198 mResolveActivity.enabled = true; 7199 mResolveInfo.activityInfo = mResolveActivity; 7200 mResolveInfo.priority = 0; 7201 mResolveInfo.preferredOrder = 0; 7202 mResolveInfo.match = 0; 7203 mResolveComponentName = mCustomResolverComponentName; 7204 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7205 mResolveComponentName); 7206 } 7207 } 7208 7209 private static String calculateBundledApkRoot(final String codePathString) { 7210 final File codePath = new File(codePathString); 7211 final File codeRoot; 7212 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7213 codeRoot = Environment.getRootDirectory(); 7214 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7215 codeRoot = Environment.getOemDirectory(); 7216 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7217 codeRoot = Environment.getVendorDirectory(); 7218 } else { 7219 // Unrecognized code path; take its top real segment as the apk root: 7220 // e.g. /something/app/blah.apk => /something 7221 try { 7222 File f = codePath.getCanonicalFile(); 7223 File parent = f.getParentFile(); // non-null because codePath is a file 7224 File tmp; 7225 while ((tmp = parent.getParentFile()) != null) { 7226 f = parent; 7227 parent = tmp; 7228 } 7229 codeRoot = f; 7230 Slog.w(TAG, "Unrecognized code path " 7231 + codePath + " - using " + codeRoot); 7232 } catch (IOException e) { 7233 // Can't canonicalize the code path -- shenanigans? 7234 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7235 return Environment.getRootDirectory().getPath(); 7236 } 7237 } 7238 return codeRoot.getPath(); 7239 } 7240 7241 /** 7242 * Derive and set the location of native libraries for the given package, 7243 * which varies depending on where and how the package was installed. 7244 */ 7245 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7246 final ApplicationInfo info = pkg.applicationInfo; 7247 final String codePath = pkg.codePath; 7248 final File codeFile = new File(codePath); 7249 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7250 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7251 7252 info.nativeLibraryRootDir = null; 7253 info.nativeLibraryRootRequiresIsa = false; 7254 info.nativeLibraryDir = null; 7255 info.secondaryNativeLibraryDir = null; 7256 7257 if (isApkFile(codeFile)) { 7258 // Monolithic install 7259 if (bundledApp) { 7260 // If "/system/lib64/apkname" exists, assume that is the per-package 7261 // native library directory to use; otherwise use "/system/lib/apkname". 7262 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7263 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7264 getPrimaryInstructionSet(info)); 7265 7266 // This is a bundled system app so choose the path based on the ABI. 7267 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7268 // is just the default path. 7269 final String apkName = deriveCodePathName(codePath); 7270 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7271 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7272 apkName).getAbsolutePath(); 7273 7274 if (info.secondaryCpuAbi != null) { 7275 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7276 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7277 secondaryLibDir, apkName).getAbsolutePath(); 7278 } 7279 } else if (asecApp) { 7280 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7281 .getAbsolutePath(); 7282 } else { 7283 final String apkName = deriveCodePathName(codePath); 7284 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7285 .getAbsolutePath(); 7286 } 7287 7288 info.nativeLibraryRootRequiresIsa = false; 7289 info.nativeLibraryDir = info.nativeLibraryRootDir; 7290 } else { 7291 // Cluster install 7292 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7293 info.nativeLibraryRootRequiresIsa = true; 7294 7295 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7296 getPrimaryInstructionSet(info)).getAbsolutePath(); 7297 7298 if (info.secondaryCpuAbi != null) { 7299 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7300 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7301 } 7302 } 7303 } 7304 7305 /** 7306 * Calculate the abis and roots for a bundled app. These can uniquely 7307 * be determined from the contents of the system partition, i.e whether 7308 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7309 * of this information, and instead assume that the system was built 7310 * sensibly. 7311 */ 7312 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7313 PackageSetting pkgSetting) { 7314 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7315 7316 // If "/system/lib64/apkname" exists, assume that is the per-package 7317 // native library directory to use; otherwise use "/system/lib/apkname". 7318 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7319 setBundledAppAbi(pkg, apkRoot, apkName); 7320 // pkgSetting might be null during rescan following uninstall of updates 7321 // to a bundled app, so accommodate that possibility. The settings in 7322 // that case will be established later from the parsed package. 7323 // 7324 // If the settings aren't null, sync them up with what we've just derived. 7325 // note that apkRoot isn't stored in the package settings. 7326 if (pkgSetting != null) { 7327 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7328 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7329 } 7330 } 7331 7332 /** 7333 * Deduces the ABI of a bundled app and sets the relevant fields on the 7334 * parsed pkg object. 7335 * 7336 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7337 * under which system libraries are installed. 7338 * @param apkName the name of the installed package. 7339 */ 7340 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7341 final File codeFile = new File(pkg.codePath); 7342 7343 final boolean has64BitLibs; 7344 final boolean has32BitLibs; 7345 if (isApkFile(codeFile)) { 7346 // Monolithic install 7347 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7348 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7349 } else { 7350 // Cluster install 7351 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7352 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7353 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7354 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7355 has64BitLibs = (new File(rootDir, isa)).exists(); 7356 } else { 7357 has64BitLibs = false; 7358 } 7359 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7360 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7361 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7362 has32BitLibs = (new File(rootDir, isa)).exists(); 7363 } else { 7364 has32BitLibs = false; 7365 } 7366 } 7367 7368 if (has64BitLibs && !has32BitLibs) { 7369 // The package has 64 bit libs, but not 32 bit libs. Its primary 7370 // ABI should be 64 bit. We can safely assume here that the bundled 7371 // native libraries correspond to the most preferred ABI in the list. 7372 7373 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7374 pkg.applicationInfo.secondaryCpuAbi = null; 7375 } else if (has32BitLibs && !has64BitLibs) { 7376 // The package has 32 bit libs but not 64 bit libs. Its primary 7377 // ABI should be 32 bit. 7378 7379 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7380 pkg.applicationInfo.secondaryCpuAbi = null; 7381 } else if (has32BitLibs && has64BitLibs) { 7382 // The application has both 64 and 32 bit bundled libraries. We check 7383 // here that the app declares multiArch support, and warn if it doesn't. 7384 // 7385 // We will be lenient here and record both ABIs. The primary will be the 7386 // ABI that's higher on the list, i.e, a device that's configured to prefer 7387 // 64 bit apps will see a 64 bit primary ABI, 7388 7389 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7390 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7391 } 7392 7393 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7394 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7395 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7396 } else { 7397 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7398 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7399 } 7400 } else { 7401 pkg.applicationInfo.primaryCpuAbi = null; 7402 pkg.applicationInfo.secondaryCpuAbi = null; 7403 } 7404 } 7405 7406 private void killApplication(String pkgName, int appId, String reason) { 7407 // Request the ActivityManager to kill the process(only for existing packages) 7408 // so that we do not end up in a confused state while the user is still using the older 7409 // version of the application while the new one gets installed. 7410 IActivityManager am = ActivityManagerNative.getDefault(); 7411 if (am != null) { 7412 try { 7413 am.killApplicationWithAppId(pkgName, appId, reason); 7414 } catch (RemoteException e) { 7415 } 7416 } 7417 } 7418 7419 void removePackageLI(PackageSetting ps, boolean chatty) { 7420 if (DEBUG_INSTALL) { 7421 if (chatty) 7422 Log.d(TAG, "Removing package " + ps.name); 7423 } 7424 7425 // writer 7426 synchronized (mPackages) { 7427 mPackages.remove(ps.name); 7428 final PackageParser.Package pkg = ps.pkg; 7429 if (pkg != null) { 7430 cleanPackageDataStructuresLILPw(pkg, chatty); 7431 } 7432 } 7433 } 7434 7435 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7436 if (DEBUG_INSTALL) { 7437 if (chatty) 7438 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7439 } 7440 7441 // writer 7442 synchronized (mPackages) { 7443 mPackages.remove(pkg.applicationInfo.packageName); 7444 cleanPackageDataStructuresLILPw(pkg, chatty); 7445 } 7446 } 7447 7448 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7449 int N = pkg.providers.size(); 7450 StringBuilder r = null; 7451 int i; 7452 for (i=0; i<N; i++) { 7453 PackageParser.Provider p = pkg.providers.get(i); 7454 mProviders.removeProvider(p); 7455 if (p.info.authority == null) { 7456 7457 /* There was another ContentProvider with this authority when 7458 * this app was installed so this authority is null, 7459 * Ignore it as we don't have to unregister the provider. 7460 */ 7461 continue; 7462 } 7463 String names[] = p.info.authority.split(";"); 7464 for (int j = 0; j < names.length; j++) { 7465 if (mProvidersByAuthority.get(names[j]) == p) { 7466 mProvidersByAuthority.remove(names[j]); 7467 if (DEBUG_REMOVE) { 7468 if (chatty) 7469 Log.d(TAG, "Unregistered content provider: " + names[j] 7470 + ", className = " + p.info.name + ", isSyncable = " 7471 + p.info.isSyncable); 7472 } 7473 } 7474 } 7475 if (DEBUG_REMOVE && chatty) { 7476 if (r == null) { 7477 r = new StringBuilder(256); 7478 } else { 7479 r.append(' '); 7480 } 7481 r.append(p.info.name); 7482 } 7483 } 7484 if (r != null) { 7485 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7486 } 7487 7488 N = pkg.services.size(); 7489 r = null; 7490 for (i=0; i<N; i++) { 7491 PackageParser.Service s = pkg.services.get(i); 7492 mServices.removeService(s); 7493 if (chatty) { 7494 if (r == null) { 7495 r = new StringBuilder(256); 7496 } else { 7497 r.append(' '); 7498 } 7499 r.append(s.info.name); 7500 } 7501 } 7502 if (r != null) { 7503 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7504 } 7505 7506 N = pkg.receivers.size(); 7507 r = null; 7508 for (i=0; i<N; i++) { 7509 PackageParser.Activity a = pkg.receivers.get(i); 7510 mReceivers.removeActivity(a, "receiver"); 7511 if (DEBUG_REMOVE && chatty) { 7512 if (r == null) { 7513 r = new StringBuilder(256); 7514 } else { 7515 r.append(' '); 7516 } 7517 r.append(a.info.name); 7518 } 7519 } 7520 if (r != null) { 7521 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7522 } 7523 7524 N = pkg.activities.size(); 7525 r = null; 7526 for (i=0; i<N; i++) { 7527 PackageParser.Activity a = pkg.activities.get(i); 7528 mActivities.removeActivity(a, "activity"); 7529 if (DEBUG_REMOVE && chatty) { 7530 if (r == null) { 7531 r = new StringBuilder(256); 7532 } else { 7533 r.append(' '); 7534 } 7535 r.append(a.info.name); 7536 } 7537 } 7538 if (r != null) { 7539 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7540 } 7541 7542 N = pkg.permissions.size(); 7543 r = null; 7544 for (i=0; i<N; i++) { 7545 PackageParser.Permission p = pkg.permissions.get(i); 7546 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7547 if (bp == null) { 7548 bp = mSettings.mPermissionTrees.get(p.info.name); 7549 } 7550 if (bp != null && bp.perm == p) { 7551 bp.perm = null; 7552 if (DEBUG_REMOVE && chatty) { 7553 if (r == null) { 7554 r = new StringBuilder(256); 7555 } else { 7556 r.append(' '); 7557 } 7558 r.append(p.info.name); 7559 } 7560 } 7561 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7562 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7563 if (appOpPerms != null) { 7564 appOpPerms.remove(pkg.packageName); 7565 } 7566 } 7567 } 7568 if (r != null) { 7569 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7570 } 7571 7572 N = pkg.requestedPermissions.size(); 7573 r = null; 7574 for (i=0; i<N; i++) { 7575 String perm = pkg.requestedPermissions.get(i); 7576 BasePermission bp = mSettings.mPermissions.get(perm); 7577 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7578 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7579 if (appOpPerms != null) { 7580 appOpPerms.remove(pkg.packageName); 7581 if (appOpPerms.isEmpty()) { 7582 mAppOpPermissionPackages.remove(perm); 7583 } 7584 } 7585 } 7586 } 7587 if (r != null) { 7588 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7589 } 7590 7591 N = pkg.instrumentation.size(); 7592 r = null; 7593 for (i=0; i<N; i++) { 7594 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7595 mInstrumentation.remove(a.getComponentName()); 7596 if (DEBUG_REMOVE && chatty) { 7597 if (r == null) { 7598 r = new StringBuilder(256); 7599 } else { 7600 r.append(' '); 7601 } 7602 r.append(a.info.name); 7603 } 7604 } 7605 if (r != null) { 7606 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7607 } 7608 7609 r = null; 7610 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7611 // Only system apps can hold shared libraries. 7612 if (pkg.libraryNames != null) { 7613 for (i=0; i<pkg.libraryNames.size(); i++) { 7614 String name = pkg.libraryNames.get(i); 7615 SharedLibraryEntry cur = mSharedLibraries.get(name); 7616 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7617 mSharedLibraries.remove(name); 7618 if (DEBUG_REMOVE && chatty) { 7619 if (r == null) { 7620 r = new StringBuilder(256); 7621 } else { 7622 r.append(' '); 7623 } 7624 r.append(name); 7625 } 7626 } 7627 } 7628 } 7629 } 7630 if (r != null) { 7631 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7632 } 7633 } 7634 7635 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7636 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7637 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7638 return true; 7639 } 7640 } 7641 return false; 7642 } 7643 7644 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7645 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7646 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7647 7648 private void updatePermissionsLPw(String changingPkg, 7649 PackageParser.Package pkgInfo, int flags) { 7650 // Make sure there are no dangling permission trees. 7651 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7652 while (it.hasNext()) { 7653 final BasePermission bp = it.next(); 7654 if (bp.packageSetting == null) { 7655 // We may not yet have parsed the package, so just see if 7656 // we still know about its settings. 7657 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7658 } 7659 if (bp.packageSetting == null) { 7660 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7661 + " from package " + bp.sourcePackage); 7662 it.remove(); 7663 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7664 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7665 Slog.i(TAG, "Removing old permission tree: " + bp.name 7666 + " from package " + bp.sourcePackage); 7667 flags |= UPDATE_PERMISSIONS_ALL; 7668 it.remove(); 7669 } 7670 } 7671 } 7672 7673 // Make sure all dynamic permissions have been assigned to a package, 7674 // and make sure there are no dangling permissions. 7675 it = mSettings.mPermissions.values().iterator(); 7676 while (it.hasNext()) { 7677 final BasePermission bp = it.next(); 7678 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7679 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7680 + bp.name + " pkg=" + bp.sourcePackage 7681 + " info=" + bp.pendingInfo); 7682 if (bp.packageSetting == null && bp.pendingInfo != null) { 7683 final BasePermission tree = findPermissionTreeLP(bp.name); 7684 if (tree != null && tree.perm != null) { 7685 bp.packageSetting = tree.packageSetting; 7686 bp.perm = new PackageParser.Permission(tree.perm.owner, 7687 new PermissionInfo(bp.pendingInfo)); 7688 bp.perm.info.packageName = tree.perm.info.packageName; 7689 bp.perm.info.name = bp.name; 7690 bp.uid = tree.uid; 7691 } 7692 } 7693 } 7694 if (bp.packageSetting == null) { 7695 // We may not yet have parsed the package, so just see if 7696 // we still know about its settings. 7697 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7698 } 7699 if (bp.packageSetting == null) { 7700 Slog.w(TAG, "Removing dangling permission: " + bp.name 7701 + " from package " + bp.sourcePackage); 7702 it.remove(); 7703 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7704 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7705 Slog.i(TAG, "Removing old permission: " + bp.name 7706 + " from package " + bp.sourcePackage); 7707 flags |= UPDATE_PERMISSIONS_ALL; 7708 it.remove(); 7709 } 7710 } 7711 } 7712 7713 // Now update the permissions for all packages, in particular 7714 // replace the granted permissions of the system packages. 7715 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7716 for (PackageParser.Package pkg : mPackages.values()) { 7717 if (pkg != pkgInfo) { 7718 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7719 changingPkg); 7720 } 7721 } 7722 } 7723 7724 if (pkgInfo != null) { 7725 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7726 } 7727 } 7728 7729 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7730 String packageOfInterest) { 7731 // IMPORTANT: There are two types of permissions: install and runtime. 7732 // Install time permissions are granted when the app is installed to 7733 // all device users and users added in the future. Runtime permissions 7734 // are granted at runtime explicitly to specific users. Normal and signature 7735 // protected permissions are install time permissions. Dangerous permissions 7736 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7737 // otherwise they are runtime permissions. This function does not manage 7738 // runtime permissions except for the case an app targeting Lollipop MR1 7739 // being upgraded to target a newer SDK, in which case dangerous permissions 7740 // are transformed from install time to runtime ones. 7741 7742 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7743 if (ps == null) { 7744 return; 7745 } 7746 7747 PermissionsState permissionsState = ps.getPermissionsState(); 7748 PermissionsState origPermissions = permissionsState; 7749 7750 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7751 7752 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7753 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7754 7755 boolean changedInstallPermission = false; 7756 7757 if (replace) { 7758 ps.installPermissionsFixed = false; 7759 if (!ps.isSharedUser()) { 7760 origPermissions = new PermissionsState(permissionsState); 7761 permissionsState.reset(); 7762 } 7763 } 7764 7765 permissionsState.setGlobalGids(mGlobalGids); 7766 7767 final int N = pkg.requestedPermissions.size(); 7768 for (int i=0; i<N; i++) { 7769 final String name = pkg.requestedPermissions.get(i); 7770 final BasePermission bp = mSettings.mPermissions.get(name); 7771 7772 if (DEBUG_INSTALL) { 7773 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7774 } 7775 7776 if (bp == null || bp.packageSetting == null) { 7777 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7778 Slog.w(TAG, "Unknown permission " + name 7779 + " in package " + pkg.packageName); 7780 } 7781 continue; 7782 } 7783 7784 final String perm = bp.name; 7785 boolean allowedSig = false; 7786 int grant = GRANT_DENIED; 7787 7788 // Keep track of app op permissions. 7789 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7790 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7791 if (pkgs == null) { 7792 pkgs = new ArraySet<>(); 7793 mAppOpPermissionPackages.put(bp.name, pkgs); 7794 } 7795 pkgs.add(pkg.packageName); 7796 } 7797 7798 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7799 switch (level) { 7800 case PermissionInfo.PROTECTION_NORMAL: { 7801 // For all apps normal permissions are install time ones. 7802 grant = GRANT_INSTALL; 7803 } break; 7804 7805 case PermissionInfo.PROTECTION_DANGEROUS: { 7806 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7807 // For legacy apps dangerous permissions are install time ones. 7808 grant = GRANT_INSTALL_LEGACY; 7809 } else if (ps.isSystem()) { 7810 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7811 if (origPermissions.hasInstallPermission(bp.name)) { 7812 // If a system app had an install permission, then the app was 7813 // upgraded and we grant the permissions as runtime to all users. 7814 grant = GRANT_UPGRADE; 7815 upgradeUserIds = currentUserIds; 7816 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7817 // If users changed since the last permissions update for a 7818 // system app, we grant the permission as runtime to the new users. 7819 grant = GRANT_UPGRADE; 7820 upgradeUserIds = currentUserIds; 7821 for (int userId : updatedUserIds) { 7822 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7823 } 7824 } else { 7825 // Otherwise, we grant the permission as runtime if the app 7826 // already had it, i.e. we preserve runtime permissions. 7827 grant = GRANT_RUNTIME; 7828 } 7829 } else if (origPermissions.hasInstallPermission(bp.name)) { 7830 // For legacy apps that became modern, install becomes runtime. 7831 grant = GRANT_UPGRADE; 7832 upgradeUserIds = currentUserIds; 7833 } else if (replace) { 7834 // For upgraded modern apps keep runtime permissions unchanged. 7835 grant = GRANT_RUNTIME; 7836 } 7837 } break; 7838 7839 case PermissionInfo.PROTECTION_SIGNATURE: { 7840 // For all apps signature permissions are install time ones. 7841 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7842 if (allowedSig) { 7843 grant = GRANT_INSTALL; 7844 } 7845 } break; 7846 } 7847 7848 if (DEBUG_INSTALL) { 7849 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7850 } 7851 7852 if (grant != GRANT_DENIED) { 7853 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7854 // If this is an existing, non-system package, then 7855 // we can't add any new permissions to it. 7856 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7857 // Except... if this is a permission that was added 7858 // to the platform (note: need to only do this when 7859 // updating the platform). 7860 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7861 grant = GRANT_DENIED; 7862 } 7863 } 7864 } 7865 7866 switch (grant) { 7867 case GRANT_INSTALL: { 7868 // Revoke this as runtime permission to handle the case of 7869 // a runtime permssion being downgraded to an install one. 7870 for (int userId : UserManagerService.getInstance().getUserIds()) { 7871 if (origPermissions.getRuntimePermissionState( 7872 bp.name, userId) != null) { 7873 // Revoke the runtime permission and clear the flags. 7874 origPermissions.revokeRuntimePermission(bp, userId); 7875 origPermissions.updatePermissionFlags(bp, userId, 7876 PackageManager.MASK_PERMISSION_FLAGS, 0); 7877 // If we revoked a permission permission, we have to write. 7878 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7879 changedRuntimePermissionUserIds, userId); 7880 } 7881 } 7882 // Grant an install permission. 7883 if (permissionsState.grantInstallPermission(bp) != 7884 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7885 changedInstallPermission = true; 7886 } 7887 } break; 7888 7889 case GRANT_INSTALL_LEGACY: { 7890 // Grant an install permission. 7891 if (permissionsState.grantInstallPermission(bp) != 7892 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7893 changedInstallPermission = true; 7894 } 7895 } break; 7896 7897 case GRANT_RUNTIME: { 7898 // Grant previously granted runtime permissions. 7899 for (int userId : UserManagerService.getInstance().getUserIds()) { 7900 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7901 PermissionState permissionState = origPermissions 7902 .getRuntimePermissionState(bp.name, userId); 7903 final int flags = permissionState.getFlags(); 7904 if (permissionsState.grantRuntimePermission(bp, userId) == 7905 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7906 // If we cannot put the permission as it was, we have to write. 7907 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7908 changedRuntimePermissionUserIds, userId); 7909 } else { 7910 // System components not only get the permissions but 7911 // they are also fixed, so nothing can change that. 7912 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7913 ? flags 7914 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7915 // Propagate the permission flags. 7916 permissionsState.updatePermissionFlags(bp, userId, 7917 newFlags, newFlags); 7918 } 7919 } 7920 } 7921 } break; 7922 7923 case GRANT_UPGRADE: { 7924 // Grant runtime permissions for a previously held install permission. 7925 PermissionState permissionState = origPermissions 7926 .getInstallPermissionState(bp.name); 7927 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7928 7929 origPermissions.revokeInstallPermission(bp); 7930 // We will be transferring the permission flags, so clear them. 7931 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7932 PackageManager.MASK_PERMISSION_FLAGS, 0); 7933 7934 // If the permission is not to be promoted to runtime we ignore it and 7935 // also its other flags as they are not applicable to install permissions. 7936 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7937 for (int userId : upgradeUserIds) { 7938 if (permissionsState.grantRuntimePermission(bp, userId) != 7939 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7940 // System components not only get the permissions but 7941 // they are also fixed so nothing can change that. 7942 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7943 ? flags 7944 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7945 // Transfer the permission flags. 7946 permissionsState.updatePermissionFlags(bp, userId, 7947 newFlags, newFlags); 7948 // If we granted the permission, we have to write. 7949 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7950 changedRuntimePermissionUserIds, userId); 7951 } 7952 } 7953 } 7954 } break; 7955 7956 default: { 7957 if (packageOfInterest == null 7958 || packageOfInterest.equals(pkg.packageName)) { 7959 Slog.w(TAG, "Not granting permission " + perm 7960 + " to package " + pkg.packageName 7961 + " because it was previously installed without"); 7962 } 7963 } break; 7964 } 7965 } else { 7966 if (permissionsState.revokeInstallPermission(bp) != 7967 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7968 // Also drop the permission flags. 7969 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7970 PackageManager.MASK_PERMISSION_FLAGS, 0); 7971 changedInstallPermission = true; 7972 Slog.i(TAG, "Un-granting permission " + perm 7973 + " from package " + pkg.packageName 7974 + " (protectionLevel=" + bp.protectionLevel 7975 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7976 + ")"); 7977 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7978 // Don't print warning for app op permissions, since it is fine for them 7979 // not to be granted, there is a UI for the user to decide. 7980 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7981 Slog.w(TAG, "Not granting permission " + perm 7982 + " to package " + pkg.packageName 7983 + " (protectionLevel=" + bp.protectionLevel 7984 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7985 + ")"); 7986 } 7987 } 7988 } 7989 } 7990 7991 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7992 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7993 // This is the first that we have heard about this package, so the 7994 // permissions we have now selected are fixed until explicitly 7995 // changed. 7996 ps.installPermissionsFixed = true; 7997 } 7998 7999 ps.setPermissionsUpdatedForUserIds(currentUserIds); 8000 8001 // Persist the runtime permissions state for users with changes. 8002 for (int userId : changedRuntimePermissionUserIds) { 8003 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 8004 } 8005 } 8006 8007 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8008 boolean allowed = false; 8009 final int NP = PackageParser.NEW_PERMISSIONS.length; 8010 for (int ip=0; ip<NP; ip++) { 8011 final PackageParser.NewPermissionInfo npi 8012 = PackageParser.NEW_PERMISSIONS[ip]; 8013 if (npi.name.equals(perm) 8014 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8015 allowed = true; 8016 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8017 + pkg.packageName); 8018 break; 8019 } 8020 } 8021 return allowed; 8022 } 8023 8024 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8025 BasePermission bp, PermissionsState origPermissions) { 8026 boolean allowed; 8027 allowed = (compareSignatures( 8028 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8029 == PackageManager.SIGNATURE_MATCH) 8030 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8031 == PackageManager.SIGNATURE_MATCH); 8032 if (!allowed && (bp.protectionLevel 8033 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8034 if (isSystemApp(pkg)) { 8035 // For updated system applications, a system permission 8036 // is granted only if it had been defined by the original application. 8037 if (pkg.isUpdatedSystemApp()) { 8038 final PackageSetting sysPs = mSettings 8039 .getDisabledSystemPkgLPr(pkg.packageName); 8040 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8041 // If the original was granted this permission, we take 8042 // that grant decision as read and propagate it to the 8043 // update. 8044 if (sysPs.isPrivileged()) { 8045 allowed = true; 8046 } 8047 } else { 8048 // The system apk may have been updated with an older 8049 // version of the one on the data partition, but which 8050 // granted a new system permission that it didn't have 8051 // before. In this case we do want to allow the app to 8052 // now get the new permission if the ancestral apk is 8053 // privileged to get it. 8054 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8055 for (int j=0; 8056 j<sysPs.pkg.requestedPermissions.size(); j++) { 8057 if (perm.equals( 8058 sysPs.pkg.requestedPermissions.get(j))) { 8059 allowed = true; 8060 break; 8061 } 8062 } 8063 } 8064 } 8065 } else { 8066 allowed = isPrivilegedApp(pkg); 8067 } 8068 } 8069 } 8070 if (!allowed && (bp.protectionLevel 8071 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8072 // For development permissions, a development permission 8073 // is granted only if it was already granted. 8074 allowed = origPermissions.hasInstallPermission(perm); 8075 } 8076 return allowed; 8077 } 8078 8079 final class ActivityIntentResolver 8080 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8081 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8082 boolean defaultOnly, int userId) { 8083 if (!sUserManager.exists(userId)) return null; 8084 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8085 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8086 } 8087 8088 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8089 int userId) { 8090 if (!sUserManager.exists(userId)) return null; 8091 mFlags = flags; 8092 return super.queryIntent(intent, resolvedType, 8093 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8094 } 8095 8096 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8097 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8098 if (!sUserManager.exists(userId)) return null; 8099 if (packageActivities == null) { 8100 return null; 8101 } 8102 mFlags = flags; 8103 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8104 final int N = packageActivities.size(); 8105 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8106 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8107 8108 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8109 for (int i = 0; i < N; ++i) { 8110 intentFilters = packageActivities.get(i).intents; 8111 if (intentFilters != null && intentFilters.size() > 0) { 8112 PackageParser.ActivityIntentInfo[] array = 8113 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8114 intentFilters.toArray(array); 8115 listCut.add(array); 8116 } 8117 } 8118 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8119 } 8120 8121 public final void addActivity(PackageParser.Activity a, String type) { 8122 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8123 mActivities.put(a.getComponentName(), a); 8124 if (DEBUG_SHOW_INFO) 8125 Log.v( 8126 TAG, " " + type + " " + 8127 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8128 if (DEBUG_SHOW_INFO) 8129 Log.v(TAG, " Class=" + a.info.name); 8130 final int NI = a.intents.size(); 8131 for (int j=0; j<NI; j++) { 8132 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8133 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8134 intent.setPriority(0); 8135 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8136 + a.className + " with priority > 0, forcing to 0"); 8137 } 8138 if (DEBUG_SHOW_INFO) { 8139 Log.v(TAG, " IntentFilter:"); 8140 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8141 } 8142 if (!intent.debugCheck()) { 8143 Log.w(TAG, "==> For Activity " + a.info.name); 8144 } 8145 addFilter(intent); 8146 } 8147 } 8148 8149 public final void removeActivity(PackageParser.Activity a, String type) { 8150 mActivities.remove(a.getComponentName()); 8151 if (DEBUG_SHOW_INFO) { 8152 Log.v(TAG, " " + type + " " 8153 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8154 : a.info.name) + ":"); 8155 Log.v(TAG, " Class=" + a.info.name); 8156 } 8157 final int NI = a.intents.size(); 8158 for (int j=0; j<NI; j++) { 8159 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8160 if (DEBUG_SHOW_INFO) { 8161 Log.v(TAG, " IntentFilter:"); 8162 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8163 } 8164 removeFilter(intent); 8165 } 8166 } 8167 8168 @Override 8169 protected boolean allowFilterResult( 8170 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8171 ActivityInfo filterAi = filter.activity.info; 8172 for (int i=dest.size()-1; i>=0; i--) { 8173 ActivityInfo destAi = dest.get(i).activityInfo; 8174 if (destAi.name == filterAi.name 8175 && destAi.packageName == filterAi.packageName) { 8176 return false; 8177 } 8178 } 8179 return true; 8180 } 8181 8182 @Override 8183 protected ActivityIntentInfo[] newArray(int size) { 8184 return new ActivityIntentInfo[size]; 8185 } 8186 8187 @Override 8188 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8189 if (!sUserManager.exists(userId)) return true; 8190 PackageParser.Package p = filter.activity.owner; 8191 if (p != null) { 8192 PackageSetting ps = (PackageSetting)p.mExtras; 8193 if (ps != null) { 8194 // System apps are never considered stopped for purposes of 8195 // filtering, because there may be no way for the user to 8196 // actually re-launch them. 8197 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8198 && ps.getStopped(userId); 8199 } 8200 } 8201 return false; 8202 } 8203 8204 @Override 8205 protected boolean isPackageForFilter(String packageName, 8206 PackageParser.ActivityIntentInfo info) { 8207 return packageName.equals(info.activity.owner.packageName); 8208 } 8209 8210 @Override 8211 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8212 int match, int userId) { 8213 if (!sUserManager.exists(userId)) return null; 8214 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8215 return null; 8216 } 8217 final PackageParser.Activity activity = info.activity; 8218 if (mSafeMode && (activity.info.applicationInfo.flags 8219 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8220 return null; 8221 } 8222 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8223 if (ps == null) { 8224 return null; 8225 } 8226 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8227 ps.readUserState(userId), userId); 8228 if (ai == null) { 8229 return null; 8230 } 8231 final ResolveInfo res = new ResolveInfo(); 8232 res.activityInfo = ai; 8233 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8234 res.filter = info; 8235 } 8236 if (info != null) { 8237 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8238 } 8239 res.priority = info.getPriority(); 8240 res.preferredOrder = activity.owner.mPreferredOrder; 8241 //System.out.println("Result: " + res.activityInfo.className + 8242 // " = " + res.priority); 8243 res.match = match; 8244 res.isDefault = info.hasDefault; 8245 res.labelRes = info.labelRes; 8246 res.nonLocalizedLabel = info.nonLocalizedLabel; 8247 if (userNeedsBadging(userId)) { 8248 res.noResourceId = true; 8249 } else { 8250 res.icon = info.icon; 8251 } 8252 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8253 return res; 8254 } 8255 8256 @Override 8257 protected void sortResults(List<ResolveInfo> results) { 8258 Collections.sort(results, mResolvePrioritySorter); 8259 } 8260 8261 @Override 8262 protected void dumpFilter(PrintWriter out, String prefix, 8263 PackageParser.ActivityIntentInfo filter) { 8264 out.print(prefix); out.print( 8265 Integer.toHexString(System.identityHashCode(filter.activity))); 8266 out.print(' '); 8267 filter.activity.printComponentShortName(out); 8268 out.print(" filter "); 8269 out.println(Integer.toHexString(System.identityHashCode(filter))); 8270 } 8271 8272 @Override 8273 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8274 return filter.activity; 8275 } 8276 8277 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8278 PackageParser.Activity activity = (PackageParser.Activity)label; 8279 out.print(prefix); out.print( 8280 Integer.toHexString(System.identityHashCode(activity))); 8281 out.print(' '); 8282 activity.printComponentShortName(out); 8283 if (count > 1) { 8284 out.print(" ("); out.print(count); out.print(" filters)"); 8285 } 8286 out.println(); 8287 } 8288 8289// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8290// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8291// final List<ResolveInfo> retList = Lists.newArrayList(); 8292// while (i.hasNext()) { 8293// final ResolveInfo resolveInfo = i.next(); 8294// if (isEnabledLP(resolveInfo.activityInfo)) { 8295// retList.add(resolveInfo); 8296// } 8297// } 8298// return retList; 8299// } 8300 8301 // Keys are String (activity class name), values are Activity. 8302 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8303 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8304 private int mFlags; 8305 } 8306 8307 private final class ServiceIntentResolver 8308 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8309 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8310 boolean defaultOnly, int userId) { 8311 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8312 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8313 } 8314 8315 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8316 int userId) { 8317 if (!sUserManager.exists(userId)) return null; 8318 mFlags = flags; 8319 return super.queryIntent(intent, resolvedType, 8320 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8321 } 8322 8323 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8324 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8325 if (!sUserManager.exists(userId)) return null; 8326 if (packageServices == null) { 8327 return null; 8328 } 8329 mFlags = flags; 8330 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8331 final int N = packageServices.size(); 8332 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8333 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8334 8335 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8336 for (int i = 0; i < N; ++i) { 8337 intentFilters = packageServices.get(i).intents; 8338 if (intentFilters != null && intentFilters.size() > 0) { 8339 PackageParser.ServiceIntentInfo[] array = 8340 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8341 intentFilters.toArray(array); 8342 listCut.add(array); 8343 } 8344 } 8345 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8346 } 8347 8348 public final void addService(PackageParser.Service s) { 8349 mServices.put(s.getComponentName(), s); 8350 if (DEBUG_SHOW_INFO) { 8351 Log.v(TAG, " " 8352 + (s.info.nonLocalizedLabel != null 8353 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8354 Log.v(TAG, " Class=" + s.info.name); 8355 } 8356 final int NI = s.intents.size(); 8357 int j; 8358 for (j=0; j<NI; j++) { 8359 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8360 if (DEBUG_SHOW_INFO) { 8361 Log.v(TAG, " IntentFilter:"); 8362 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8363 } 8364 if (!intent.debugCheck()) { 8365 Log.w(TAG, "==> For Service " + s.info.name); 8366 } 8367 addFilter(intent); 8368 } 8369 } 8370 8371 public final void removeService(PackageParser.Service s) { 8372 mServices.remove(s.getComponentName()); 8373 if (DEBUG_SHOW_INFO) { 8374 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8375 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8376 Log.v(TAG, " Class=" + s.info.name); 8377 } 8378 final int NI = s.intents.size(); 8379 int j; 8380 for (j=0; j<NI; j++) { 8381 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8382 if (DEBUG_SHOW_INFO) { 8383 Log.v(TAG, " IntentFilter:"); 8384 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8385 } 8386 removeFilter(intent); 8387 } 8388 } 8389 8390 @Override 8391 protected boolean allowFilterResult( 8392 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8393 ServiceInfo filterSi = filter.service.info; 8394 for (int i=dest.size()-1; i>=0; i--) { 8395 ServiceInfo destAi = dest.get(i).serviceInfo; 8396 if (destAi.name == filterSi.name 8397 && destAi.packageName == filterSi.packageName) { 8398 return false; 8399 } 8400 } 8401 return true; 8402 } 8403 8404 @Override 8405 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8406 return new PackageParser.ServiceIntentInfo[size]; 8407 } 8408 8409 @Override 8410 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8411 if (!sUserManager.exists(userId)) return true; 8412 PackageParser.Package p = filter.service.owner; 8413 if (p != null) { 8414 PackageSetting ps = (PackageSetting)p.mExtras; 8415 if (ps != null) { 8416 // System apps are never considered stopped for purposes of 8417 // filtering, because there may be no way for the user to 8418 // actually re-launch them. 8419 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8420 && ps.getStopped(userId); 8421 } 8422 } 8423 return false; 8424 } 8425 8426 @Override 8427 protected boolean isPackageForFilter(String packageName, 8428 PackageParser.ServiceIntentInfo info) { 8429 return packageName.equals(info.service.owner.packageName); 8430 } 8431 8432 @Override 8433 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8434 int match, int userId) { 8435 if (!sUserManager.exists(userId)) return null; 8436 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8437 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8438 return null; 8439 } 8440 final PackageParser.Service service = info.service; 8441 if (mSafeMode && (service.info.applicationInfo.flags 8442 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8443 return null; 8444 } 8445 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8446 if (ps == null) { 8447 return null; 8448 } 8449 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8450 ps.readUserState(userId), userId); 8451 if (si == null) { 8452 return null; 8453 } 8454 final ResolveInfo res = new ResolveInfo(); 8455 res.serviceInfo = si; 8456 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8457 res.filter = filter; 8458 } 8459 res.priority = info.getPriority(); 8460 res.preferredOrder = service.owner.mPreferredOrder; 8461 res.match = match; 8462 res.isDefault = info.hasDefault; 8463 res.labelRes = info.labelRes; 8464 res.nonLocalizedLabel = info.nonLocalizedLabel; 8465 res.icon = info.icon; 8466 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8467 return res; 8468 } 8469 8470 @Override 8471 protected void sortResults(List<ResolveInfo> results) { 8472 Collections.sort(results, mResolvePrioritySorter); 8473 } 8474 8475 @Override 8476 protected void dumpFilter(PrintWriter out, String prefix, 8477 PackageParser.ServiceIntentInfo filter) { 8478 out.print(prefix); out.print( 8479 Integer.toHexString(System.identityHashCode(filter.service))); 8480 out.print(' '); 8481 filter.service.printComponentShortName(out); 8482 out.print(" filter "); 8483 out.println(Integer.toHexString(System.identityHashCode(filter))); 8484 } 8485 8486 @Override 8487 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8488 return filter.service; 8489 } 8490 8491 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8492 PackageParser.Service service = (PackageParser.Service)label; 8493 out.print(prefix); out.print( 8494 Integer.toHexString(System.identityHashCode(service))); 8495 out.print(' '); 8496 service.printComponentShortName(out); 8497 if (count > 1) { 8498 out.print(" ("); out.print(count); out.print(" filters)"); 8499 } 8500 out.println(); 8501 } 8502 8503// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8504// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8505// final List<ResolveInfo> retList = Lists.newArrayList(); 8506// while (i.hasNext()) { 8507// final ResolveInfo resolveInfo = (ResolveInfo) i; 8508// if (isEnabledLP(resolveInfo.serviceInfo)) { 8509// retList.add(resolveInfo); 8510// } 8511// } 8512// return retList; 8513// } 8514 8515 // Keys are String (activity class name), values are Activity. 8516 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8517 = new ArrayMap<ComponentName, PackageParser.Service>(); 8518 private int mFlags; 8519 }; 8520 8521 private final class ProviderIntentResolver 8522 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8523 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8524 boolean defaultOnly, int userId) { 8525 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8526 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8527 } 8528 8529 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8530 int userId) { 8531 if (!sUserManager.exists(userId)) 8532 return null; 8533 mFlags = flags; 8534 return super.queryIntent(intent, resolvedType, 8535 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8536 } 8537 8538 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8539 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8540 if (!sUserManager.exists(userId)) 8541 return null; 8542 if (packageProviders == null) { 8543 return null; 8544 } 8545 mFlags = flags; 8546 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8547 final int N = packageProviders.size(); 8548 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8549 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8550 8551 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8552 for (int i = 0; i < N; ++i) { 8553 intentFilters = packageProviders.get(i).intents; 8554 if (intentFilters != null && intentFilters.size() > 0) { 8555 PackageParser.ProviderIntentInfo[] array = 8556 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8557 intentFilters.toArray(array); 8558 listCut.add(array); 8559 } 8560 } 8561 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8562 } 8563 8564 public final void addProvider(PackageParser.Provider p) { 8565 if (mProviders.containsKey(p.getComponentName())) { 8566 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8567 return; 8568 } 8569 8570 mProviders.put(p.getComponentName(), p); 8571 if (DEBUG_SHOW_INFO) { 8572 Log.v(TAG, " " 8573 + (p.info.nonLocalizedLabel != null 8574 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8575 Log.v(TAG, " Class=" + p.info.name); 8576 } 8577 final int NI = p.intents.size(); 8578 int j; 8579 for (j = 0; j < NI; j++) { 8580 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8581 if (DEBUG_SHOW_INFO) { 8582 Log.v(TAG, " IntentFilter:"); 8583 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8584 } 8585 if (!intent.debugCheck()) { 8586 Log.w(TAG, "==> For Provider " + p.info.name); 8587 } 8588 addFilter(intent); 8589 } 8590 } 8591 8592 public final void removeProvider(PackageParser.Provider p) { 8593 mProviders.remove(p.getComponentName()); 8594 if (DEBUG_SHOW_INFO) { 8595 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8596 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8597 Log.v(TAG, " Class=" + p.info.name); 8598 } 8599 final int NI = p.intents.size(); 8600 int j; 8601 for (j = 0; j < NI; j++) { 8602 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8603 if (DEBUG_SHOW_INFO) { 8604 Log.v(TAG, " IntentFilter:"); 8605 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8606 } 8607 removeFilter(intent); 8608 } 8609 } 8610 8611 @Override 8612 protected boolean allowFilterResult( 8613 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8614 ProviderInfo filterPi = filter.provider.info; 8615 for (int i = dest.size() - 1; i >= 0; i--) { 8616 ProviderInfo destPi = dest.get(i).providerInfo; 8617 if (destPi.name == filterPi.name 8618 && destPi.packageName == filterPi.packageName) { 8619 return false; 8620 } 8621 } 8622 return true; 8623 } 8624 8625 @Override 8626 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8627 return new PackageParser.ProviderIntentInfo[size]; 8628 } 8629 8630 @Override 8631 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8632 if (!sUserManager.exists(userId)) 8633 return true; 8634 PackageParser.Package p = filter.provider.owner; 8635 if (p != null) { 8636 PackageSetting ps = (PackageSetting) p.mExtras; 8637 if (ps != null) { 8638 // System apps are never considered stopped for purposes of 8639 // filtering, because there may be no way for the user to 8640 // actually re-launch them. 8641 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8642 && ps.getStopped(userId); 8643 } 8644 } 8645 return false; 8646 } 8647 8648 @Override 8649 protected boolean isPackageForFilter(String packageName, 8650 PackageParser.ProviderIntentInfo info) { 8651 return packageName.equals(info.provider.owner.packageName); 8652 } 8653 8654 @Override 8655 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8656 int match, int userId) { 8657 if (!sUserManager.exists(userId)) 8658 return null; 8659 final PackageParser.ProviderIntentInfo info = filter; 8660 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8661 return null; 8662 } 8663 final PackageParser.Provider provider = info.provider; 8664 if (mSafeMode && (provider.info.applicationInfo.flags 8665 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8666 return null; 8667 } 8668 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8669 if (ps == null) { 8670 return null; 8671 } 8672 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8673 ps.readUserState(userId), userId); 8674 if (pi == null) { 8675 return null; 8676 } 8677 final ResolveInfo res = new ResolveInfo(); 8678 res.providerInfo = pi; 8679 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8680 res.filter = filter; 8681 } 8682 res.priority = info.getPriority(); 8683 res.preferredOrder = provider.owner.mPreferredOrder; 8684 res.match = match; 8685 res.isDefault = info.hasDefault; 8686 res.labelRes = info.labelRes; 8687 res.nonLocalizedLabel = info.nonLocalizedLabel; 8688 res.icon = info.icon; 8689 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8690 return res; 8691 } 8692 8693 @Override 8694 protected void sortResults(List<ResolveInfo> results) { 8695 Collections.sort(results, mResolvePrioritySorter); 8696 } 8697 8698 @Override 8699 protected void dumpFilter(PrintWriter out, String prefix, 8700 PackageParser.ProviderIntentInfo filter) { 8701 out.print(prefix); 8702 out.print( 8703 Integer.toHexString(System.identityHashCode(filter.provider))); 8704 out.print(' '); 8705 filter.provider.printComponentShortName(out); 8706 out.print(" filter "); 8707 out.println(Integer.toHexString(System.identityHashCode(filter))); 8708 } 8709 8710 @Override 8711 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8712 return filter.provider; 8713 } 8714 8715 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8716 PackageParser.Provider provider = (PackageParser.Provider)label; 8717 out.print(prefix); out.print( 8718 Integer.toHexString(System.identityHashCode(provider))); 8719 out.print(' '); 8720 provider.printComponentShortName(out); 8721 if (count > 1) { 8722 out.print(" ("); out.print(count); out.print(" filters)"); 8723 } 8724 out.println(); 8725 } 8726 8727 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8728 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8729 private int mFlags; 8730 }; 8731 8732 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8733 new Comparator<ResolveInfo>() { 8734 public int compare(ResolveInfo r1, ResolveInfo r2) { 8735 int v1 = r1.priority; 8736 int v2 = r2.priority; 8737 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8738 if (v1 != v2) { 8739 return (v1 > v2) ? -1 : 1; 8740 } 8741 v1 = r1.preferredOrder; 8742 v2 = r2.preferredOrder; 8743 if (v1 != v2) { 8744 return (v1 > v2) ? -1 : 1; 8745 } 8746 if (r1.isDefault != r2.isDefault) { 8747 return r1.isDefault ? -1 : 1; 8748 } 8749 v1 = r1.match; 8750 v2 = r2.match; 8751 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8752 if (v1 != v2) { 8753 return (v1 > v2) ? -1 : 1; 8754 } 8755 if (r1.system != r2.system) { 8756 return r1.system ? -1 : 1; 8757 } 8758 return 0; 8759 } 8760 }; 8761 8762 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8763 new Comparator<ProviderInfo>() { 8764 public int compare(ProviderInfo p1, ProviderInfo p2) { 8765 final int v1 = p1.initOrder; 8766 final int v2 = p2.initOrder; 8767 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8768 } 8769 }; 8770 8771 final void sendPackageBroadcast(final String action, final String pkg, 8772 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8773 final int[] userIds) { 8774 mHandler.post(new Runnable() { 8775 @Override 8776 public void run() { 8777 try { 8778 final IActivityManager am = ActivityManagerNative.getDefault(); 8779 if (am == null) return; 8780 final int[] resolvedUserIds; 8781 if (userIds == null) { 8782 resolvedUserIds = am.getRunningUserIds(); 8783 } else { 8784 resolvedUserIds = userIds; 8785 } 8786 for (int id : resolvedUserIds) { 8787 final Intent intent = new Intent(action, 8788 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8789 if (extras != null) { 8790 intent.putExtras(extras); 8791 } 8792 if (targetPkg != null) { 8793 intent.setPackage(targetPkg); 8794 } 8795 // Modify the UID when posting to other users 8796 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8797 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8798 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8799 intent.putExtra(Intent.EXTRA_UID, uid); 8800 } 8801 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8802 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8803 if (DEBUG_BROADCASTS) { 8804 RuntimeException here = new RuntimeException("here"); 8805 here.fillInStackTrace(); 8806 Slog.d(TAG, "Sending to user " + id + ": " 8807 + intent.toShortString(false, true, false, false) 8808 + " " + intent.getExtras(), here); 8809 } 8810 am.broadcastIntent(null, intent, null, finishedReceiver, 8811 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8812 null, finishedReceiver != null, false, id); 8813 } 8814 } catch (RemoteException ex) { 8815 } 8816 } 8817 }); 8818 } 8819 8820 /** 8821 * Check if the external storage media is available. This is true if there 8822 * is a mounted external storage medium or if the external storage is 8823 * emulated. 8824 */ 8825 private boolean isExternalMediaAvailable() { 8826 return mMediaMounted || Environment.isExternalStorageEmulated(); 8827 } 8828 8829 @Override 8830 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8831 // writer 8832 synchronized (mPackages) { 8833 if (!isExternalMediaAvailable()) { 8834 // If the external storage is no longer mounted at this point, 8835 // the caller may not have been able to delete all of this 8836 // packages files and can not delete any more. Bail. 8837 return null; 8838 } 8839 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8840 if (lastPackage != null) { 8841 pkgs.remove(lastPackage); 8842 } 8843 if (pkgs.size() > 0) { 8844 return pkgs.get(0); 8845 } 8846 } 8847 return null; 8848 } 8849 8850 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8851 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8852 userId, andCode ? 1 : 0, packageName); 8853 if (mSystemReady) { 8854 msg.sendToTarget(); 8855 } else { 8856 if (mPostSystemReadyMessages == null) { 8857 mPostSystemReadyMessages = new ArrayList<>(); 8858 } 8859 mPostSystemReadyMessages.add(msg); 8860 } 8861 } 8862 8863 void startCleaningPackages() { 8864 // reader 8865 synchronized (mPackages) { 8866 if (!isExternalMediaAvailable()) { 8867 return; 8868 } 8869 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8870 return; 8871 } 8872 } 8873 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8874 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8875 IActivityManager am = ActivityManagerNative.getDefault(); 8876 if (am != null) { 8877 try { 8878 am.startService(null, intent, null, UserHandle.USER_OWNER); 8879 } catch (RemoteException e) { 8880 } 8881 } 8882 } 8883 8884 @Override 8885 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8886 int installFlags, String installerPackageName, VerificationParams verificationParams, 8887 String packageAbiOverride) { 8888 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8889 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8890 } 8891 8892 @Override 8893 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8894 int installFlags, String installerPackageName, VerificationParams verificationParams, 8895 String packageAbiOverride, int userId) { 8896 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8897 8898 final int callingUid = Binder.getCallingUid(); 8899 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8900 8901 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8902 try { 8903 if (observer != null) { 8904 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8905 } 8906 } catch (RemoteException re) { 8907 } 8908 return; 8909 } 8910 8911 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8912 installFlags |= PackageManager.INSTALL_FROM_ADB; 8913 8914 } else { 8915 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8916 // about installerPackageName. 8917 8918 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8919 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8920 } 8921 8922 UserHandle user; 8923 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8924 user = UserHandle.ALL; 8925 } else { 8926 user = new UserHandle(userId); 8927 } 8928 8929 // Only system components can circumvent runtime permissions when installing. 8930 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8931 && mContext.checkCallingOrSelfPermission(Manifest.permission 8932 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8933 throw new SecurityException("You need the " 8934 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8935 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8936 } 8937 8938 verificationParams.setInstallerUid(callingUid); 8939 8940 final File originFile = new File(originPath); 8941 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8942 8943 final Message msg = mHandler.obtainMessage(INIT_COPY); 8944 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8945 null, verificationParams, user, packageAbiOverride); 8946 mHandler.sendMessage(msg); 8947 } 8948 8949 void installStage(String packageName, File stagedDir, String stagedCid, 8950 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8951 String installerPackageName, int installerUid, UserHandle user) { 8952 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8953 params.referrerUri, installerUid, null); 8954 8955 final OriginInfo origin; 8956 if (stagedDir != null) { 8957 origin = OriginInfo.fromStagedFile(stagedDir); 8958 } else { 8959 origin = OriginInfo.fromStagedContainer(stagedCid); 8960 } 8961 8962 final Message msg = mHandler.obtainMessage(INIT_COPY); 8963 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8964 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8965 mHandler.sendMessage(msg); 8966 } 8967 8968 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8969 Bundle extras = new Bundle(1); 8970 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8971 8972 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8973 packageName, extras, null, null, new int[] {userId}); 8974 try { 8975 IActivityManager am = ActivityManagerNative.getDefault(); 8976 final boolean isSystem = 8977 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8978 if (isSystem && am.isUserRunning(userId, false)) { 8979 // The just-installed/enabled app is bundled on the system, so presumed 8980 // to be able to run automatically without needing an explicit launch. 8981 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8982 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8983 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8984 .setPackage(packageName); 8985 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8986 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 8987 } 8988 } catch (RemoteException e) { 8989 // shouldn't happen 8990 Slog.w(TAG, "Unable to bootstrap installed package", e); 8991 } 8992 } 8993 8994 @Override 8995 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8996 int userId) { 8997 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8998 PackageSetting pkgSetting; 8999 final int uid = Binder.getCallingUid(); 9000 enforceCrossUserPermission(uid, userId, true, true, 9001 "setApplicationHiddenSetting for user " + userId); 9002 9003 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9004 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9005 return false; 9006 } 9007 9008 long callingId = Binder.clearCallingIdentity(); 9009 try { 9010 boolean sendAdded = false; 9011 boolean sendRemoved = false; 9012 // writer 9013 synchronized (mPackages) { 9014 pkgSetting = mSettings.mPackages.get(packageName); 9015 if (pkgSetting == null) { 9016 return false; 9017 } 9018 if (pkgSetting.getHidden(userId) != hidden) { 9019 pkgSetting.setHidden(hidden, userId); 9020 mSettings.writePackageRestrictionsLPr(userId); 9021 if (hidden) { 9022 sendRemoved = true; 9023 } else { 9024 sendAdded = true; 9025 } 9026 } 9027 } 9028 if (sendAdded) { 9029 sendPackageAddedForUser(packageName, pkgSetting, userId); 9030 return true; 9031 } 9032 if (sendRemoved) { 9033 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9034 "hiding pkg"); 9035 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9036 } 9037 } finally { 9038 Binder.restoreCallingIdentity(callingId); 9039 } 9040 return false; 9041 } 9042 9043 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9044 int userId) { 9045 final PackageRemovedInfo info = new PackageRemovedInfo(); 9046 info.removedPackage = packageName; 9047 info.removedUsers = new int[] {userId}; 9048 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9049 info.sendBroadcast(false, false, false); 9050 } 9051 9052 /** 9053 * Returns true if application is not found or there was an error. Otherwise it returns 9054 * the hidden state of the package for the given user. 9055 */ 9056 @Override 9057 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9058 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9059 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9060 false, "getApplicationHidden for user " + userId); 9061 PackageSetting pkgSetting; 9062 long callingId = Binder.clearCallingIdentity(); 9063 try { 9064 // writer 9065 synchronized (mPackages) { 9066 pkgSetting = mSettings.mPackages.get(packageName); 9067 if (pkgSetting == null) { 9068 return true; 9069 } 9070 return pkgSetting.getHidden(userId); 9071 } 9072 } finally { 9073 Binder.restoreCallingIdentity(callingId); 9074 } 9075 } 9076 9077 /** 9078 * @hide 9079 */ 9080 @Override 9081 public int installExistingPackageAsUser(String packageName, int userId) { 9082 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9083 null); 9084 PackageSetting pkgSetting; 9085 final int uid = Binder.getCallingUid(); 9086 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9087 + userId); 9088 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9089 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9090 } 9091 9092 long callingId = Binder.clearCallingIdentity(); 9093 try { 9094 boolean sendAdded = false; 9095 9096 // writer 9097 synchronized (mPackages) { 9098 pkgSetting = mSettings.mPackages.get(packageName); 9099 if (pkgSetting == null) { 9100 return PackageManager.INSTALL_FAILED_INVALID_URI; 9101 } 9102 if (!pkgSetting.getInstalled(userId)) { 9103 pkgSetting.setInstalled(true, userId); 9104 pkgSetting.setHidden(false, userId); 9105 mSettings.writePackageRestrictionsLPr(userId); 9106 sendAdded = true; 9107 } 9108 } 9109 9110 if (sendAdded) { 9111 sendPackageAddedForUser(packageName, pkgSetting, userId); 9112 } 9113 } finally { 9114 Binder.restoreCallingIdentity(callingId); 9115 } 9116 9117 return PackageManager.INSTALL_SUCCEEDED; 9118 } 9119 9120 boolean isUserRestricted(int userId, String restrictionKey) { 9121 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9122 if (restrictions.getBoolean(restrictionKey, false)) { 9123 Log.w(TAG, "User is restricted: " + restrictionKey); 9124 return true; 9125 } 9126 return false; 9127 } 9128 9129 @Override 9130 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9131 mContext.enforceCallingOrSelfPermission( 9132 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9133 "Only package verification agents can verify applications"); 9134 9135 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9136 final PackageVerificationResponse response = new PackageVerificationResponse( 9137 verificationCode, Binder.getCallingUid()); 9138 msg.arg1 = id; 9139 msg.obj = response; 9140 mHandler.sendMessage(msg); 9141 } 9142 9143 @Override 9144 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9145 long millisecondsToDelay) { 9146 mContext.enforceCallingOrSelfPermission( 9147 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9148 "Only package verification agents can extend verification timeouts"); 9149 9150 final PackageVerificationState state = mPendingVerification.get(id); 9151 final PackageVerificationResponse response = new PackageVerificationResponse( 9152 verificationCodeAtTimeout, Binder.getCallingUid()); 9153 9154 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9155 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9156 } 9157 if (millisecondsToDelay < 0) { 9158 millisecondsToDelay = 0; 9159 } 9160 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9161 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9162 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9163 } 9164 9165 if ((state != null) && !state.timeoutExtended()) { 9166 state.extendTimeout(); 9167 9168 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9169 msg.arg1 = id; 9170 msg.obj = response; 9171 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9172 } 9173 } 9174 9175 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9176 int verificationCode, UserHandle user) { 9177 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9178 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9179 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9180 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9181 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9182 9183 mContext.sendBroadcastAsUser(intent, user, 9184 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9185 } 9186 9187 private ComponentName matchComponentForVerifier(String packageName, 9188 List<ResolveInfo> receivers) { 9189 ActivityInfo targetReceiver = null; 9190 9191 final int NR = receivers.size(); 9192 for (int i = 0; i < NR; i++) { 9193 final ResolveInfo info = receivers.get(i); 9194 if (info.activityInfo == null) { 9195 continue; 9196 } 9197 9198 if (packageName.equals(info.activityInfo.packageName)) { 9199 targetReceiver = info.activityInfo; 9200 break; 9201 } 9202 } 9203 9204 if (targetReceiver == null) { 9205 return null; 9206 } 9207 9208 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9209 } 9210 9211 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9212 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9213 if (pkgInfo.verifiers.length == 0) { 9214 return null; 9215 } 9216 9217 final int N = pkgInfo.verifiers.length; 9218 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9219 for (int i = 0; i < N; i++) { 9220 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9221 9222 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9223 receivers); 9224 if (comp == null) { 9225 continue; 9226 } 9227 9228 final int verifierUid = getUidForVerifier(verifierInfo); 9229 if (verifierUid == -1) { 9230 continue; 9231 } 9232 9233 if (DEBUG_VERIFY) { 9234 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9235 + " with the correct signature"); 9236 } 9237 sufficientVerifiers.add(comp); 9238 verificationState.addSufficientVerifier(verifierUid); 9239 } 9240 9241 return sufficientVerifiers; 9242 } 9243 9244 private int getUidForVerifier(VerifierInfo verifierInfo) { 9245 synchronized (mPackages) { 9246 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9247 if (pkg == null) { 9248 return -1; 9249 } else if (pkg.mSignatures.length != 1) { 9250 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9251 + " has more than one signature; ignoring"); 9252 return -1; 9253 } 9254 9255 /* 9256 * If the public key of the package's signature does not match 9257 * our expected public key, then this is a different package and 9258 * we should skip. 9259 */ 9260 9261 final byte[] expectedPublicKey; 9262 try { 9263 final Signature verifierSig = pkg.mSignatures[0]; 9264 final PublicKey publicKey = verifierSig.getPublicKey(); 9265 expectedPublicKey = publicKey.getEncoded(); 9266 } catch (CertificateException e) { 9267 return -1; 9268 } 9269 9270 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9271 9272 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9273 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9274 + " does not have the expected public key; ignoring"); 9275 return -1; 9276 } 9277 9278 return pkg.applicationInfo.uid; 9279 } 9280 } 9281 9282 @Override 9283 public void finishPackageInstall(int token) { 9284 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9285 9286 if (DEBUG_INSTALL) { 9287 Slog.v(TAG, "BM finishing package install for " + token); 9288 } 9289 9290 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9291 mHandler.sendMessage(msg); 9292 } 9293 9294 /** 9295 * Get the verification agent timeout. 9296 * 9297 * @return verification timeout in milliseconds 9298 */ 9299 private long getVerificationTimeout() { 9300 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9301 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9302 DEFAULT_VERIFICATION_TIMEOUT); 9303 } 9304 9305 /** 9306 * Get the default verification agent response code. 9307 * 9308 * @return default verification response code 9309 */ 9310 private int getDefaultVerificationResponse() { 9311 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9312 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9313 DEFAULT_VERIFICATION_RESPONSE); 9314 } 9315 9316 /** 9317 * Check whether or not package verification has been enabled. 9318 * 9319 * @return true if verification should be performed 9320 */ 9321 private boolean isVerificationEnabled(int userId, int installFlags) { 9322 if (!DEFAULT_VERIFY_ENABLE) { 9323 return false; 9324 } 9325 9326 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9327 9328 // Check if installing from ADB 9329 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9330 // Do not run verification in a test harness environment 9331 if (ActivityManager.isRunningInTestHarness()) { 9332 return false; 9333 } 9334 if (ensureVerifyAppsEnabled) { 9335 return true; 9336 } 9337 // Check if the developer does not want package verification for ADB installs 9338 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9339 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9340 return false; 9341 } 9342 } 9343 9344 if (ensureVerifyAppsEnabled) { 9345 return true; 9346 } 9347 9348 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9349 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9350 } 9351 9352 @Override 9353 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9354 throws RemoteException { 9355 mContext.enforceCallingOrSelfPermission( 9356 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9357 "Only intentfilter verification agents can verify applications"); 9358 9359 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9360 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9361 Binder.getCallingUid(), verificationCode, failedDomains); 9362 msg.arg1 = id; 9363 msg.obj = response; 9364 mHandler.sendMessage(msg); 9365 } 9366 9367 @Override 9368 public int getIntentVerificationStatus(String packageName, int userId) { 9369 synchronized (mPackages) { 9370 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9371 } 9372 } 9373 9374 @Override 9375 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9376 boolean result = false; 9377 synchronized (mPackages) { 9378 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9379 } 9380 if (result) { 9381 scheduleWritePackageRestrictionsLocked(userId); 9382 } 9383 return result; 9384 } 9385 9386 @Override 9387 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9388 synchronized (mPackages) { 9389 return mSettings.getIntentFilterVerificationsLPr(packageName); 9390 } 9391 } 9392 9393 @Override 9394 public List<IntentFilter> getAllIntentFilters(String packageName) { 9395 if (TextUtils.isEmpty(packageName)) { 9396 return Collections.<IntentFilter>emptyList(); 9397 } 9398 synchronized (mPackages) { 9399 PackageParser.Package pkg = mPackages.get(packageName); 9400 if (pkg == null || pkg.activities == null) { 9401 return Collections.<IntentFilter>emptyList(); 9402 } 9403 final int count = pkg.activities.size(); 9404 ArrayList<IntentFilter> result = new ArrayList<>(); 9405 for (int n=0; n<count; n++) { 9406 PackageParser.Activity activity = pkg.activities.get(n); 9407 if (activity.intents != null || activity.intents.size() > 0) { 9408 result.addAll(activity.intents); 9409 } 9410 } 9411 return result; 9412 } 9413 } 9414 9415 @Override 9416 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9417 synchronized (mPackages) { 9418 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9419 if (packageName != null) { 9420 result |= updateIntentVerificationStatus(packageName, 9421 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9422 UserHandle.myUserId()); 9423 } 9424 return result; 9425 } 9426 } 9427 9428 @Override 9429 public String getDefaultBrowserPackageName(int userId) { 9430 synchronized (mPackages) { 9431 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9432 } 9433 } 9434 9435 /** 9436 * Get the "allow unknown sources" setting. 9437 * 9438 * @return the current "allow unknown sources" setting 9439 */ 9440 private int getUnknownSourcesSettings() { 9441 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9442 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9443 -1); 9444 } 9445 9446 @Override 9447 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9448 final int uid = Binder.getCallingUid(); 9449 // writer 9450 synchronized (mPackages) { 9451 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9452 if (targetPackageSetting == null) { 9453 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9454 } 9455 9456 PackageSetting installerPackageSetting; 9457 if (installerPackageName != null) { 9458 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9459 if (installerPackageSetting == null) { 9460 throw new IllegalArgumentException("Unknown installer package: " 9461 + installerPackageName); 9462 } 9463 } else { 9464 installerPackageSetting = null; 9465 } 9466 9467 Signature[] callerSignature; 9468 Object obj = mSettings.getUserIdLPr(uid); 9469 if (obj != null) { 9470 if (obj instanceof SharedUserSetting) { 9471 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9472 } else if (obj instanceof PackageSetting) { 9473 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9474 } else { 9475 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9476 } 9477 } else { 9478 throw new SecurityException("Unknown calling uid " + uid); 9479 } 9480 9481 // Verify: can't set installerPackageName to a package that is 9482 // not signed with the same cert as the caller. 9483 if (installerPackageSetting != null) { 9484 if (compareSignatures(callerSignature, 9485 installerPackageSetting.signatures.mSignatures) 9486 != PackageManager.SIGNATURE_MATCH) { 9487 throw new SecurityException( 9488 "Caller does not have same cert as new installer package " 9489 + installerPackageName); 9490 } 9491 } 9492 9493 // Verify: if target already has an installer package, it must 9494 // be signed with the same cert as the caller. 9495 if (targetPackageSetting.installerPackageName != null) { 9496 PackageSetting setting = mSettings.mPackages.get( 9497 targetPackageSetting.installerPackageName); 9498 // If the currently set package isn't valid, then it's always 9499 // okay to change it. 9500 if (setting != null) { 9501 if (compareSignatures(callerSignature, 9502 setting.signatures.mSignatures) 9503 != PackageManager.SIGNATURE_MATCH) { 9504 throw new SecurityException( 9505 "Caller does not have same cert as old installer package " 9506 + targetPackageSetting.installerPackageName); 9507 } 9508 } 9509 } 9510 9511 // Okay! 9512 targetPackageSetting.installerPackageName = installerPackageName; 9513 scheduleWriteSettingsLocked(); 9514 } 9515 } 9516 9517 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9518 // Queue up an async operation since the package installation may take a little while. 9519 mHandler.post(new Runnable() { 9520 public void run() { 9521 mHandler.removeCallbacks(this); 9522 // Result object to be returned 9523 PackageInstalledInfo res = new PackageInstalledInfo(); 9524 res.returnCode = currentStatus; 9525 res.uid = -1; 9526 res.pkg = null; 9527 res.removedInfo = new PackageRemovedInfo(); 9528 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9529 args.doPreInstall(res.returnCode); 9530 synchronized (mInstallLock) { 9531 installPackageLI(args, res); 9532 } 9533 args.doPostInstall(res.returnCode, res.uid); 9534 } 9535 9536 // A restore should be performed at this point if (a) the install 9537 // succeeded, (b) the operation is not an update, and (c) the new 9538 // package has not opted out of backup participation. 9539 final boolean update = res.removedInfo.removedPackage != null; 9540 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9541 boolean doRestore = !update 9542 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9543 9544 // Set up the post-install work request bookkeeping. This will be used 9545 // and cleaned up by the post-install event handling regardless of whether 9546 // there's a restore pass performed. Token values are >= 1. 9547 int token; 9548 if (mNextInstallToken < 0) mNextInstallToken = 1; 9549 token = mNextInstallToken++; 9550 9551 PostInstallData data = new PostInstallData(args, res); 9552 mRunningInstalls.put(token, data); 9553 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9554 9555 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9556 // Pass responsibility to the Backup Manager. It will perform a 9557 // restore if appropriate, then pass responsibility back to the 9558 // Package Manager to run the post-install observer callbacks 9559 // and broadcasts. 9560 IBackupManager bm = IBackupManager.Stub.asInterface( 9561 ServiceManager.getService(Context.BACKUP_SERVICE)); 9562 if (bm != null) { 9563 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9564 + " to BM for possible restore"); 9565 try { 9566 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9567 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9568 } else { 9569 doRestore = false; 9570 } 9571 } catch (RemoteException e) { 9572 // can't happen; the backup manager is local 9573 } catch (Exception e) { 9574 Slog.e(TAG, "Exception trying to enqueue restore", e); 9575 doRestore = false; 9576 } 9577 } else { 9578 Slog.e(TAG, "Backup Manager not found!"); 9579 doRestore = false; 9580 } 9581 } 9582 9583 if (!doRestore) { 9584 // No restore possible, or the Backup Manager was mysteriously not 9585 // available -- just fire the post-install work request directly. 9586 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9587 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9588 mHandler.sendMessage(msg); 9589 } 9590 } 9591 }); 9592 } 9593 9594 private abstract class HandlerParams { 9595 private static final int MAX_RETRIES = 4; 9596 9597 /** 9598 * Number of times startCopy() has been attempted and had a non-fatal 9599 * error. 9600 */ 9601 private int mRetries = 0; 9602 9603 /** User handle for the user requesting the information or installation. */ 9604 private final UserHandle mUser; 9605 9606 HandlerParams(UserHandle user) { 9607 mUser = user; 9608 } 9609 9610 UserHandle getUser() { 9611 return mUser; 9612 } 9613 9614 final boolean startCopy() { 9615 boolean res; 9616 try { 9617 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9618 9619 if (++mRetries > MAX_RETRIES) { 9620 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9621 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9622 handleServiceError(); 9623 return false; 9624 } else { 9625 handleStartCopy(); 9626 res = true; 9627 } 9628 } catch (RemoteException e) { 9629 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9630 mHandler.sendEmptyMessage(MCS_RECONNECT); 9631 res = false; 9632 } 9633 handleReturnCode(); 9634 return res; 9635 } 9636 9637 final void serviceError() { 9638 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9639 handleServiceError(); 9640 handleReturnCode(); 9641 } 9642 9643 abstract void handleStartCopy() throws RemoteException; 9644 abstract void handleServiceError(); 9645 abstract void handleReturnCode(); 9646 } 9647 9648 class MeasureParams extends HandlerParams { 9649 private final PackageStats mStats; 9650 private boolean mSuccess; 9651 9652 private final IPackageStatsObserver mObserver; 9653 9654 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9655 super(new UserHandle(stats.userHandle)); 9656 mObserver = observer; 9657 mStats = stats; 9658 } 9659 9660 @Override 9661 public String toString() { 9662 return "MeasureParams{" 9663 + Integer.toHexString(System.identityHashCode(this)) 9664 + " " + mStats.packageName + "}"; 9665 } 9666 9667 @Override 9668 void handleStartCopy() throws RemoteException { 9669 synchronized (mInstallLock) { 9670 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9671 } 9672 9673 if (mSuccess) { 9674 final boolean mounted; 9675 if (Environment.isExternalStorageEmulated()) { 9676 mounted = true; 9677 } else { 9678 final String status = Environment.getExternalStorageState(); 9679 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9680 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9681 } 9682 9683 if (mounted) { 9684 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9685 9686 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9687 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9688 9689 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9690 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9691 9692 // Always subtract cache size, since it's a subdirectory 9693 mStats.externalDataSize -= mStats.externalCacheSize; 9694 9695 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9696 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9697 9698 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9699 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9700 } 9701 } 9702 } 9703 9704 @Override 9705 void handleReturnCode() { 9706 if (mObserver != null) { 9707 try { 9708 mObserver.onGetStatsCompleted(mStats, mSuccess); 9709 } catch (RemoteException e) { 9710 Slog.i(TAG, "Observer no longer exists."); 9711 } 9712 } 9713 } 9714 9715 @Override 9716 void handleServiceError() { 9717 Slog.e(TAG, "Could not measure application " + mStats.packageName 9718 + " external storage"); 9719 } 9720 } 9721 9722 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9723 throws RemoteException { 9724 long result = 0; 9725 for (File path : paths) { 9726 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9727 } 9728 return result; 9729 } 9730 9731 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9732 for (File path : paths) { 9733 try { 9734 mcs.clearDirectory(path.getAbsolutePath()); 9735 } catch (RemoteException e) { 9736 } 9737 } 9738 } 9739 9740 static class OriginInfo { 9741 /** 9742 * Location where install is coming from, before it has been 9743 * copied/renamed into place. This could be a single monolithic APK 9744 * file, or a cluster directory. This location may be untrusted. 9745 */ 9746 final File file; 9747 final String cid; 9748 9749 /** 9750 * Flag indicating that {@link #file} or {@link #cid} has already been 9751 * staged, meaning downstream users don't need to defensively copy the 9752 * contents. 9753 */ 9754 final boolean staged; 9755 9756 /** 9757 * Flag indicating that {@link #file} or {@link #cid} is an already 9758 * installed app that is being moved. 9759 */ 9760 final boolean existing; 9761 9762 final String resolvedPath; 9763 final File resolvedFile; 9764 9765 static OriginInfo fromNothing() { 9766 return new OriginInfo(null, null, false, false); 9767 } 9768 9769 static OriginInfo fromUntrustedFile(File file) { 9770 return new OriginInfo(file, null, false, false); 9771 } 9772 9773 static OriginInfo fromExistingFile(File file) { 9774 return new OriginInfo(file, null, false, true); 9775 } 9776 9777 static OriginInfo fromStagedFile(File file) { 9778 return new OriginInfo(file, null, true, false); 9779 } 9780 9781 static OriginInfo fromStagedContainer(String cid) { 9782 return new OriginInfo(null, cid, true, false); 9783 } 9784 9785 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9786 this.file = file; 9787 this.cid = cid; 9788 this.staged = staged; 9789 this.existing = existing; 9790 9791 if (cid != null) { 9792 resolvedPath = PackageHelper.getSdDir(cid); 9793 resolvedFile = new File(resolvedPath); 9794 } else if (file != null) { 9795 resolvedPath = file.getAbsolutePath(); 9796 resolvedFile = file; 9797 } else { 9798 resolvedPath = null; 9799 resolvedFile = null; 9800 } 9801 } 9802 } 9803 9804 class MoveInfo { 9805 final int moveId; 9806 final String fromUuid; 9807 final String toUuid; 9808 final String packageName; 9809 final String dataAppName; 9810 final int appId; 9811 final String seinfo; 9812 9813 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9814 String dataAppName, int appId, String seinfo) { 9815 this.moveId = moveId; 9816 this.fromUuid = fromUuid; 9817 this.toUuid = toUuid; 9818 this.packageName = packageName; 9819 this.dataAppName = dataAppName; 9820 this.appId = appId; 9821 this.seinfo = seinfo; 9822 } 9823 } 9824 9825 class InstallParams extends HandlerParams { 9826 final OriginInfo origin; 9827 final MoveInfo move; 9828 final IPackageInstallObserver2 observer; 9829 int installFlags; 9830 final String installerPackageName; 9831 final String volumeUuid; 9832 final VerificationParams verificationParams; 9833 private InstallArgs mArgs; 9834 private int mRet; 9835 final String packageAbiOverride; 9836 9837 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9838 int installFlags, String installerPackageName, String volumeUuid, 9839 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9840 super(user); 9841 this.origin = origin; 9842 this.move = move; 9843 this.observer = observer; 9844 this.installFlags = installFlags; 9845 this.installerPackageName = installerPackageName; 9846 this.volumeUuid = volumeUuid; 9847 this.verificationParams = verificationParams; 9848 this.packageAbiOverride = packageAbiOverride; 9849 } 9850 9851 @Override 9852 public String toString() { 9853 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9854 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9855 } 9856 9857 public ManifestDigest getManifestDigest() { 9858 if (verificationParams == null) { 9859 return null; 9860 } 9861 return verificationParams.getManifestDigest(); 9862 } 9863 9864 private int installLocationPolicy(PackageInfoLite pkgLite) { 9865 String packageName = pkgLite.packageName; 9866 int installLocation = pkgLite.installLocation; 9867 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9868 // reader 9869 synchronized (mPackages) { 9870 PackageParser.Package pkg = mPackages.get(packageName); 9871 if (pkg != null) { 9872 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9873 // Check for downgrading. 9874 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9875 try { 9876 checkDowngrade(pkg, pkgLite); 9877 } catch (PackageManagerException e) { 9878 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9879 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9880 } 9881 } 9882 // Check for updated system application. 9883 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9884 if (onSd) { 9885 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9886 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9887 } 9888 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9889 } else { 9890 if (onSd) { 9891 // Install flag overrides everything. 9892 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9893 } 9894 // If current upgrade specifies particular preference 9895 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9896 // Application explicitly specified internal. 9897 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9898 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9899 // App explictly prefers external. Let policy decide 9900 } else { 9901 // Prefer previous location 9902 if (isExternal(pkg)) { 9903 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9904 } 9905 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9906 } 9907 } 9908 } else { 9909 // Invalid install. Return error code 9910 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9911 } 9912 } 9913 } 9914 // All the special cases have been taken care of. 9915 // Return result based on recommended install location. 9916 if (onSd) { 9917 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9918 } 9919 return pkgLite.recommendedInstallLocation; 9920 } 9921 9922 /* 9923 * Invoke remote method to get package information and install 9924 * location values. Override install location based on default 9925 * policy if needed and then create install arguments based 9926 * on the install location. 9927 */ 9928 public void handleStartCopy() throws RemoteException { 9929 int ret = PackageManager.INSTALL_SUCCEEDED; 9930 9931 // If we're already staged, we've firmly committed to an install location 9932 if (origin.staged) { 9933 if (origin.file != null) { 9934 installFlags |= PackageManager.INSTALL_INTERNAL; 9935 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9936 } else if (origin.cid != null) { 9937 installFlags |= PackageManager.INSTALL_EXTERNAL; 9938 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9939 } else { 9940 throw new IllegalStateException("Invalid stage location"); 9941 } 9942 } 9943 9944 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9945 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9946 9947 PackageInfoLite pkgLite = null; 9948 9949 if (onInt && onSd) { 9950 // Check if both bits are set. 9951 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9952 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9953 } else { 9954 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9955 packageAbiOverride); 9956 9957 /* 9958 * If we have too little free space, try to free cache 9959 * before giving up. 9960 */ 9961 if (!origin.staged && pkgLite.recommendedInstallLocation 9962 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9963 // TODO: focus freeing disk space on the target device 9964 final StorageManager storage = StorageManager.from(mContext); 9965 final long lowThreshold = storage.getStorageLowBytes( 9966 Environment.getDataDirectory()); 9967 9968 final long sizeBytes = mContainerService.calculateInstalledSize( 9969 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9970 9971 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9972 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9973 installFlags, packageAbiOverride); 9974 } 9975 9976 /* 9977 * The cache free must have deleted the file we 9978 * downloaded to install. 9979 * 9980 * TODO: fix the "freeCache" call to not delete 9981 * the file we care about. 9982 */ 9983 if (pkgLite.recommendedInstallLocation 9984 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9985 pkgLite.recommendedInstallLocation 9986 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9987 } 9988 } 9989 } 9990 9991 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9992 int loc = pkgLite.recommendedInstallLocation; 9993 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9994 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9995 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9996 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9997 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9998 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9999 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10000 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10001 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10002 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10003 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10004 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10005 } else { 10006 // Override with defaults if needed. 10007 loc = installLocationPolicy(pkgLite); 10008 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10009 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10010 } else if (!onSd && !onInt) { 10011 // Override install location with flags 10012 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10013 // Set the flag to install on external media. 10014 installFlags |= PackageManager.INSTALL_EXTERNAL; 10015 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10016 } else { 10017 // Make sure the flag for installing on external 10018 // media is unset 10019 installFlags |= PackageManager.INSTALL_INTERNAL; 10020 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10021 } 10022 } 10023 } 10024 } 10025 10026 final InstallArgs args = createInstallArgs(this); 10027 mArgs = args; 10028 10029 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10030 /* 10031 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10032 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10033 */ 10034 int userIdentifier = getUser().getIdentifier(); 10035 if (userIdentifier == UserHandle.USER_ALL 10036 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10037 userIdentifier = UserHandle.USER_OWNER; 10038 } 10039 10040 /* 10041 * Determine if we have any installed package verifiers. If we 10042 * do, then we'll defer to them to verify the packages. 10043 */ 10044 final int requiredUid = mRequiredVerifierPackage == null ? -1 10045 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10046 if (!origin.existing && requiredUid != -1 10047 && isVerificationEnabled(userIdentifier, installFlags)) { 10048 final Intent verification = new Intent( 10049 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10050 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10051 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10052 PACKAGE_MIME_TYPE); 10053 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10054 10055 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10056 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10057 0 /* TODO: Which userId? */); 10058 10059 if (DEBUG_VERIFY) { 10060 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10061 + verification.toString() + " with " + pkgLite.verifiers.length 10062 + " optional verifiers"); 10063 } 10064 10065 final int verificationId = mPendingVerificationToken++; 10066 10067 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10068 10069 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10070 installerPackageName); 10071 10072 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10073 installFlags); 10074 10075 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10076 pkgLite.packageName); 10077 10078 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10079 pkgLite.versionCode); 10080 10081 if (verificationParams != null) { 10082 if (verificationParams.getVerificationURI() != null) { 10083 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10084 verificationParams.getVerificationURI()); 10085 } 10086 if (verificationParams.getOriginatingURI() != null) { 10087 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10088 verificationParams.getOriginatingURI()); 10089 } 10090 if (verificationParams.getReferrer() != null) { 10091 verification.putExtra(Intent.EXTRA_REFERRER, 10092 verificationParams.getReferrer()); 10093 } 10094 if (verificationParams.getOriginatingUid() >= 0) { 10095 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10096 verificationParams.getOriginatingUid()); 10097 } 10098 if (verificationParams.getInstallerUid() >= 0) { 10099 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10100 verificationParams.getInstallerUid()); 10101 } 10102 } 10103 10104 final PackageVerificationState verificationState = new PackageVerificationState( 10105 requiredUid, args); 10106 10107 mPendingVerification.append(verificationId, verificationState); 10108 10109 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10110 receivers, verificationState); 10111 10112 /* 10113 * If any sufficient verifiers were listed in the package 10114 * manifest, attempt to ask them. 10115 */ 10116 if (sufficientVerifiers != null) { 10117 final int N = sufficientVerifiers.size(); 10118 if (N == 0) { 10119 Slog.i(TAG, "Additional verifiers required, but none installed."); 10120 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10121 } else { 10122 for (int i = 0; i < N; i++) { 10123 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10124 10125 final Intent sufficientIntent = new Intent(verification); 10126 sufficientIntent.setComponent(verifierComponent); 10127 10128 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10129 } 10130 } 10131 } 10132 10133 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10134 mRequiredVerifierPackage, receivers); 10135 if (ret == PackageManager.INSTALL_SUCCEEDED 10136 && mRequiredVerifierPackage != null) { 10137 /* 10138 * Send the intent to the required verification agent, 10139 * but only start the verification timeout after the 10140 * target BroadcastReceivers have run. 10141 */ 10142 verification.setComponent(requiredVerifierComponent); 10143 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10144 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10145 new BroadcastReceiver() { 10146 @Override 10147 public void onReceive(Context context, Intent intent) { 10148 final Message msg = mHandler 10149 .obtainMessage(CHECK_PENDING_VERIFICATION); 10150 msg.arg1 = verificationId; 10151 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10152 } 10153 }, null, 0, null, null); 10154 10155 /* 10156 * We don't want the copy to proceed until verification 10157 * succeeds, so null out this field. 10158 */ 10159 mArgs = null; 10160 } 10161 } else { 10162 /* 10163 * No package verification is enabled, so immediately start 10164 * the remote call to initiate copy using temporary file. 10165 */ 10166 ret = args.copyApk(mContainerService, true); 10167 } 10168 } 10169 10170 mRet = ret; 10171 } 10172 10173 @Override 10174 void handleReturnCode() { 10175 // If mArgs is null, then MCS couldn't be reached. When it 10176 // reconnects, it will try again to install. At that point, this 10177 // will succeed. 10178 if (mArgs != null) { 10179 processPendingInstall(mArgs, mRet); 10180 } 10181 } 10182 10183 @Override 10184 void handleServiceError() { 10185 mArgs = createInstallArgs(this); 10186 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10187 } 10188 10189 public boolean isForwardLocked() { 10190 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10191 } 10192 } 10193 10194 /** 10195 * Used during creation of InstallArgs 10196 * 10197 * @param installFlags package installation flags 10198 * @return true if should be installed on external storage 10199 */ 10200 private static boolean installOnExternalAsec(int installFlags) { 10201 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10202 return false; 10203 } 10204 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10205 return true; 10206 } 10207 return false; 10208 } 10209 10210 /** 10211 * Used during creation of InstallArgs 10212 * 10213 * @param installFlags package installation flags 10214 * @return true if should be installed as forward locked 10215 */ 10216 private static boolean installForwardLocked(int installFlags) { 10217 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10218 } 10219 10220 private InstallArgs createInstallArgs(InstallParams params) { 10221 if (params.move != null) { 10222 return new MoveInstallArgs(params); 10223 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10224 return new AsecInstallArgs(params); 10225 } else { 10226 return new FileInstallArgs(params); 10227 } 10228 } 10229 10230 /** 10231 * Create args that describe an existing installed package. Typically used 10232 * when cleaning up old installs, or used as a move source. 10233 */ 10234 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10235 String resourcePath, String[] instructionSets) { 10236 final boolean isInAsec; 10237 if (installOnExternalAsec(installFlags)) { 10238 /* Apps on SD card are always in ASEC containers. */ 10239 isInAsec = true; 10240 } else if (installForwardLocked(installFlags) 10241 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10242 /* 10243 * Forward-locked apps are only in ASEC containers if they're the 10244 * new style 10245 */ 10246 isInAsec = true; 10247 } else { 10248 isInAsec = false; 10249 } 10250 10251 if (isInAsec) { 10252 return new AsecInstallArgs(codePath, instructionSets, 10253 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10254 } else { 10255 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10256 } 10257 } 10258 10259 static abstract class InstallArgs { 10260 /** @see InstallParams#origin */ 10261 final OriginInfo origin; 10262 /** @see InstallParams#move */ 10263 final MoveInfo move; 10264 10265 final IPackageInstallObserver2 observer; 10266 // Always refers to PackageManager flags only 10267 final int installFlags; 10268 final String installerPackageName; 10269 final String volumeUuid; 10270 final ManifestDigest manifestDigest; 10271 final UserHandle user; 10272 final String abiOverride; 10273 10274 // The list of instruction sets supported by this app. This is currently 10275 // only used during the rmdex() phase to clean up resources. We can get rid of this 10276 // if we move dex files under the common app path. 10277 /* nullable */ String[] instructionSets; 10278 10279 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10280 int installFlags, String installerPackageName, String volumeUuid, 10281 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10282 String abiOverride) { 10283 this.origin = origin; 10284 this.move = move; 10285 this.installFlags = installFlags; 10286 this.observer = observer; 10287 this.installerPackageName = installerPackageName; 10288 this.volumeUuid = volumeUuid; 10289 this.manifestDigest = manifestDigest; 10290 this.user = user; 10291 this.instructionSets = instructionSets; 10292 this.abiOverride = abiOverride; 10293 } 10294 10295 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10296 abstract int doPreInstall(int status); 10297 10298 /** 10299 * Rename package into final resting place. All paths on the given 10300 * scanned package should be updated to reflect the rename. 10301 */ 10302 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10303 abstract int doPostInstall(int status, int uid); 10304 10305 /** @see PackageSettingBase#codePathString */ 10306 abstract String getCodePath(); 10307 /** @see PackageSettingBase#resourcePathString */ 10308 abstract String getResourcePath(); 10309 10310 // Need installer lock especially for dex file removal. 10311 abstract void cleanUpResourcesLI(); 10312 abstract boolean doPostDeleteLI(boolean delete); 10313 10314 /** 10315 * Called before the source arguments are copied. This is used mostly 10316 * for MoveParams when it needs to read the source file to put it in the 10317 * destination. 10318 */ 10319 int doPreCopy() { 10320 return PackageManager.INSTALL_SUCCEEDED; 10321 } 10322 10323 /** 10324 * Called after the source arguments are copied. This is used mostly for 10325 * MoveParams when it needs to read the source file to put it in the 10326 * destination. 10327 * 10328 * @return 10329 */ 10330 int doPostCopy(int uid) { 10331 return PackageManager.INSTALL_SUCCEEDED; 10332 } 10333 10334 protected boolean isFwdLocked() { 10335 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10336 } 10337 10338 protected boolean isExternalAsec() { 10339 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10340 } 10341 10342 UserHandle getUser() { 10343 return user; 10344 } 10345 } 10346 10347 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10348 if (!allCodePaths.isEmpty()) { 10349 if (instructionSets == null) { 10350 throw new IllegalStateException("instructionSet == null"); 10351 } 10352 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10353 for (String codePath : allCodePaths) { 10354 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10355 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10356 if (retCode < 0) { 10357 Slog.w(TAG, "Couldn't remove dex file for package: " 10358 + " at location " + codePath + ", retcode=" + retCode); 10359 // we don't consider this to be a failure of the core package deletion 10360 } 10361 } 10362 } 10363 } 10364 } 10365 10366 /** 10367 * Logic to handle installation of non-ASEC applications, including copying 10368 * and renaming logic. 10369 */ 10370 class FileInstallArgs extends InstallArgs { 10371 private File codeFile; 10372 private File resourceFile; 10373 10374 // Example topology: 10375 // /data/app/com.example/base.apk 10376 // /data/app/com.example/split_foo.apk 10377 // /data/app/com.example/lib/arm/libfoo.so 10378 // /data/app/com.example/lib/arm64/libfoo.so 10379 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10380 10381 /** New install */ 10382 FileInstallArgs(InstallParams params) { 10383 super(params.origin, params.move, params.observer, params.installFlags, 10384 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10385 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10386 if (isFwdLocked()) { 10387 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10388 } 10389 } 10390 10391 /** Existing install */ 10392 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10393 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10394 null); 10395 this.codeFile = (codePath != null) ? new File(codePath) : null; 10396 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10397 } 10398 10399 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10400 if (origin.staged) { 10401 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10402 codeFile = origin.file; 10403 resourceFile = origin.file; 10404 return PackageManager.INSTALL_SUCCEEDED; 10405 } 10406 10407 try { 10408 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10409 codeFile = tempDir; 10410 resourceFile = tempDir; 10411 } catch (IOException e) { 10412 Slog.w(TAG, "Failed to create copy file: " + e); 10413 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10414 } 10415 10416 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10417 @Override 10418 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10419 if (!FileUtils.isValidExtFilename(name)) { 10420 throw new IllegalArgumentException("Invalid filename: " + name); 10421 } 10422 try { 10423 final File file = new File(codeFile, name); 10424 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10425 O_RDWR | O_CREAT, 0644); 10426 Os.chmod(file.getAbsolutePath(), 0644); 10427 return new ParcelFileDescriptor(fd); 10428 } catch (ErrnoException e) { 10429 throw new RemoteException("Failed to open: " + e.getMessage()); 10430 } 10431 } 10432 }; 10433 10434 int ret = PackageManager.INSTALL_SUCCEEDED; 10435 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10436 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10437 Slog.e(TAG, "Failed to copy package"); 10438 return ret; 10439 } 10440 10441 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10442 NativeLibraryHelper.Handle handle = null; 10443 try { 10444 handle = NativeLibraryHelper.Handle.create(codeFile); 10445 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10446 abiOverride); 10447 } catch (IOException e) { 10448 Slog.e(TAG, "Copying native libraries failed", e); 10449 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10450 } finally { 10451 IoUtils.closeQuietly(handle); 10452 } 10453 10454 return ret; 10455 } 10456 10457 int doPreInstall(int status) { 10458 if (status != PackageManager.INSTALL_SUCCEEDED) { 10459 cleanUp(); 10460 } 10461 return status; 10462 } 10463 10464 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10465 if (status != PackageManager.INSTALL_SUCCEEDED) { 10466 cleanUp(); 10467 return false; 10468 } 10469 10470 final File targetDir = codeFile.getParentFile(); 10471 final File beforeCodeFile = codeFile; 10472 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10473 10474 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10475 try { 10476 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10477 } catch (ErrnoException e) { 10478 Slog.w(TAG, "Failed to rename", e); 10479 return false; 10480 } 10481 10482 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10483 Slog.w(TAG, "Failed to restorecon"); 10484 return false; 10485 } 10486 10487 // Reflect the rename internally 10488 codeFile = afterCodeFile; 10489 resourceFile = afterCodeFile; 10490 10491 // Reflect the rename in scanned details 10492 pkg.codePath = afterCodeFile.getAbsolutePath(); 10493 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10494 pkg.baseCodePath); 10495 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10496 pkg.splitCodePaths); 10497 10498 // Reflect the rename in app info 10499 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10500 pkg.applicationInfo.setCodePath(pkg.codePath); 10501 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10502 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10503 pkg.applicationInfo.setResourcePath(pkg.codePath); 10504 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10505 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10506 10507 return true; 10508 } 10509 10510 int doPostInstall(int status, int uid) { 10511 if (status != PackageManager.INSTALL_SUCCEEDED) { 10512 cleanUp(); 10513 } 10514 return status; 10515 } 10516 10517 @Override 10518 String getCodePath() { 10519 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10520 } 10521 10522 @Override 10523 String getResourcePath() { 10524 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10525 } 10526 10527 private boolean cleanUp() { 10528 if (codeFile == null || !codeFile.exists()) { 10529 return false; 10530 } 10531 10532 if (codeFile.isDirectory()) { 10533 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10534 } else { 10535 codeFile.delete(); 10536 } 10537 10538 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10539 resourceFile.delete(); 10540 } 10541 10542 return true; 10543 } 10544 10545 void cleanUpResourcesLI() { 10546 // Try enumerating all code paths before deleting 10547 List<String> allCodePaths = Collections.EMPTY_LIST; 10548 if (codeFile != null && codeFile.exists()) { 10549 try { 10550 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10551 allCodePaths = pkg.getAllCodePaths(); 10552 } catch (PackageParserException e) { 10553 // Ignored; we tried our best 10554 } 10555 } 10556 10557 cleanUp(); 10558 removeDexFiles(allCodePaths, instructionSets); 10559 } 10560 10561 boolean doPostDeleteLI(boolean delete) { 10562 // XXX err, shouldn't we respect the delete flag? 10563 cleanUpResourcesLI(); 10564 return true; 10565 } 10566 } 10567 10568 private boolean isAsecExternal(String cid) { 10569 final String asecPath = PackageHelper.getSdFilesystem(cid); 10570 return !asecPath.startsWith(mAsecInternalPath); 10571 } 10572 10573 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10574 PackageManagerException { 10575 if (copyRet < 0) { 10576 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10577 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10578 throw new PackageManagerException(copyRet, message); 10579 } 10580 } 10581 } 10582 10583 /** 10584 * Extract the MountService "container ID" from the full code path of an 10585 * .apk. 10586 */ 10587 static String cidFromCodePath(String fullCodePath) { 10588 int eidx = fullCodePath.lastIndexOf("/"); 10589 String subStr1 = fullCodePath.substring(0, eidx); 10590 int sidx = subStr1.lastIndexOf("/"); 10591 return subStr1.substring(sidx+1, eidx); 10592 } 10593 10594 /** 10595 * Logic to handle installation of ASEC applications, including copying and 10596 * renaming logic. 10597 */ 10598 class AsecInstallArgs extends InstallArgs { 10599 static final String RES_FILE_NAME = "pkg.apk"; 10600 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10601 10602 String cid; 10603 String packagePath; 10604 String resourcePath; 10605 10606 /** New install */ 10607 AsecInstallArgs(InstallParams params) { 10608 super(params.origin, params.move, params.observer, params.installFlags, 10609 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10610 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10611 } 10612 10613 /** Existing install */ 10614 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10615 boolean isExternal, boolean isForwardLocked) { 10616 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10617 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10618 instructionSets, null); 10619 // Hackily pretend we're still looking at a full code path 10620 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10621 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10622 } 10623 10624 // Extract cid from fullCodePath 10625 int eidx = fullCodePath.lastIndexOf("/"); 10626 String subStr1 = fullCodePath.substring(0, eidx); 10627 int sidx = subStr1.lastIndexOf("/"); 10628 cid = subStr1.substring(sidx+1, eidx); 10629 setMountPath(subStr1); 10630 } 10631 10632 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10633 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10634 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10635 instructionSets, null); 10636 this.cid = cid; 10637 setMountPath(PackageHelper.getSdDir(cid)); 10638 } 10639 10640 void createCopyFile() { 10641 cid = mInstallerService.allocateExternalStageCidLegacy(); 10642 } 10643 10644 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10645 if (origin.staged) { 10646 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10647 cid = origin.cid; 10648 setMountPath(PackageHelper.getSdDir(cid)); 10649 return PackageManager.INSTALL_SUCCEEDED; 10650 } 10651 10652 if (temp) { 10653 createCopyFile(); 10654 } else { 10655 /* 10656 * Pre-emptively destroy the container since it's destroyed if 10657 * copying fails due to it existing anyway. 10658 */ 10659 PackageHelper.destroySdDir(cid); 10660 } 10661 10662 final String newMountPath = imcs.copyPackageToContainer( 10663 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10664 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10665 10666 if (newMountPath != null) { 10667 setMountPath(newMountPath); 10668 return PackageManager.INSTALL_SUCCEEDED; 10669 } else { 10670 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10671 } 10672 } 10673 10674 @Override 10675 String getCodePath() { 10676 return packagePath; 10677 } 10678 10679 @Override 10680 String getResourcePath() { 10681 return resourcePath; 10682 } 10683 10684 int doPreInstall(int status) { 10685 if (status != PackageManager.INSTALL_SUCCEEDED) { 10686 // Destroy container 10687 PackageHelper.destroySdDir(cid); 10688 } else { 10689 boolean mounted = PackageHelper.isContainerMounted(cid); 10690 if (!mounted) { 10691 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10692 Process.SYSTEM_UID); 10693 if (newMountPath != null) { 10694 setMountPath(newMountPath); 10695 } else { 10696 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10697 } 10698 } 10699 } 10700 return status; 10701 } 10702 10703 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10704 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10705 String newMountPath = null; 10706 if (PackageHelper.isContainerMounted(cid)) { 10707 // Unmount the container 10708 if (!PackageHelper.unMountSdDir(cid)) { 10709 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10710 return false; 10711 } 10712 } 10713 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10714 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10715 " which might be stale. Will try to clean up."); 10716 // Clean up the stale container and proceed to recreate. 10717 if (!PackageHelper.destroySdDir(newCacheId)) { 10718 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10719 return false; 10720 } 10721 // Successfully cleaned up stale container. Try to rename again. 10722 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10723 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10724 + " inspite of cleaning it up."); 10725 return false; 10726 } 10727 } 10728 if (!PackageHelper.isContainerMounted(newCacheId)) { 10729 Slog.w(TAG, "Mounting container " + newCacheId); 10730 newMountPath = PackageHelper.mountSdDir(newCacheId, 10731 getEncryptKey(), Process.SYSTEM_UID); 10732 } else { 10733 newMountPath = PackageHelper.getSdDir(newCacheId); 10734 } 10735 if (newMountPath == null) { 10736 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10737 return false; 10738 } 10739 Log.i(TAG, "Succesfully renamed " + cid + 10740 " to " + newCacheId + 10741 " at new path: " + newMountPath); 10742 cid = newCacheId; 10743 10744 final File beforeCodeFile = new File(packagePath); 10745 setMountPath(newMountPath); 10746 final File afterCodeFile = new File(packagePath); 10747 10748 // Reflect the rename in scanned details 10749 pkg.codePath = afterCodeFile.getAbsolutePath(); 10750 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10751 pkg.baseCodePath); 10752 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10753 pkg.splitCodePaths); 10754 10755 // Reflect the rename in app info 10756 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10757 pkg.applicationInfo.setCodePath(pkg.codePath); 10758 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10759 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10760 pkg.applicationInfo.setResourcePath(pkg.codePath); 10761 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10762 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10763 10764 return true; 10765 } 10766 10767 private void setMountPath(String mountPath) { 10768 final File mountFile = new File(mountPath); 10769 10770 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10771 if (monolithicFile.exists()) { 10772 packagePath = monolithicFile.getAbsolutePath(); 10773 if (isFwdLocked()) { 10774 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10775 } else { 10776 resourcePath = packagePath; 10777 } 10778 } else { 10779 packagePath = mountFile.getAbsolutePath(); 10780 resourcePath = packagePath; 10781 } 10782 } 10783 10784 int doPostInstall(int status, int uid) { 10785 if (status != PackageManager.INSTALL_SUCCEEDED) { 10786 cleanUp(); 10787 } else { 10788 final int groupOwner; 10789 final String protectedFile; 10790 if (isFwdLocked()) { 10791 groupOwner = UserHandle.getSharedAppGid(uid); 10792 protectedFile = RES_FILE_NAME; 10793 } else { 10794 groupOwner = -1; 10795 protectedFile = null; 10796 } 10797 10798 if (uid < Process.FIRST_APPLICATION_UID 10799 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10800 Slog.e(TAG, "Failed to finalize " + cid); 10801 PackageHelper.destroySdDir(cid); 10802 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10803 } 10804 10805 boolean mounted = PackageHelper.isContainerMounted(cid); 10806 if (!mounted) { 10807 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10808 } 10809 } 10810 return status; 10811 } 10812 10813 private void cleanUp() { 10814 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10815 10816 // Destroy secure container 10817 PackageHelper.destroySdDir(cid); 10818 } 10819 10820 private List<String> getAllCodePaths() { 10821 final File codeFile = new File(getCodePath()); 10822 if (codeFile != null && codeFile.exists()) { 10823 try { 10824 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10825 return pkg.getAllCodePaths(); 10826 } catch (PackageParserException e) { 10827 // Ignored; we tried our best 10828 } 10829 } 10830 return Collections.EMPTY_LIST; 10831 } 10832 10833 void cleanUpResourcesLI() { 10834 // Enumerate all code paths before deleting 10835 cleanUpResourcesLI(getAllCodePaths()); 10836 } 10837 10838 private void cleanUpResourcesLI(List<String> allCodePaths) { 10839 cleanUp(); 10840 removeDexFiles(allCodePaths, instructionSets); 10841 } 10842 10843 String getPackageName() { 10844 return getAsecPackageName(cid); 10845 } 10846 10847 boolean doPostDeleteLI(boolean delete) { 10848 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10849 final List<String> allCodePaths = getAllCodePaths(); 10850 boolean mounted = PackageHelper.isContainerMounted(cid); 10851 if (mounted) { 10852 // Unmount first 10853 if (PackageHelper.unMountSdDir(cid)) { 10854 mounted = false; 10855 } 10856 } 10857 if (!mounted && delete) { 10858 cleanUpResourcesLI(allCodePaths); 10859 } 10860 return !mounted; 10861 } 10862 10863 @Override 10864 int doPreCopy() { 10865 if (isFwdLocked()) { 10866 if (!PackageHelper.fixSdPermissions(cid, 10867 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10868 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10869 } 10870 } 10871 10872 return PackageManager.INSTALL_SUCCEEDED; 10873 } 10874 10875 @Override 10876 int doPostCopy(int uid) { 10877 if (isFwdLocked()) { 10878 if (uid < Process.FIRST_APPLICATION_UID 10879 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10880 RES_FILE_NAME)) { 10881 Slog.e(TAG, "Failed to finalize " + cid); 10882 PackageHelper.destroySdDir(cid); 10883 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10884 } 10885 } 10886 10887 return PackageManager.INSTALL_SUCCEEDED; 10888 } 10889 } 10890 10891 /** 10892 * Logic to handle movement of existing installed applications. 10893 */ 10894 class MoveInstallArgs extends InstallArgs { 10895 private File codeFile; 10896 private File resourceFile; 10897 10898 /** New install */ 10899 MoveInstallArgs(InstallParams params) { 10900 super(params.origin, params.move, params.observer, params.installFlags, 10901 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10902 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10903 } 10904 10905 int copyApk(IMediaContainerService imcs, boolean temp) { 10906 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10907 + move.fromUuid + " to " + move.toUuid); 10908 synchronized (mInstaller) { 10909 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10910 move.dataAppName, move.appId, move.seinfo) != 0) { 10911 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10912 } 10913 } 10914 10915 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10916 resourceFile = codeFile; 10917 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10918 10919 return PackageManager.INSTALL_SUCCEEDED; 10920 } 10921 10922 int doPreInstall(int status) { 10923 if (status != PackageManager.INSTALL_SUCCEEDED) { 10924 cleanUp(); 10925 } 10926 return status; 10927 } 10928 10929 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10930 if (status != PackageManager.INSTALL_SUCCEEDED) { 10931 cleanUp(); 10932 return false; 10933 } 10934 10935 // Reflect the move in app info 10936 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10937 pkg.applicationInfo.setCodePath(pkg.codePath); 10938 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10939 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10940 pkg.applicationInfo.setResourcePath(pkg.codePath); 10941 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10942 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10943 10944 return true; 10945 } 10946 10947 int doPostInstall(int status, int uid) { 10948 if (status != PackageManager.INSTALL_SUCCEEDED) { 10949 cleanUp(); 10950 } 10951 return status; 10952 } 10953 10954 @Override 10955 String getCodePath() { 10956 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10957 } 10958 10959 @Override 10960 String getResourcePath() { 10961 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10962 } 10963 10964 private boolean cleanUp() { 10965 if (codeFile == null || !codeFile.exists()) { 10966 return false; 10967 } 10968 10969 if (codeFile.isDirectory()) { 10970 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10971 } else { 10972 codeFile.delete(); 10973 } 10974 10975 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10976 resourceFile.delete(); 10977 } 10978 10979 return true; 10980 } 10981 10982 void cleanUpResourcesLI() { 10983 cleanUp(); 10984 } 10985 10986 boolean doPostDeleteLI(boolean delete) { 10987 // XXX err, shouldn't we respect the delete flag? 10988 cleanUpResourcesLI(); 10989 return true; 10990 } 10991 } 10992 10993 static String getAsecPackageName(String packageCid) { 10994 int idx = packageCid.lastIndexOf("-"); 10995 if (idx == -1) { 10996 return packageCid; 10997 } 10998 return packageCid.substring(0, idx); 10999 } 11000 11001 // Utility method used to create code paths based on package name and available index. 11002 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11003 String idxStr = ""; 11004 int idx = 1; 11005 // Fall back to default value of idx=1 if prefix is not 11006 // part of oldCodePath 11007 if (oldCodePath != null) { 11008 String subStr = oldCodePath; 11009 // Drop the suffix right away 11010 if (suffix != null && subStr.endsWith(suffix)) { 11011 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11012 } 11013 // If oldCodePath already contains prefix find out the 11014 // ending index to either increment or decrement. 11015 int sidx = subStr.lastIndexOf(prefix); 11016 if (sidx != -1) { 11017 subStr = subStr.substring(sidx + prefix.length()); 11018 if (subStr != null) { 11019 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11020 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11021 } 11022 try { 11023 idx = Integer.parseInt(subStr); 11024 if (idx <= 1) { 11025 idx++; 11026 } else { 11027 idx--; 11028 } 11029 } catch(NumberFormatException e) { 11030 } 11031 } 11032 } 11033 } 11034 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11035 return prefix + idxStr; 11036 } 11037 11038 private File getNextCodePath(File targetDir, String packageName) { 11039 int suffix = 1; 11040 File result; 11041 do { 11042 result = new File(targetDir, packageName + "-" + suffix); 11043 suffix++; 11044 } while (result.exists()); 11045 return result; 11046 } 11047 11048 // Utility method that returns the relative package path with respect 11049 // to the installation directory. Like say for /data/data/com.test-1.apk 11050 // string com.test-1 is returned. 11051 static String deriveCodePathName(String codePath) { 11052 if (codePath == null) { 11053 return null; 11054 } 11055 final File codeFile = new File(codePath); 11056 final String name = codeFile.getName(); 11057 if (codeFile.isDirectory()) { 11058 return name; 11059 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11060 final int lastDot = name.lastIndexOf('.'); 11061 return name.substring(0, lastDot); 11062 } else { 11063 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11064 return null; 11065 } 11066 } 11067 11068 class PackageInstalledInfo { 11069 String name; 11070 int uid; 11071 // The set of users that originally had this package installed. 11072 int[] origUsers; 11073 // The set of users that now have this package installed. 11074 int[] newUsers; 11075 PackageParser.Package pkg; 11076 int returnCode; 11077 String returnMsg; 11078 PackageRemovedInfo removedInfo; 11079 11080 public void setError(int code, String msg) { 11081 returnCode = code; 11082 returnMsg = msg; 11083 Slog.w(TAG, msg); 11084 } 11085 11086 public void setError(String msg, PackageParserException e) { 11087 returnCode = e.error; 11088 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11089 Slog.w(TAG, msg, e); 11090 } 11091 11092 public void setError(String msg, PackageManagerException e) { 11093 returnCode = e.error; 11094 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11095 Slog.w(TAG, msg, e); 11096 } 11097 11098 // In some error cases we want to convey more info back to the observer 11099 String origPackage; 11100 String origPermission; 11101 } 11102 11103 /* 11104 * Install a non-existing package. 11105 */ 11106 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11107 UserHandle user, String installerPackageName, String volumeUuid, 11108 PackageInstalledInfo res) { 11109 // Remember this for later, in case we need to rollback this install 11110 String pkgName = pkg.packageName; 11111 11112 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11113 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11114 UserHandle.USER_OWNER).exists(); 11115 synchronized(mPackages) { 11116 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11117 // A package with the same name is already installed, though 11118 // it has been renamed to an older name. The package we 11119 // are trying to install should be installed as an update to 11120 // the existing one, but that has not been requested, so bail. 11121 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11122 + " without first uninstalling package running as " 11123 + mSettings.mRenamedPackages.get(pkgName)); 11124 return; 11125 } 11126 if (mPackages.containsKey(pkgName)) { 11127 // Don't allow installation over an existing package with the same name. 11128 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11129 + " without first uninstalling."); 11130 return; 11131 } 11132 } 11133 11134 try { 11135 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11136 System.currentTimeMillis(), user); 11137 11138 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11139 // delete the partially installed application. the data directory will have to be 11140 // restored if it was already existing 11141 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11142 // remove package from internal structures. Note that we want deletePackageX to 11143 // delete the package data and cache directories that it created in 11144 // scanPackageLocked, unless those directories existed before we even tried to 11145 // install. 11146 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11147 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11148 res.removedInfo, true); 11149 } 11150 11151 } catch (PackageManagerException e) { 11152 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11153 } 11154 } 11155 11156 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11157 // Can't rotate keys during boot or if sharedUser. 11158 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 11159 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11160 return false; 11161 } 11162 // app is using upgradeKeySets; make sure all are valid 11163 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11164 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11165 for (int i = 0; i < upgradeKeySets.length; i++) { 11166 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11167 Slog.wtf(TAG, "Package " 11168 + (oldPs.name != null ? oldPs.name : "<null>") 11169 + " contains upgrade-key-set reference to unknown key-set: " 11170 + upgradeKeySets[i] 11171 + " reverting to signatures check."); 11172 return false; 11173 } 11174 } 11175 return true; 11176 } 11177 11178 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11179 // Upgrade keysets are being used. Determine if new package has a superset of the 11180 // required keys. 11181 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11182 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11183 for (int i = 0; i < upgradeKeySets.length; i++) { 11184 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11185 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11186 return true; 11187 } 11188 } 11189 return false; 11190 } 11191 11192 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11193 UserHandle user, String installerPackageName, String volumeUuid, 11194 PackageInstalledInfo res) { 11195 final PackageParser.Package oldPackage; 11196 final String pkgName = pkg.packageName; 11197 final int[] allUsers; 11198 final boolean[] perUserInstalled; 11199 final boolean weFroze; 11200 11201 // First find the old package info and check signatures 11202 synchronized(mPackages) { 11203 oldPackage = mPackages.get(pkgName); 11204 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11205 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11206 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11207 if(!checkUpgradeKeySetLP(ps, pkg)) { 11208 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11209 "New package not signed by keys specified by upgrade-keysets: " 11210 + pkgName); 11211 return; 11212 } 11213 } else { 11214 // default to original signature matching 11215 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11216 != PackageManager.SIGNATURE_MATCH) { 11217 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11218 "New package has a different signature: " + pkgName); 11219 return; 11220 } 11221 } 11222 11223 // In case of rollback, remember per-user/profile install state 11224 allUsers = sUserManager.getUserIds(); 11225 perUserInstalled = new boolean[allUsers.length]; 11226 for (int i = 0; i < allUsers.length; i++) { 11227 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11228 } 11229 11230 // Mark the app as frozen to prevent launching during the upgrade 11231 // process, and then kill all running instances 11232 if (!ps.frozen) { 11233 ps.frozen = true; 11234 weFroze = true; 11235 } else { 11236 weFroze = false; 11237 } 11238 } 11239 11240 // Now that we're guarded by frozen state, kill app during upgrade 11241 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11242 11243 try { 11244 boolean sysPkg = (isSystemApp(oldPackage)); 11245 if (sysPkg) { 11246 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11247 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11248 } else { 11249 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11250 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11251 } 11252 } finally { 11253 // Regardless of success or failure of upgrade steps above, always 11254 // unfreeze the package if we froze it 11255 if (weFroze) { 11256 unfreezePackage(pkgName); 11257 } 11258 } 11259 } 11260 11261 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11262 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11263 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11264 String volumeUuid, PackageInstalledInfo res) { 11265 String pkgName = deletedPackage.packageName; 11266 boolean deletedPkg = true; 11267 boolean updatedSettings = false; 11268 11269 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11270 + deletedPackage); 11271 long origUpdateTime; 11272 if (pkg.mExtras != null) { 11273 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11274 } else { 11275 origUpdateTime = 0; 11276 } 11277 11278 // First delete the existing package while retaining the data directory 11279 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11280 res.removedInfo, true)) { 11281 // If the existing package wasn't successfully deleted 11282 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11283 deletedPkg = false; 11284 } else { 11285 // Successfully deleted the old package; proceed with replace. 11286 11287 // If deleted package lived in a container, give users a chance to 11288 // relinquish resources before killing. 11289 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11290 if (DEBUG_INSTALL) { 11291 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11292 } 11293 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11294 final ArrayList<String> pkgList = new ArrayList<String>(1); 11295 pkgList.add(deletedPackage.applicationInfo.packageName); 11296 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11297 } 11298 11299 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11300 try { 11301 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11302 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11303 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11304 perUserInstalled, res, user); 11305 updatedSettings = true; 11306 } catch (PackageManagerException e) { 11307 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11308 } 11309 } 11310 11311 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11312 // remove package from internal structures. Note that we want deletePackageX to 11313 // delete the package data and cache directories that it created in 11314 // scanPackageLocked, unless those directories existed before we even tried to 11315 // install. 11316 if(updatedSettings) { 11317 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11318 deletePackageLI( 11319 pkgName, null, true, allUsers, perUserInstalled, 11320 PackageManager.DELETE_KEEP_DATA, 11321 res.removedInfo, true); 11322 } 11323 // Since we failed to install the new package we need to restore the old 11324 // package that we deleted. 11325 if (deletedPkg) { 11326 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11327 File restoreFile = new File(deletedPackage.codePath); 11328 // Parse old package 11329 boolean oldExternal = isExternal(deletedPackage); 11330 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11331 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11332 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11333 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11334 try { 11335 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11336 } catch (PackageManagerException e) { 11337 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11338 + e.getMessage()); 11339 return; 11340 } 11341 // Restore of old package succeeded. Update permissions. 11342 // writer 11343 synchronized (mPackages) { 11344 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11345 UPDATE_PERMISSIONS_ALL); 11346 // can downgrade to reader 11347 mSettings.writeLPr(); 11348 } 11349 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11350 } 11351 } 11352 } 11353 11354 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11355 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11356 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11357 String volumeUuid, PackageInstalledInfo res) { 11358 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11359 + ", old=" + deletedPackage); 11360 boolean disabledSystem = false; 11361 boolean updatedSettings = false; 11362 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11363 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11364 != 0) { 11365 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11366 } 11367 String packageName = deletedPackage.packageName; 11368 if (packageName == null) { 11369 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11370 "Attempt to delete null packageName."); 11371 return; 11372 } 11373 PackageParser.Package oldPkg; 11374 PackageSetting oldPkgSetting; 11375 // reader 11376 synchronized (mPackages) { 11377 oldPkg = mPackages.get(packageName); 11378 oldPkgSetting = mSettings.mPackages.get(packageName); 11379 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11380 (oldPkgSetting == null)) { 11381 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11382 "Couldn't find package:" + packageName + " information"); 11383 return; 11384 } 11385 } 11386 11387 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11388 res.removedInfo.removedPackage = packageName; 11389 // Remove existing system package 11390 removePackageLI(oldPkgSetting, true); 11391 // writer 11392 synchronized (mPackages) { 11393 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11394 if (!disabledSystem && deletedPackage != null) { 11395 // We didn't need to disable the .apk as a current system package, 11396 // which means we are replacing another update that is already 11397 // installed. We need to make sure to delete the older one's .apk. 11398 res.removedInfo.args = createInstallArgsForExisting(0, 11399 deletedPackage.applicationInfo.getCodePath(), 11400 deletedPackage.applicationInfo.getResourcePath(), 11401 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11402 } else { 11403 res.removedInfo.args = null; 11404 } 11405 } 11406 11407 // Successfully disabled the old package. Now proceed with re-installation 11408 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11409 11410 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11411 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11412 11413 PackageParser.Package newPackage = null; 11414 try { 11415 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11416 if (newPackage.mExtras != null) { 11417 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11418 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11419 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11420 11421 // is the update attempting to change shared user? that isn't going to work... 11422 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11423 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11424 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11425 + " to " + newPkgSetting.sharedUser); 11426 updatedSettings = true; 11427 } 11428 } 11429 11430 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11431 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11432 perUserInstalled, res, user); 11433 updatedSettings = true; 11434 } 11435 11436 } catch (PackageManagerException e) { 11437 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11438 } 11439 11440 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11441 // Re installation failed. Restore old information 11442 // Remove new pkg information 11443 if (newPackage != null) { 11444 removeInstalledPackageLI(newPackage, true); 11445 } 11446 // Add back the old system package 11447 try { 11448 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11449 } catch (PackageManagerException e) { 11450 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11451 } 11452 // Restore the old system information in Settings 11453 synchronized (mPackages) { 11454 if (disabledSystem) { 11455 mSettings.enableSystemPackageLPw(packageName); 11456 } 11457 if (updatedSettings) { 11458 mSettings.setInstallerPackageName(packageName, 11459 oldPkgSetting.installerPackageName); 11460 } 11461 mSettings.writeLPr(); 11462 } 11463 } 11464 } 11465 11466 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11467 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11468 UserHandle user) { 11469 String pkgName = newPackage.packageName; 11470 synchronized (mPackages) { 11471 //write settings. the installStatus will be incomplete at this stage. 11472 //note that the new package setting would have already been 11473 //added to mPackages. It hasn't been persisted yet. 11474 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11475 mSettings.writeLPr(); 11476 } 11477 11478 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11479 11480 synchronized (mPackages) { 11481 updatePermissionsLPw(newPackage.packageName, newPackage, 11482 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11483 ? UPDATE_PERMISSIONS_ALL : 0)); 11484 // For system-bundled packages, we assume that installing an upgraded version 11485 // of the package implies that the user actually wants to run that new code, 11486 // so we enable the package. 11487 PackageSetting ps = mSettings.mPackages.get(pkgName); 11488 if (ps != null) { 11489 if (isSystemApp(newPackage)) { 11490 // NB: implicit assumption that system package upgrades apply to all users 11491 if (DEBUG_INSTALL) { 11492 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11493 } 11494 if (res.origUsers != null) { 11495 for (int userHandle : res.origUsers) { 11496 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11497 userHandle, installerPackageName); 11498 } 11499 } 11500 // Also convey the prior install/uninstall state 11501 if (allUsers != null && perUserInstalled != null) { 11502 for (int i = 0; i < allUsers.length; i++) { 11503 if (DEBUG_INSTALL) { 11504 Slog.d(TAG, " user " + allUsers[i] 11505 + " => " + perUserInstalled[i]); 11506 } 11507 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11508 } 11509 // these install state changes will be persisted in the 11510 // upcoming call to mSettings.writeLPr(). 11511 } 11512 } 11513 // It's implied that when a user requests installation, they want the app to be 11514 // installed and enabled. 11515 int userId = user.getIdentifier(); 11516 if (userId != UserHandle.USER_ALL) { 11517 ps.setInstalled(true, userId); 11518 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11519 } 11520 } 11521 res.name = pkgName; 11522 res.uid = newPackage.applicationInfo.uid; 11523 res.pkg = newPackage; 11524 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11525 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11526 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11527 //to update install status 11528 mSettings.writeLPr(); 11529 } 11530 } 11531 11532 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11533 final int installFlags = args.installFlags; 11534 final String installerPackageName = args.installerPackageName; 11535 final String volumeUuid = args.volumeUuid; 11536 final File tmpPackageFile = new File(args.getCodePath()); 11537 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11538 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11539 || (args.volumeUuid != null)); 11540 boolean replace = false; 11541 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11542 if (args.move != null) { 11543 // moving a complete application; perfom an initial scan on the new install location 11544 scanFlags |= SCAN_INITIAL; 11545 } 11546 // Result object to be returned 11547 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11548 11549 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11550 // Retrieve PackageSettings and parse package 11551 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11552 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11553 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11554 PackageParser pp = new PackageParser(); 11555 pp.setSeparateProcesses(mSeparateProcesses); 11556 pp.setDisplayMetrics(mMetrics); 11557 11558 final PackageParser.Package pkg; 11559 try { 11560 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11561 } catch (PackageParserException e) { 11562 res.setError("Failed parse during installPackageLI", e); 11563 return; 11564 } 11565 11566 // Mark that we have an install time CPU ABI override. 11567 pkg.cpuAbiOverride = args.abiOverride; 11568 11569 String pkgName = res.name = pkg.packageName; 11570 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11571 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11572 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11573 return; 11574 } 11575 } 11576 11577 try { 11578 pp.collectCertificates(pkg, parseFlags); 11579 pp.collectManifestDigest(pkg); 11580 } catch (PackageParserException e) { 11581 res.setError("Failed collect during installPackageLI", e); 11582 return; 11583 } 11584 11585 /* If the installer passed in a manifest digest, compare it now. */ 11586 if (args.manifestDigest != null) { 11587 if (DEBUG_INSTALL) { 11588 final String parsedManifest = pkg.manifestDigest == null ? "null" 11589 : pkg.manifestDigest.toString(); 11590 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11591 + parsedManifest); 11592 } 11593 11594 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11595 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11596 return; 11597 } 11598 } else if (DEBUG_INSTALL) { 11599 final String parsedManifest = pkg.manifestDigest == null 11600 ? "null" : pkg.manifestDigest.toString(); 11601 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11602 } 11603 11604 // Get rid of all references to package scan path via parser. 11605 pp = null; 11606 String oldCodePath = null; 11607 boolean systemApp = false; 11608 synchronized (mPackages) { 11609 // Check if installing already existing package 11610 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11611 String oldName = mSettings.mRenamedPackages.get(pkgName); 11612 if (pkg.mOriginalPackages != null 11613 && pkg.mOriginalPackages.contains(oldName) 11614 && mPackages.containsKey(oldName)) { 11615 // This package is derived from an original package, 11616 // and this device has been updating from that original 11617 // name. We must continue using the original name, so 11618 // rename the new package here. 11619 pkg.setPackageName(oldName); 11620 pkgName = pkg.packageName; 11621 replace = true; 11622 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11623 + oldName + " pkgName=" + pkgName); 11624 } else if (mPackages.containsKey(pkgName)) { 11625 // This package, under its official name, already exists 11626 // on the device; we should replace it. 11627 replace = true; 11628 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11629 } 11630 11631 // Prevent apps opting out from runtime permissions 11632 if (replace) { 11633 PackageParser.Package oldPackage = mPackages.get(pkgName); 11634 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11635 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11636 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11637 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11638 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11639 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11640 + " doesn't support runtime permissions but the old" 11641 + " target SDK " + oldTargetSdk + " does."); 11642 return; 11643 } 11644 } 11645 } 11646 11647 PackageSetting ps = mSettings.mPackages.get(pkgName); 11648 if (ps != null) { 11649 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11650 11651 // Quick sanity check that we're signed correctly if updating; 11652 // we'll check this again later when scanning, but we want to 11653 // bail early here before tripping over redefined permissions. 11654 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11655 if (!checkUpgradeKeySetLP(ps, pkg)) { 11656 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11657 + pkg.packageName + " upgrade keys do not match the " 11658 + "previously installed version"); 11659 return; 11660 } 11661 } else { 11662 try { 11663 verifySignaturesLP(ps, pkg); 11664 } catch (PackageManagerException e) { 11665 res.setError(e.error, e.getMessage()); 11666 return; 11667 } 11668 } 11669 11670 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11671 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11672 systemApp = (ps.pkg.applicationInfo.flags & 11673 ApplicationInfo.FLAG_SYSTEM) != 0; 11674 } 11675 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11676 } 11677 11678 // Check whether the newly-scanned package wants to define an already-defined perm 11679 int N = pkg.permissions.size(); 11680 for (int i = N-1; i >= 0; i--) { 11681 PackageParser.Permission perm = pkg.permissions.get(i); 11682 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11683 if (bp != null) { 11684 // If the defining package is signed with our cert, it's okay. This 11685 // also includes the "updating the same package" case, of course. 11686 // "updating same package" could also involve key-rotation. 11687 final boolean sigsOk; 11688 if (bp.sourcePackage.equals(pkg.packageName) 11689 && (bp.packageSetting instanceof PackageSetting) 11690 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11691 scanFlags))) { 11692 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11693 } else { 11694 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11695 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11696 } 11697 if (!sigsOk) { 11698 // If the owning package is the system itself, we log but allow 11699 // install to proceed; we fail the install on all other permission 11700 // redefinitions. 11701 if (!bp.sourcePackage.equals("android")) { 11702 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11703 + pkg.packageName + " attempting to redeclare permission " 11704 + perm.info.name + " already owned by " + bp.sourcePackage); 11705 res.origPermission = perm.info.name; 11706 res.origPackage = bp.sourcePackage; 11707 return; 11708 } else { 11709 Slog.w(TAG, "Package " + pkg.packageName 11710 + " attempting to redeclare system permission " 11711 + perm.info.name + "; ignoring new declaration"); 11712 pkg.permissions.remove(i); 11713 } 11714 } 11715 } 11716 } 11717 11718 } 11719 11720 if (systemApp && onExternal) { 11721 // Disable updates to system apps on sdcard 11722 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11723 "Cannot install updates to system apps on sdcard"); 11724 return; 11725 } 11726 11727 if (args.move != null) { 11728 // We did an in-place move, so dex is ready to roll 11729 scanFlags |= SCAN_NO_DEX; 11730 scanFlags |= SCAN_MOVE; 11731 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11732 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11733 scanFlags |= SCAN_NO_DEX; 11734 11735 try { 11736 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11737 true /* extract libs */); 11738 } catch (PackageManagerException pme) { 11739 Slog.e(TAG, "Error deriving application ABI", pme); 11740 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11741 return; 11742 } 11743 11744 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11745 int result = mPackageDexOptimizer 11746 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11747 false /* defer */, false /* inclDependencies */); 11748 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11749 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11750 return; 11751 } 11752 } 11753 11754 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11755 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11756 return; 11757 } 11758 11759 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11760 11761 if (replace) { 11762 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11763 installerPackageName, volumeUuid, res); 11764 } else { 11765 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11766 args.user, installerPackageName, volumeUuid, res); 11767 } 11768 synchronized (mPackages) { 11769 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11770 if (ps != null) { 11771 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11772 } 11773 } 11774 } 11775 11776 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11777 if (mIntentFilterVerifierComponent == null) { 11778 Slog.w(TAG, "No IntentFilter verification will not be done as " 11779 + "there is no IntentFilterVerifier available!"); 11780 return; 11781 } 11782 11783 final int verifierUid = getPackageUid( 11784 mIntentFilterVerifierComponent.getPackageName(), 11785 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11786 11787 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11788 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11789 msg.obj = pkg; 11790 msg.arg1 = userId; 11791 msg.arg2 = verifierUid; 11792 11793 mHandler.sendMessage(msg); 11794 } 11795 11796 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11797 PackageParser.Package pkg) { 11798 int size = pkg.activities.size(); 11799 if (size == 0) { 11800 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11801 "No activity, so no need to verify any IntentFilter!"); 11802 return; 11803 } 11804 11805 final boolean hasDomainURLs = hasDomainURLs(pkg); 11806 if (!hasDomainURLs) { 11807 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11808 "No domain URLs, so no need to verify any IntentFilter!"); 11809 return; 11810 } 11811 11812 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11813 + " if any IntentFilter from the " + size 11814 + " Activities needs verification ..."); 11815 11816 final int verificationId = mIntentFilterVerificationToken++; 11817 int count = 0; 11818 final String packageName = pkg.packageName; 11819 boolean needToVerify = false; 11820 11821 synchronized (mPackages) { 11822 // If any filters need to be verified, then all need to be. 11823 for (PackageParser.Activity a : pkg.activities) { 11824 for (ActivityIntentInfo filter : a.intents) { 11825 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11826 if (DEBUG_DOMAIN_VERIFICATION) { 11827 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11828 } 11829 needToVerify = true; 11830 break; 11831 } 11832 } 11833 } 11834 if (needToVerify) { 11835 for (PackageParser.Activity a : pkg.activities) { 11836 for (ActivityIntentInfo filter : a.intents) { 11837 boolean needsFilterVerification = filter.hasWebDataURI(); 11838 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11839 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11840 "Verification needed for IntentFilter:" + filter.toString()); 11841 mIntentFilterVerifier.addOneIntentFilterVerification( 11842 verifierUid, userId, verificationId, filter, packageName); 11843 count++; 11844 } 11845 } 11846 } 11847 } 11848 } 11849 11850 if (count > 0) { 11851 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11852 + " IntentFilter verification" + (count > 1 ? "s" : "") 11853 + " for userId:" + userId); 11854 mIntentFilterVerifier.startVerifications(userId); 11855 } else { 11856 if (DEBUG_DOMAIN_VERIFICATION) { 11857 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11858 } 11859 } 11860 } 11861 11862 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11863 final ComponentName cn = filter.activity.getComponentName(); 11864 final String packageName = cn.getPackageName(); 11865 11866 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11867 packageName); 11868 if (ivi == null) { 11869 return true; 11870 } 11871 int status = ivi.getStatus(); 11872 switch (status) { 11873 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11874 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11875 return true; 11876 11877 default: 11878 // Nothing to do 11879 return false; 11880 } 11881 } 11882 11883 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11884 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11885 || ((pkg.applicationInfo.privateFlags 11886 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11887 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11888 } 11889 11890 private static boolean isMultiArch(PackageSetting ps) { 11891 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11892 } 11893 11894 private static boolean isMultiArch(ApplicationInfo info) { 11895 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11896 } 11897 11898 private static boolean isExternal(PackageParser.Package pkg) { 11899 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11900 } 11901 11902 private static boolean isExternal(PackageSetting ps) { 11903 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11904 } 11905 11906 private static boolean isExternal(ApplicationInfo info) { 11907 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11908 } 11909 11910 private static boolean isSystemApp(PackageParser.Package pkg) { 11911 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11912 } 11913 11914 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11915 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11916 } 11917 11918 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11919 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11920 } 11921 11922 private static boolean isSystemApp(PackageSetting ps) { 11923 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11924 } 11925 11926 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11927 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11928 } 11929 11930 private int packageFlagsToInstallFlags(PackageSetting ps) { 11931 int installFlags = 0; 11932 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11933 // This existing package was an external ASEC install when we have 11934 // the external flag without a UUID 11935 installFlags |= PackageManager.INSTALL_EXTERNAL; 11936 } 11937 if (ps.isForwardLocked()) { 11938 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11939 } 11940 return installFlags; 11941 } 11942 11943 private void deleteTempPackageFiles() { 11944 final FilenameFilter filter = new FilenameFilter() { 11945 public boolean accept(File dir, String name) { 11946 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11947 } 11948 }; 11949 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11950 file.delete(); 11951 } 11952 } 11953 11954 @Override 11955 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11956 int flags) { 11957 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11958 flags); 11959 } 11960 11961 @Override 11962 public void deletePackage(final String packageName, 11963 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11964 mContext.enforceCallingOrSelfPermission( 11965 android.Manifest.permission.DELETE_PACKAGES, null); 11966 final int uid = Binder.getCallingUid(); 11967 if (UserHandle.getUserId(uid) != userId) { 11968 mContext.enforceCallingPermission( 11969 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11970 "deletePackage for user " + userId); 11971 } 11972 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11973 try { 11974 observer.onPackageDeleted(packageName, 11975 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11976 } catch (RemoteException re) { 11977 } 11978 return; 11979 } 11980 11981 boolean uninstallBlocked = false; 11982 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11983 int[] users = sUserManager.getUserIds(); 11984 for (int i = 0; i < users.length; ++i) { 11985 if (getBlockUninstallForUser(packageName, users[i])) { 11986 uninstallBlocked = true; 11987 break; 11988 } 11989 } 11990 } else { 11991 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11992 } 11993 if (uninstallBlocked) { 11994 try { 11995 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11996 null); 11997 } catch (RemoteException re) { 11998 } 11999 return; 12000 } 12001 12002 if (DEBUG_REMOVE) { 12003 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12004 } 12005 // Queue up an async operation since the package deletion may take a little while. 12006 mHandler.post(new Runnable() { 12007 public void run() { 12008 mHandler.removeCallbacks(this); 12009 final int returnCode = deletePackageX(packageName, userId, flags); 12010 if (observer != null) { 12011 try { 12012 observer.onPackageDeleted(packageName, returnCode, null); 12013 } catch (RemoteException e) { 12014 Log.i(TAG, "Observer no longer exists."); 12015 } //end catch 12016 } //end if 12017 } //end run 12018 }); 12019 } 12020 12021 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12022 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12023 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12024 try { 12025 if (dpm != null) { 12026 if (dpm.isDeviceOwner(packageName)) { 12027 return true; 12028 } 12029 int[] users; 12030 if (userId == UserHandle.USER_ALL) { 12031 users = sUserManager.getUserIds(); 12032 } else { 12033 users = new int[]{userId}; 12034 } 12035 for (int i = 0; i < users.length; ++i) { 12036 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12037 return true; 12038 } 12039 } 12040 } 12041 } catch (RemoteException e) { 12042 } 12043 return false; 12044 } 12045 12046 /** 12047 * This method is an internal method that could be get invoked either 12048 * to delete an installed package or to clean up a failed installation. 12049 * After deleting an installed package, a broadcast is sent to notify any 12050 * listeners that the package has been installed. For cleaning up a failed 12051 * installation, the broadcast is not necessary since the package's 12052 * installation wouldn't have sent the initial broadcast either 12053 * The key steps in deleting a package are 12054 * deleting the package information in internal structures like mPackages, 12055 * deleting the packages base directories through installd 12056 * updating mSettings to reflect current status 12057 * persisting settings for later use 12058 * sending a broadcast if necessary 12059 */ 12060 private int deletePackageX(String packageName, int userId, int flags) { 12061 final PackageRemovedInfo info = new PackageRemovedInfo(); 12062 final boolean res; 12063 12064 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12065 ? UserHandle.ALL : new UserHandle(userId); 12066 12067 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12068 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12069 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12070 } 12071 12072 boolean removedForAllUsers = false; 12073 boolean systemUpdate = false; 12074 12075 // for the uninstall-updates case and restricted profiles, remember the per- 12076 // userhandle installed state 12077 int[] allUsers; 12078 boolean[] perUserInstalled; 12079 synchronized (mPackages) { 12080 PackageSetting ps = mSettings.mPackages.get(packageName); 12081 allUsers = sUserManager.getUserIds(); 12082 perUserInstalled = new boolean[allUsers.length]; 12083 for (int i = 0; i < allUsers.length; i++) { 12084 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12085 } 12086 } 12087 12088 synchronized (mInstallLock) { 12089 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12090 res = deletePackageLI(packageName, removeForUser, 12091 true, allUsers, perUserInstalled, 12092 flags | REMOVE_CHATTY, info, true); 12093 systemUpdate = info.isRemovedPackageSystemUpdate; 12094 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12095 removedForAllUsers = true; 12096 } 12097 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12098 + " removedForAllUsers=" + removedForAllUsers); 12099 } 12100 12101 if (res) { 12102 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12103 12104 // If the removed package was a system update, the old system package 12105 // was re-enabled; we need to broadcast this information 12106 if (systemUpdate) { 12107 Bundle extras = new Bundle(1); 12108 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12109 ? info.removedAppId : info.uid); 12110 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12111 12112 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12113 extras, null, null, null); 12114 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12115 extras, null, null, null); 12116 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12117 null, packageName, null, null); 12118 } 12119 } 12120 // Force a gc here. 12121 Runtime.getRuntime().gc(); 12122 // Delete the resources here after sending the broadcast to let 12123 // other processes clean up before deleting resources. 12124 if (info.args != null) { 12125 synchronized (mInstallLock) { 12126 info.args.doPostDeleteLI(true); 12127 } 12128 } 12129 12130 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12131 } 12132 12133 class PackageRemovedInfo { 12134 String removedPackage; 12135 int uid = -1; 12136 int removedAppId = -1; 12137 int[] removedUsers = null; 12138 boolean isRemovedPackageSystemUpdate = false; 12139 // Clean up resources deleted packages. 12140 InstallArgs args = null; 12141 12142 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12143 Bundle extras = new Bundle(1); 12144 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12145 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12146 if (replacing) { 12147 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12148 } 12149 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12150 if (removedPackage != null) { 12151 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12152 extras, null, null, removedUsers); 12153 if (fullRemove && !replacing) { 12154 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12155 extras, null, null, removedUsers); 12156 } 12157 } 12158 if (removedAppId >= 0) { 12159 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12160 removedUsers); 12161 } 12162 } 12163 } 12164 12165 /* 12166 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12167 * flag is not set, the data directory is removed as well. 12168 * make sure this flag is set for partially installed apps. If not its meaningless to 12169 * delete a partially installed application. 12170 */ 12171 private void removePackageDataLI(PackageSetting ps, 12172 int[] allUserHandles, boolean[] perUserInstalled, 12173 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12174 String packageName = ps.name; 12175 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12176 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12177 // Retrieve object to delete permissions for shared user later on 12178 final PackageSetting deletedPs; 12179 // reader 12180 synchronized (mPackages) { 12181 deletedPs = mSettings.mPackages.get(packageName); 12182 if (outInfo != null) { 12183 outInfo.removedPackage = packageName; 12184 outInfo.removedUsers = deletedPs != null 12185 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12186 : null; 12187 } 12188 } 12189 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12190 removeDataDirsLI(ps.volumeUuid, packageName); 12191 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12192 } 12193 // writer 12194 synchronized (mPackages) { 12195 if (deletedPs != null) { 12196 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12197 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12198 clearDefaultBrowserIfNeeded(packageName); 12199 if (outInfo != null) { 12200 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12201 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12202 } 12203 updatePermissionsLPw(deletedPs.name, null, 0); 12204 if (deletedPs.sharedUser != null) { 12205 // Remove permissions associated with package. Since runtime 12206 // permissions are per user we have to kill the removed package 12207 // or packages running under the shared user of the removed 12208 // package if revoking the permissions requested only by the removed 12209 // package is successful and this causes a change in gids. 12210 for (int userId : UserManagerService.getInstance().getUserIds()) { 12211 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12212 userId); 12213 if (userIdToKill == UserHandle.USER_ALL 12214 || userIdToKill >= UserHandle.USER_OWNER) { 12215 // If gids changed for this user, kill all affected packages. 12216 mHandler.post(new Runnable() { 12217 @Override 12218 public void run() { 12219 // This has to happen with no lock held. 12220 killSettingPackagesForUser(deletedPs, userIdToKill, 12221 KILL_APP_REASON_GIDS_CHANGED); 12222 } 12223 }); 12224 break; 12225 } 12226 } 12227 } 12228 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12229 } 12230 // make sure to preserve per-user disabled state if this removal was just 12231 // a downgrade of a system app to the factory package 12232 if (allUserHandles != null && perUserInstalled != null) { 12233 if (DEBUG_REMOVE) { 12234 Slog.d(TAG, "Propagating install state across downgrade"); 12235 } 12236 for (int i = 0; i < allUserHandles.length; i++) { 12237 if (DEBUG_REMOVE) { 12238 Slog.d(TAG, " user " + allUserHandles[i] 12239 + " => " + perUserInstalled[i]); 12240 } 12241 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12242 } 12243 } 12244 } 12245 // can downgrade to reader 12246 if (writeSettings) { 12247 // Save settings now 12248 mSettings.writeLPr(); 12249 } 12250 } 12251 if (outInfo != null) { 12252 // A user ID was deleted here. Go through all users and remove it 12253 // from KeyStore. 12254 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12255 } 12256 } 12257 12258 static boolean locationIsPrivileged(File path) { 12259 try { 12260 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12261 .getCanonicalPath(); 12262 return path.getCanonicalPath().startsWith(privilegedAppDir); 12263 } catch (IOException e) { 12264 Slog.e(TAG, "Unable to access code path " + path); 12265 } 12266 return false; 12267 } 12268 12269 /* 12270 * Tries to delete system package. 12271 */ 12272 private boolean deleteSystemPackageLI(PackageSetting newPs, 12273 int[] allUserHandles, boolean[] perUserInstalled, 12274 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12275 final boolean applyUserRestrictions 12276 = (allUserHandles != null) && (perUserInstalled != null); 12277 PackageSetting disabledPs = null; 12278 // Confirm if the system package has been updated 12279 // An updated system app can be deleted. This will also have to restore 12280 // the system pkg from system partition 12281 // reader 12282 synchronized (mPackages) { 12283 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12284 } 12285 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12286 + " disabledPs=" + disabledPs); 12287 if (disabledPs == null) { 12288 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12289 return false; 12290 } else if (DEBUG_REMOVE) { 12291 Slog.d(TAG, "Deleting system pkg from data partition"); 12292 } 12293 if (DEBUG_REMOVE) { 12294 if (applyUserRestrictions) { 12295 Slog.d(TAG, "Remembering install states:"); 12296 for (int i = 0; i < allUserHandles.length; i++) { 12297 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12298 } 12299 } 12300 } 12301 // Delete the updated package 12302 outInfo.isRemovedPackageSystemUpdate = true; 12303 if (disabledPs.versionCode < newPs.versionCode) { 12304 // Delete data for downgrades 12305 flags &= ~PackageManager.DELETE_KEEP_DATA; 12306 } else { 12307 // Preserve data by setting flag 12308 flags |= PackageManager.DELETE_KEEP_DATA; 12309 } 12310 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12311 allUserHandles, perUserInstalled, outInfo, writeSettings); 12312 if (!ret) { 12313 return false; 12314 } 12315 // writer 12316 synchronized (mPackages) { 12317 // Reinstate the old system package 12318 mSettings.enableSystemPackageLPw(newPs.name); 12319 // Remove any native libraries from the upgraded package. 12320 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12321 } 12322 // Install the system package 12323 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12324 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12325 if (locationIsPrivileged(disabledPs.codePath)) { 12326 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12327 } 12328 12329 final PackageParser.Package newPkg; 12330 try { 12331 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12332 } catch (PackageManagerException e) { 12333 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12334 return false; 12335 } 12336 12337 // writer 12338 synchronized (mPackages) { 12339 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12340 updatePermissionsLPw(newPkg.packageName, newPkg, 12341 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12342 if (applyUserRestrictions) { 12343 if (DEBUG_REMOVE) { 12344 Slog.d(TAG, "Propagating install state across reinstall"); 12345 } 12346 for (int i = 0; i < allUserHandles.length; i++) { 12347 if (DEBUG_REMOVE) { 12348 Slog.d(TAG, " user " + allUserHandles[i] 12349 + " => " + perUserInstalled[i]); 12350 } 12351 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12352 } 12353 // Regardless of writeSettings we need to ensure that this restriction 12354 // state propagation is persisted 12355 mSettings.writeAllUsersPackageRestrictionsLPr(); 12356 } 12357 // can downgrade to reader here 12358 if (writeSettings) { 12359 mSettings.writeLPr(); 12360 } 12361 } 12362 return true; 12363 } 12364 12365 private boolean deleteInstalledPackageLI(PackageSetting ps, 12366 boolean deleteCodeAndResources, int flags, 12367 int[] allUserHandles, boolean[] perUserInstalled, 12368 PackageRemovedInfo outInfo, boolean writeSettings) { 12369 if (outInfo != null) { 12370 outInfo.uid = ps.appId; 12371 } 12372 12373 // Delete package data from internal structures and also remove data if flag is set 12374 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12375 12376 // Delete application code and resources 12377 if (deleteCodeAndResources && (outInfo != null)) { 12378 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12379 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12380 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12381 } 12382 return true; 12383 } 12384 12385 @Override 12386 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12387 int userId) { 12388 mContext.enforceCallingOrSelfPermission( 12389 android.Manifest.permission.DELETE_PACKAGES, null); 12390 synchronized (mPackages) { 12391 PackageSetting ps = mSettings.mPackages.get(packageName); 12392 if (ps == null) { 12393 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12394 return false; 12395 } 12396 if (!ps.getInstalled(userId)) { 12397 // Can't block uninstall for an app that is not installed or enabled. 12398 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12399 return false; 12400 } 12401 ps.setBlockUninstall(blockUninstall, userId); 12402 mSettings.writePackageRestrictionsLPr(userId); 12403 } 12404 return true; 12405 } 12406 12407 @Override 12408 public boolean getBlockUninstallForUser(String packageName, int userId) { 12409 synchronized (mPackages) { 12410 PackageSetting ps = mSettings.mPackages.get(packageName); 12411 if (ps == null) { 12412 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12413 return false; 12414 } 12415 return ps.getBlockUninstall(userId); 12416 } 12417 } 12418 12419 /* 12420 * This method handles package deletion in general 12421 */ 12422 private boolean deletePackageLI(String packageName, UserHandle user, 12423 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12424 int flags, PackageRemovedInfo outInfo, 12425 boolean writeSettings) { 12426 if (packageName == null) { 12427 Slog.w(TAG, "Attempt to delete null packageName."); 12428 return false; 12429 } 12430 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12431 PackageSetting ps; 12432 boolean dataOnly = false; 12433 int removeUser = -1; 12434 int appId = -1; 12435 synchronized (mPackages) { 12436 ps = mSettings.mPackages.get(packageName); 12437 if (ps == null) { 12438 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12439 return false; 12440 } 12441 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12442 && user.getIdentifier() != UserHandle.USER_ALL) { 12443 // The caller is asking that the package only be deleted for a single 12444 // user. To do this, we just mark its uninstalled state and delete 12445 // its data. If this is a system app, we only allow this to happen if 12446 // they have set the special DELETE_SYSTEM_APP which requests different 12447 // semantics than normal for uninstalling system apps. 12448 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12449 ps.setUserState(user.getIdentifier(), 12450 COMPONENT_ENABLED_STATE_DEFAULT, 12451 false, //installed 12452 true, //stopped 12453 true, //notLaunched 12454 false, //hidden 12455 null, null, null, 12456 false, // blockUninstall 12457 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12458 if (!isSystemApp(ps)) { 12459 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12460 // Other user still have this package installed, so all 12461 // we need to do is clear this user's data and save that 12462 // it is uninstalled. 12463 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12464 removeUser = user.getIdentifier(); 12465 appId = ps.appId; 12466 scheduleWritePackageRestrictionsLocked(removeUser); 12467 } else { 12468 // We need to set it back to 'installed' so the uninstall 12469 // broadcasts will be sent correctly. 12470 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12471 ps.setInstalled(true, user.getIdentifier()); 12472 } 12473 } else { 12474 // This is a system app, so we assume that the 12475 // other users still have this package installed, so all 12476 // we need to do is clear this user's data and save that 12477 // it is uninstalled. 12478 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12479 removeUser = user.getIdentifier(); 12480 appId = ps.appId; 12481 scheduleWritePackageRestrictionsLocked(removeUser); 12482 } 12483 } 12484 } 12485 12486 if (removeUser >= 0) { 12487 // From above, we determined that we are deleting this only 12488 // for a single user. Continue the work here. 12489 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12490 if (outInfo != null) { 12491 outInfo.removedPackage = packageName; 12492 outInfo.removedAppId = appId; 12493 outInfo.removedUsers = new int[] {removeUser}; 12494 } 12495 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12496 removeKeystoreDataIfNeeded(removeUser, appId); 12497 schedulePackageCleaning(packageName, removeUser, false); 12498 synchronized (mPackages) { 12499 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12500 scheduleWritePackageRestrictionsLocked(removeUser); 12501 } 12502 } 12503 return true; 12504 } 12505 12506 if (dataOnly) { 12507 // Delete application data first 12508 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12509 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12510 return true; 12511 } 12512 12513 boolean ret = false; 12514 if (isSystemApp(ps)) { 12515 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12516 // When an updated system application is deleted we delete the existing resources as well and 12517 // fall back to existing code in system partition 12518 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12519 flags, outInfo, writeSettings); 12520 } else { 12521 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12522 // Kill application pre-emptively especially for apps on sd. 12523 killApplication(packageName, ps.appId, "uninstall pkg"); 12524 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12525 allUserHandles, perUserInstalled, 12526 outInfo, writeSettings); 12527 } 12528 12529 return ret; 12530 } 12531 12532 private final class ClearStorageConnection implements ServiceConnection { 12533 IMediaContainerService mContainerService; 12534 12535 @Override 12536 public void onServiceConnected(ComponentName name, IBinder service) { 12537 synchronized (this) { 12538 mContainerService = IMediaContainerService.Stub.asInterface(service); 12539 notifyAll(); 12540 } 12541 } 12542 12543 @Override 12544 public void onServiceDisconnected(ComponentName name) { 12545 } 12546 } 12547 12548 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12549 final boolean mounted; 12550 if (Environment.isExternalStorageEmulated()) { 12551 mounted = true; 12552 } else { 12553 final String status = Environment.getExternalStorageState(); 12554 12555 mounted = status.equals(Environment.MEDIA_MOUNTED) 12556 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12557 } 12558 12559 if (!mounted) { 12560 return; 12561 } 12562 12563 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12564 int[] users; 12565 if (userId == UserHandle.USER_ALL) { 12566 users = sUserManager.getUserIds(); 12567 } else { 12568 users = new int[] { userId }; 12569 } 12570 final ClearStorageConnection conn = new ClearStorageConnection(); 12571 if (mContext.bindServiceAsUser( 12572 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12573 try { 12574 for (int curUser : users) { 12575 long timeout = SystemClock.uptimeMillis() + 5000; 12576 synchronized (conn) { 12577 long now = SystemClock.uptimeMillis(); 12578 while (conn.mContainerService == null && now < timeout) { 12579 try { 12580 conn.wait(timeout - now); 12581 } catch (InterruptedException e) { 12582 } 12583 } 12584 } 12585 if (conn.mContainerService == null) { 12586 return; 12587 } 12588 12589 final UserEnvironment userEnv = new UserEnvironment(curUser); 12590 clearDirectory(conn.mContainerService, 12591 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12592 if (allData) { 12593 clearDirectory(conn.mContainerService, 12594 userEnv.buildExternalStorageAppDataDirs(packageName)); 12595 clearDirectory(conn.mContainerService, 12596 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12597 } 12598 } 12599 } finally { 12600 mContext.unbindService(conn); 12601 } 12602 } 12603 } 12604 12605 @Override 12606 public void clearApplicationUserData(final String packageName, 12607 final IPackageDataObserver observer, final int userId) { 12608 mContext.enforceCallingOrSelfPermission( 12609 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12610 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12611 // Queue up an async operation since the package deletion may take a little while. 12612 mHandler.post(new Runnable() { 12613 public void run() { 12614 mHandler.removeCallbacks(this); 12615 final boolean succeeded; 12616 synchronized (mInstallLock) { 12617 succeeded = clearApplicationUserDataLI(packageName, userId); 12618 } 12619 clearExternalStorageDataSync(packageName, userId, true); 12620 if (succeeded) { 12621 // invoke DeviceStorageMonitor's update method to clear any notifications 12622 DeviceStorageMonitorInternal 12623 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12624 if (dsm != null) { 12625 dsm.checkMemory(); 12626 } 12627 } 12628 if(observer != null) { 12629 try { 12630 observer.onRemoveCompleted(packageName, succeeded); 12631 } catch (RemoteException e) { 12632 Log.i(TAG, "Observer no longer exists."); 12633 } 12634 } //end if observer 12635 } //end run 12636 }); 12637 } 12638 12639 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12640 if (packageName == null) { 12641 Slog.w(TAG, "Attempt to delete null packageName."); 12642 return false; 12643 } 12644 12645 // Try finding details about the requested package 12646 PackageParser.Package pkg; 12647 synchronized (mPackages) { 12648 pkg = mPackages.get(packageName); 12649 if (pkg == null) { 12650 final PackageSetting ps = mSettings.mPackages.get(packageName); 12651 if (ps != null) { 12652 pkg = ps.pkg; 12653 } 12654 } 12655 12656 if (pkg == null) { 12657 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12658 return false; 12659 } 12660 12661 PackageSetting ps = (PackageSetting) pkg.mExtras; 12662 PermissionsState permissionsState = ps.getPermissionsState(); 12663 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12664 } 12665 12666 // Always delete data directories for package, even if we found no other 12667 // record of app. This helps users recover from UID mismatches without 12668 // resorting to a full data wipe. 12669 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12670 if (retCode < 0) { 12671 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12672 return false; 12673 } 12674 12675 final int appId = pkg.applicationInfo.uid; 12676 removeKeystoreDataIfNeeded(userId, appId); 12677 12678 // Create a native library symlink only if we have native libraries 12679 // and if the native libraries are 32 bit libraries. We do not provide 12680 // this symlink for 64 bit libraries. 12681 if (pkg.applicationInfo.primaryCpuAbi != null && 12682 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12683 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12684 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12685 nativeLibPath, userId) < 0) { 12686 Slog.w(TAG, "Failed linking native library dir"); 12687 return false; 12688 } 12689 } 12690 12691 return true; 12692 } 12693 12694 12695 /** 12696 * Revokes granted runtime permissions and clears resettable flags 12697 * which are flags that can be set by a user interaction. 12698 * 12699 * @param permissionsState The permission state to reset. 12700 * @param userId The device user for which to do a reset. 12701 */ 12702 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12703 PermissionsState permissionsState, int userId) { 12704 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12705 | PackageManager.FLAG_PERMISSION_USER_FIXED 12706 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12707 12708 boolean needsWrite = false; 12709 12710 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12711 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12712 if (bp != null) { 12713 permissionsState.revokeRuntimePermission(bp, userId); 12714 permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0); 12715 needsWrite = true; 12716 } 12717 } 12718 12719 if (needsWrite) { 12720 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12721 } 12722 } 12723 12724 /** 12725 * Remove entries from the keystore daemon. Will only remove it if the 12726 * {@code appId} is valid. 12727 */ 12728 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12729 if (appId < 0) { 12730 return; 12731 } 12732 12733 final KeyStore keyStore = KeyStore.getInstance(); 12734 if (keyStore != null) { 12735 if (userId == UserHandle.USER_ALL) { 12736 for (final int individual : sUserManager.getUserIds()) { 12737 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12738 } 12739 } else { 12740 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12741 } 12742 } else { 12743 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12744 } 12745 } 12746 12747 @Override 12748 public void deleteApplicationCacheFiles(final String packageName, 12749 final IPackageDataObserver observer) { 12750 mContext.enforceCallingOrSelfPermission( 12751 android.Manifest.permission.DELETE_CACHE_FILES, null); 12752 // Queue up an async operation since the package deletion may take a little while. 12753 final int userId = UserHandle.getCallingUserId(); 12754 mHandler.post(new Runnable() { 12755 public void run() { 12756 mHandler.removeCallbacks(this); 12757 final boolean succeded; 12758 synchronized (mInstallLock) { 12759 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12760 } 12761 clearExternalStorageDataSync(packageName, userId, false); 12762 if (observer != null) { 12763 try { 12764 observer.onRemoveCompleted(packageName, succeded); 12765 } catch (RemoteException e) { 12766 Log.i(TAG, "Observer no longer exists."); 12767 } 12768 } //end if observer 12769 } //end run 12770 }); 12771 } 12772 12773 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12774 if (packageName == null) { 12775 Slog.w(TAG, "Attempt to delete null packageName."); 12776 return false; 12777 } 12778 PackageParser.Package p; 12779 synchronized (mPackages) { 12780 p = mPackages.get(packageName); 12781 } 12782 if (p == null) { 12783 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12784 return false; 12785 } 12786 final ApplicationInfo applicationInfo = p.applicationInfo; 12787 if (applicationInfo == null) { 12788 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12789 return false; 12790 } 12791 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12792 if (retCode < 0) { 12793 Slog.w(TAG, "Couldn't remove cache files for package: " 12794 + packageName + " u" + userId); 12795 return false; 12796 } 12797 return true; 12798 } 12799 12800 @Override 12801 public void getPackageSizeInfo(final String packageName, int userHandle, 12802 final IPackageStatsObserver observer) { 12803 mContext.enforceCallingOrSelfPermission( 12804 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12805 if (packageName == null) { 12806 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12807 } 12808 12809 PackageStats stats = new PackageStats(packageName, userHandle); 12810 12811 /* 12812 * Queue up an async operation since the package measurement may take a 12813 * little while. 12814 */ 12815 Message msg = mHandler.obtainMessage(INIT_COPY); 12816 msg.obj = new MeasureParams(stats, observer); 12817 mHandler.sendMessage(msg); 12818 } 12819 12820 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12821 PackageStats pStats) { 12822 if (packageName == null) { 12823 Slog.w(TAG, "Attempt to get size of null packageName."); 12824 return false; 12825 } 12826 PackageParser.Package p; 12827 boolean dataOnly = false; 12828 String libDirRoot = null; 12829 String asecPath = null; 12830 PackageSetting ps = null; 12831 synchronized (mPackages) { 12832 p = mPackages.get(packageName); 12833 ps = mSettings.mPackages.get(packageName); 12834 if(p == null) { 12835 dataOnly = true; 12836 if((ps == null) || (ps.pkg == null)) { 12837 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12838 return false; 12839 } 12840 p = ps.pkg; 12841 } 12842 if (ps != null) { 12843 libDirRoot = ps.legacyNativeLibraryPathString; 12844 } 12845 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12846 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12847 if (secureContainerId != null) { 12848 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12849 } 12850 } 12851 } 12852 String publicSrcDir = null; 12853 if(!dataOnly) { 12854 final ApplicationInfo applicationInfo = p.applicationInfo; 12855 if (applicationInfo == null) { 12856 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12857 return false; 12858 } 12859 if (p.isForwardLocked()) { 12860 publicSrcDir = applicationInfo.getBaseResourcePath(); 12861 } 12862 } 12863 // TODO: extend to measure size of split APKs 12864 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12865 // not just the first level. 12866 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12867 // just the primary. 12868 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12869 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12870 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12871 if (res < 0) { 12872 return false; 12873 } 12874 12875 // Fix-up for forward-locked applications in ASEC containers. 12876 if (!isExternal(p)) { 12877 pStats.codeSize += pStats.externalCodeSize; 12878 pStats.externalCodeSize = 0L; 12879 } 12880 12881 return true; 12882 } 12883 12884 12885 @Override 12886 public void addPackageToPreferred(String packageName) { 12887 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12888 } 12889 12890 @Override 12891 public void removePackageFromPreferred(String packageName) { 12892 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12893 } 12894 12895 @Override 12896 public List<PackageInfo> getPreferredPackages(int flags) { 12897 return new ArrayList<PackageInfo>(); 12898 } 12899 12900 private int getUidTargetSdkVersionLockedLPr(int uid) { 12901 Object obj = mSettings.getUserIdLPr(uid); 12902 if (obj instanceof SharedUserSetting) { 12903 final SharedUserSetting sus = (SharedUserSetting) obj; 12904 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12905 final Iterator<PackageSetting> it = sus.packages.iterator(); 12906 while (it.hasNext()) { 12907 final PackageSetting ps = it.next(); 12908 if (ps.pkg != null) { 12909 int v = ps.pkg.applicationInfo.targetSdkVersion; 12910 if (v < vers) vers = v; 12911 } 12912 } 12913 return vers; 12914 } else if (obj instanceof PackageSetting) { 12915 final PackageSetting ps = (PackageSetting) obj; 12916 if (ps.pkg != null) { 12917 return ps.pkg.applicationInfo.targetSdkVersion; 12918 } 12919 } 12920 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12921 } 12922 12923 @Override 12924 public void addPreferredActivity(IntentFilter filter, int match, 12925 ComponentName[] set, ComponentName activity, int userId) { 12926 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12927 "Adding preferred"); 12928 } 12929 12930 private void addPreferredActivityInternal(IntentFilter filter, int match, 12931 ComponentName[] set, ComponentName activity, boolean always, int userId, 12932 String opname) { 12933 // writer 12934 int callingUid = Binder.getCallingUid(); 12935 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12936 if (filter.countActions() == 0) { 12937 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12938 return; 12939 } 12940 synchronized (mPackages) { 12941 if (mContext.checkCallingOrSelfPermission( 12942 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12943 != PackageManager.PERMISSION_GRANTED) { 12944 if (getUidTargetSdkVersionLockedLPr(callingUid) 12945 < Build.VERSION_CODES.FROYO) { 12946 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12947 + callingUid); 12948 return; 12949 } 12950 mContext.enforceCallingOrSelfPermission( 12951 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12952 } 12953 12954 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12955 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12956 + userId + ":"); 12957 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12958 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12959 scheduleWritePackageRestrictionsLocked(userId); 12960 } 12961 } 12962 12963 @Override 12964 public void replacePreferredActivity(IntentFilter filter, int match, 12965 ComponentName[] set, ComponentName activity, int userId) { 12966 if (filter.countActions() != 1) { 12967 throw new IllegalArgumentException( 12968 "replacePreferredActivity expects filter to have only 1 action."); 12969 } 12970 if (filter.countDataAuthorities() != 0 12971 || filter.countDataPaths() != 0 12972 || filter.countDataSchemes() > 1 12973 || filter.countDataTypes() != 0) { 12974 throw new IllegalArgumentException( 12975 "replacePreferredActivity expects filter to have no data authorities, " + 12976 "paths, or types; and at most one scheme."); 12977 } 12978 12979 final int callingUid = Binder.getCallingUid(); 12980 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12981 synchronized (mPackages) { 12982 if (mContext.checkCallingOrSelfPermission( 12983 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12984 != PackageManager.PERMISSION_GRANTED) { 12985 if (getUidTargetSdkVersionLockedLPr(callingUid) 12986 < Build.VERSION_CODES.FROYO) { 12987 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12988 + Binder.getCallingUid()); 12989 return; 12990 } 12991 mContext.enforceCallingOrSelfPermission( 12992 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12993 } 12994 12995 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12996 if (pir != null) { 12997 // Get all of the existing entries that exactly match this filter. 12998 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12999 if (existing != null && existing.size() == 1) { 13000 PreferredActivity cur = existing.get(0); 13001 if (DEBUG_PREFERRED) { 13002 Slog.i(TAG, "Checking replace of preferred:"); 13003 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13004 if (!cur.mPref.mAlways) { 13005 Slog.i(TAG, " -- CUR; not mAlways!"); 13006 } else { 13007 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13008 Slog.i(TAG, " -- CUR: mSet=" 13009 + Arrays.toString(cur.mPref.mSetComponents)); 13010 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13011 Slog.i(TAG, " -- NEW: mMatch=" 13012 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13013 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13014 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13015 } 13016 } 13017 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13018 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13019 && cur.mPref.sameSet(set)) { 13020 // Setting the preferred activity to what it happens to be already 13021 if (DEBUG_PREFERRED) { 13022 Slog.i(TAG, "Replacing with same preferred activity " 13023 + cur.mPref.mShortComponent + " for user " 13024 + userId + ":"); 13025 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13026 } 13027 return; 13028 } 13029 } 13030 13031 if (existing != null) { 13032 if (DEBUG_PREFERRED) { 13033 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13034 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13035 } 13036 for (int i = 0; i < existing.size(); i++) { 13037 PreferredActivity pa = existing.get(i); 13038 if (DEBUG_PREFERRED) { 13039 Slog.i(TAG, "Removing existing preferred activity " 13040 + pa.mPref.mComponent + ":"); 13041 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13042 } 13043 pir.removeFilter(pa); 13044 } 13045 } 13046 } 13047 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13048 "Replacing preferred"); 13049 } 13050 } 13051 13052 @Override 13053 public void clearPackagePreferredActivities(String packageName) { 13054 final int uid = Binder.getCallingUid(); 13055 // writer 13056 synchronized (mPackages) { 13057 PackageParser.Package pkg = mPackages.get(packageName); 13058 if (pkg == null || pkg.applicationInfo.uid != uid) { 13059 if (mContext.checkCallingOrSelfPermission( 13060 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13061 != PackageManager.PERMISSION_GRANTED) { 13062 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13063 < Build.VERSION_CODES.FROYO) { 13064 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13065 + Binder.getCallingUid()); 13066 return; 13067 } 13068 mContext.enforceCallingOrSelfPermission( 13069 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13070 } 13071 } 13072 13073 int user = UserHandle.getCallingUserId(); 13074 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13075 scheduleWritePackageRestrictionsLocked(user); 13076 } 13077 } 13078 } 13079 13080 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13081 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13082 ArrayList<PreferredActivity> removed = null; 13083 boolean changed = false; 13084 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13085 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13086 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13087 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13088 continue; 13089 } 13090 Iterator<PreferredActivity> it = pir.filterIterator(); 13091 while (it.hasNext()) { 13092 PreferredActivity pa = it.next(); 13093 // Mark entry for removal only if it matches the package name 13094 // and the entry is of type "always". 13095 if (packageName == null || 13096 (pa.mPref.mComponent.getPackageName().equals(packageName) 13097 && pa.mPref.mAlways)) { 13098 if (removed == null) { 13099 removed = new ArrayList<PreferredActivity>(); 13100 } 13101 removed.add(pa); 13102 } 13103 } 13104 if (removed != null) { 13105 for (int j=0; j<removed.size(); j++) { 13106 PreferredActivity pa = removed.get(j); 13107 pir.removeFilter(pa); 13108 } 13109 changed = true; 13110 } 13111 } 13112 return changed; 13113 } 13114 13115 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13116 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13117 if (userId == UserHandle.USER_ALL) { 13118 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13119 sUserManager.getUserIds())) { 13120 for (int oneUserId : sUserManager.getUserIds()) { 13121 scheduleWritePackageRestrictionsLocked(oneUserId); 13122 } 13123 } 13124 } else { 13125 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13126 scheduleWritePackageRestrictionsLocked(userId); 13127 } 13128 } 13129 } 13130 13131 13132 void clearDefaultBrowserIfNeeded(String packageName) { 13133 for (int oneUserId : sUserManager.getUserIds()) { 13134 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13135 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13136 if (packageName.equals(defaultBrowserPackageName)) { 13137 setDefaultBrowserPackageName(null, oneUserId); 13138 } 13139 } 13140 } 13141 13142 @Override 13143 public void resetPreferredActivities(int userId) { 13144 /* TODO: Actually use userId. Why is it being passed in? */ 13145 mContext.enforceCallingOrSelfPermission( 13146 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13147 // writer 13148 synchronized (mPackages) { 13149 int user = UserHandle.getCallingUserId(); 13150 clearPackagePreferredActivitiesLPw(null, user); 13151 mSettings.readDefaultPreferredAppsLPw(this, user); 13152 scheduleWritePackageRestrictionsLocked(user); 13153 } 13154 } 13155 13156 @Override 13157 public int getPreferredActivities(List<IntentFilter> outFilters, 13158 List<ComponentName> outActivities, String packageName) { 13159 13160 int num = 0; 13161 final int userId = UserHandle.getCallingUserId(); 13162 // reader 13163 synchronized (mPackages) { 13164 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13165 if (pir != null) { 13166 final Iterator<PreferredActivity> it = pir.filterIterator(); 13167 while (it.hasNext()) { 13168 final PreferredActivity pa = it.next(); 13169 if (packageName == null 13170 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13171 && pa.mPref.mAlways)) { 13172 if (outFilters != null) { 13173 outFilters.add(new IntentFilter(pa)); 13174 } 13175 if (outActivities != null) { 13176 outActivities.add(pa.mPref.mComponent); 13177 } 13178 } 13179 } 13180 } 13181 } 13182 13183 return num; 13184 } 13185 13186 @Override 13187 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13188 int userId) { 13189 int callingUid = Binder.getCallingUid(); 13190 if (callingUid != Process.SYSTEM_UID) { 13191 throw new SecurityException( 13192 "addPersistentPreferredActivity can only be run by the system"); 13193 } 13194 if (filter.countActions() == 0) { 13195 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13196 return; 13197 } 13198 synchronized (mPackages) { 13199 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13200 " :"); 13201 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13202 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13203 new PersistentPreferredActivity(filter, activity)); 13204 scheduleWritePackageRestrictionsLocked(userId); 13205 } 13206 } 13207 13208 @Override 13209 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13210 int callingUid = Binder.getCallingUid(); 13211 if (callingUid != Process.SYSTEM_UID) { 13212 throw new SecurityException( 13213 "clearPackagePersistentPreferredActivities can only be run by the system"); 13214 } 13215 ArrayList<PersistentPreferredActivity> removed = null; 13216 boolean changed = false; 13217 synchronized (mPackages) { 13218 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13219 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13220 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13221 .valueAt(i); 13222 if (userId != thisUserId) { 13223 continue; 13224 } 13225 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13226 while (it.hasNext()) { 13227 PersistentPreferredActivity ppa = it.next(); 13228 // Mark entry for removal only if it matches the package name. 13229 if (ppa.mComponent.getPackageName().equals(packageName)) { 13230 if (removed == null) { 13231 removed = new ArrayList<PersistentPreferredActivity>(); 13232 } 13233 removed.add(ppa); 13234 } 13235 } 13236 if (removed != null) { 13237 for (int j=0; j<removed.size(); j++) { 13238 PersistentPreferredActivity ppa = removed.get(j); 13239 ppir.removeFilter(ppa); 13240 } 13241 changed = true; 13242 } 13243 } 13244 13245 if (changed) { 13246 scheduleWritePackageRestrictionsLocked(userId); 13247 } 13248 } 13249 } 13250 13251 /** 13252 * Non-Binder method, support for the backup/restore mechanism: write the 13253 * full set of preferred activities in its canonical XML format. Returns true 13254 * on success; false otherwise. 13255 */ 13256 @Override 13257 public byte[] getPreferredActivityBackup(int userId) { 13258 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13259 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13260 } 13261 13262 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13263 try { 13264 final XmlSerializer serializer = new FastXmlSerializer(); 13265 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13266 serializer.startDocument(null, true); 13267 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13268 13269 synchronized (mPackages) { 13270 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13271 } 13272 13273 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13274 serializer.endDocument(); 13275 serializer.flush(); 13276 } catch (Exception e) { 13277 if (DEBUG_BACKUP) { 13278 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13279 } 13280 return null; 13281 } 13282 13283 return dataStream.toByteArray(); 13284 } 13285 13286 @Override 13287 public void restorePreferredActivities(byte[] backup, int userId) { 13288 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13289 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13290 } 13291 13292 try { 13293 final XmlPullParser parser = Xml.newPullParser(); 13294 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13295 13296 int type; 13297 while ((type = parser.next()) != XmlPullParser.START_TAG 13298 && type != XmlPullParser.END_DOCUMENT) { 13299 } 13300 if (type != XmlPullParser.START_TAG) { 13301 // oops didn't find a start tag?! 13302 if (DEBUG_BACKUP) { 13303 Slog.e(TAG, "Didn't find start tag during restore"); 13304 } 13305 return; 13306 } 13307 13308 // this is supposed to be TAG_PREFERRED_BACKUP 13309 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13310 if (DEBUG_BACKUP) { 13311 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13312 } 13313 return; 13314 } 13315 13316 // skip interfering stuff, then we're aligned with the backing implementation 13317 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13318 synchronized (mPackages) { 13319 mSettings.readPreferredActivitiesLPw(parser, userId); 13320 } 13321 } catch (Exception e) { 13322 if (DEBUG_BACKUP) { 13323 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13324 } 13325 } 13326 } 13327 13328 @Override 13329 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13330 int sourceUserId, int targetUserId, int flags) { 13331 mContext.enforceCallingOrSelfPermission( 13332 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13333 int callingUid = Binder.getCallingUid(); 13334 enforceOwnerRights(ownerPackage, callingUid); 13335 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13336 if (intentFilter.countActions() == 0) { 13337 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13338 return; 13339 } 13340 synchronized (mPackages) { 13341 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13342 ownerPackage, targetUserId, flags); 13343 CrossProfileIntentResolver resolver = 13344 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13345 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13346 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13347 if (existing != null) { 13348 int size = existing.size(); 13349 for (int i = 0; i < size; i++) { 13350 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13351 return; 13352 } 13353 } 13354 } 13355 resolver.addFilter(newFilter); 13356 scheduleWritePackageRestrictionsLocked(sourceUserId); 13357 } 13358 } 13359 13360 @Override 13361 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13362 mContext.enforceCallingOrSelfPermission( 13363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13364 int callingUid = Binder.getCallingUid(); 13365 enforceOwnerRights(ownerPackage, callingUid); 13366 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13367 synchronized (mPackages) { 13368 CrossProfileIntentResolver resolver = 13369 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13370 ArraySet<CrossProfileIntentFilter> set = 13371 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13372 for (CrossProfileIntentFilter filter : set) { 13373 if (filter.getOwnerPackage().equals(ownerPackage)) { 13374 resolver.removeFilter(filter); 13375 } 13376 } 13377 scheduleWritePackageRestrictionsLocked(sourceUserId); 13378 } 13379 } 13380 13381 // Enforcing that callingUid is owning pkg on userId 13382 private void enforceOwnerRights(String pkg, int callingUid) { 13383 // The system owns everything. 13384 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13385 return; 13386 } 13387 int callingUserId = UserHandle.getUserId(callingUid); 13388 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13389 if (pi == null) { 13390 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13391 + callingUserId); 13392 } 13393 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13394 throw new SecurityException("Calling uid " + callingUid 13395 + " does not own package " + pkg); 13396 } 13397 } 13398 13399 @Override 13400 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13401 Intent intent = new Intent(Intent.ACTION_MAIN); 13402 intent.addCategory(Intent.CATEGORY_HOME); 13403 13404 final int callingUserId = UserHandle.getCallingUserId(); 13405 List<ResolveInfo> list = queryIntentActivities(intent, null, 13406 PackageManager.GET_META_DATA, callingUserId); 13407 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13408 true, false, false, callingUserId); 13409 13410 allHomeCandidates.clear(); 13411 if (list != null) { 13412 for (ResolveInfo ri : list) { 13413 allHomeCandidates.add(ri); 13414 } 13415 } 13416 return (preferred == null || preferred.activityInfo == null) 13417 ? null 13418 : new ComponentName(preferred.activityInfo.packageName, 13419 preferred.activityInfo.name); 13420 } 13421 13422 @Override 13423 public void setApplicationEnabledSetting(String appPackageName, 13424 int newState, int flags, int userId, String callingPackage) { 13425 if (!sUserManager.exists(userId)) return; 13426 if (callingPackage == null) { 13427 callingPackage = Integer.toString(Binder.getCallingUid()); 13428 } 13429 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13430 } 13431 13432 @Override 13433 public void setComponentEnabledSetting(ComponentName componentName, 13434 int newState, int flags, int userId) { 13435 if (!sUserManager.exists(userId)) return; 13436 setEnabledSetting(componentName.getPackageName(), 13437 componentName.getClassName(), newState, flags, userId, null); 13438 } 13439 13440 private void setEnabledSetting(final String packageName, String className, int newState, 13441 final int flags, int userId, String callingPackage) { 13442 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13443 || newState == COMPONENT_ENABLED_STATE_ENABLED 13444 || newState == COMPONENT_ENABLED_STATE_DISABLED 13445 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13446 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13447 throw new IllegalArgumentException("Invalid new component state: " 13448 + newState); 13449 } 13450 PackageSetting pkgSetting; 13451 final int uid = Binder.getCallingUid(); 13452 final int permission = mContext.checkCallingOrSelfPermission( 13453 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13454 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13455 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13456 boolean sendNow = false; 13457 boolean isApp = (className == null); 13458 String componentName = isApp ? packageName : className; 13459 int packageUid = -1; 13460 ArrayList<String> components; 13461 13462 // writer 13463 synchronized (mPackages) { 13464 pkgSetting = mSettings.mPackages.get(packageName); 13465 if (pkgSetting == null) { 13466 if (className == null) { 13467 throw new IllegalArgumentException( 13468 "Unknown package: " + packageName); 13469 } 13470 throw new IllegalArgumentException( 13471 "Unknown component: " + packageName 13472 + "/" + className); 13473 } 13474 // Allow root and verify that userId is not being specified by a different user 13475 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13476 throw new SecurityException( 13477 "Permission Denial: attempt to change component state from pid=" 13478 + Binder.getCallingPid() 13479 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13480 } 13481 if (className == null) { 13482 // We're dealing with an application/package level state change 13483 if (pkgSetting.getEnabled(userId) == newState) { 13484 // Nothing to do 13485 return; 13486 } 13487 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13488 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13489 // Don't care about who enables an app. 13490 callingPackage = null; 13491 } 13492 pkgSetting.setEnabled(newState, userId, callingPackage); 13493 // pkgSetting.pkg.mSetEnabled = newState; 13494 } else { 13495 // We're dealing with a component level state change 13496 // First, verify that this is a valid class name. 13497 PackageParser.Package pkg = pkgSetting.pkg; 13498 if (pkg == null || !pkg.hasComponentClassName(className)) { 13499 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13500 throw new IllegalArgumentException("Component class " + className 13501 + " does not exist in " + packageName); 13502 } else { 13503 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13504 + className + " does not exist in " + packageName); 13505 } 13506 } 13507 switch (newState) { 13508 case COMPONENT_ENABLED_STATE_ENABLED: 13509 if (!pkgSetting.enableComponentLPw(className, userId)) { 13510 return; 13511 } 13512 break; 13513 case COMPONENT_ENABLED_STATE_DISABLED: 13514 if (!pkgSetting.disableComponentLPw(className, userId)) { 13515 return; 13516 } 13517 break; 13518 case COMPONENT_ENABLED_STATE_DEFAULT: 13519 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13520 return; 13521 } 13522 break; 13523 default: 13524 Slog.e(TAG, "Invalid new component state: " + newState); 13525 return; 13526 } 13527 } 13528 scheduleWritePackageRestrictionsLocked(userId); 13529 components = mPendingBroadcasts.get(userId, packageName); 13530 final boolean newPackage = components == null; 13531 if (newPackage) { 13532 components = new ArrayList<String>(); 13533 } 13534 if (!components.contains(componentName)) { 13535 components.add(componentName); 13536 } 13537 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13538 sendNow = true; 13539 // Purge entry from pending broadcast list if another one exists already 13540 // since we are sending one right away. 13541 mPendingBroadcasts.remove(userId, packageName); 13542 } else { 13543 if (newPackage) { 13544 mPendingBroadcasts.put(userId, packageName, components); 13545 } 13546 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13547 // Schedule a message 13548 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13549 } 13550 } 13551 } 13552 13553 long callingId = Binder.clearCallingIdentity(); 13554 try { 13555 if (sendNow) { 13556 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13557 sendPackageChangedBroadcast(packageName, 13558 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13559 } 13560 } finally { 13561 Binder.restoreCallingIdentity(callingId); 13562 } 13563 } 13564 13565 private void sendPackageChangedBroadcast(String packageName, 13566 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13567 if (DEBUG_INSTALL) 13568 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13569 + componentNames); 13570 Bundle extras = new Bundle(4); 13571 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13572 String nameList[] = new String[componentNames.size()]; 13573 componentNames.toArray(nameList); 13574 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13575 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13576 extras.putInt(Intent.EXTRA_UID, packageUid); 13577 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13578 new int[] {UserHandle.getUserId(packageUid)}); 13579 } 13580 13581 @Override 13582 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13583 if (!sUserManager.exists(userId)) return; 13584 final int uid = Binder.getCallingUid(); 13585 final int permission = mContext.checkCallingOrSelfPermission( 13586 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13587 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13588 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13589 // writer 13590 synchronized (mPackages) { 13591 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13592 allowedByPermission, uid, userId)) { 13593 scheduleWritePackageRestrictionsLocked(userId); 13594 } 13595 } 13596 } 13597 13598 @Override 13599 public String getInstallerPackageName(String packageName) { 13600 // reader 13601 synchronized (mPackages) { 13602 return mSettings.getInstallerPackageNameLPr(packageName); 13603 } 13604 } 13605 13606 @Override 13607 public int getApplicationEnabledSetting(String packageName, int userId) { 13608 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13609 int uid = Binder.getCallingUid(); 13610 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13611 // reader 13612 synchronized (mPackages) { 13613 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13614 } 13615 } 13616 13617 @Override 13618 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13619 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13620 int uid = Binder.getCallingUid(); 13621 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13622 // reader 13623 synchronized (mPackages) { 13624 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13625 } 13626 } 13627 13628 @Override 13629 public void enterSafeMode() { 13630 enforceSystemOrRoot("Only the system can request entering safe mode"); 13631 13632 if (!mSystemReady) { 13633 mSafeMode = true; 13634 } 13635 } 13636 13637 @Override 13638 public void systemReady() { 13639 mSystemReady = true; 13640 13641 // Read the compatibilty setting when the system is ready. 13642 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13643 mContext.getContentResolver(), 13644 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13645 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13646 if (DEBUG_SETTINGS) { 13647 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13648 } 13649 13650 synchronized (mPackages) { 13651 // Verify that all of the preferred activity components actually 13652 // exist. It is possible for applications to be updated and at 13653 // that point remove a previously declared activity component that 13654 // had been set as a preferred activity. We try to clean this up 13655 // the next time we encounter that preferred activity, but it is 13656 // possible for the user flow to never be able to return to that 13657 // situation so here we do a sanity check to make sure we haven't 13658 // left any junk around. 13659 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13660 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13661 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13662 removed.clear(); 13663 for (PreferredActivity pa : pir.filterSet()) { 13664 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13665 removed.add(pa); 13666 } 13667 } 13668 if (removed.size() > 0) { 13669 for (int r=0; r<removed.size(); r++) { 13670 PreferredActivity pa = removed.get(r); 13671 Slog.w(TAG, "Removing dangling preferred activity: " 13672 + pa.mPref.mComponent); 13673 pir.removeFilter(pa); 13674 } 13675 mSettings.writePackageRestrictionsLPr( 13676 mSettings.mPreferredActivities.keyAt(i)); 13677 } 13678 } 13679 } 13680 sUserManager.systemReady(); 13681 13682 // Kick off any messages waiting for system ready 13683 if (mPostSystemReadyMessages != null) { 13684 for (Message msg : mPostSystemReadyMessages) { 13685 msg.sendToTarget(); 13686 } 13687 mPostSystemReadyMessages = null; 13688 } 13689 13690 // Watch for external volumes that come and go over time 13691 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13692 storage.registerListener(mStorageListener); 13693 13694 mInstallerService.systemReady(); 13695 mPackageDexOptimizer.systemReady(); 13696 } 13697 13698 @Override 13699 public boolean isSafeMode() { 13700 return mSafeMode; 13701 } 13702 13703 @Override 13704 public boolean hasSystemUidErrors() { 13705 return mHasSystemUidErrors; 13706 } 13707 13708 static String arrayToString(int[] array) { 13709 StringBuffer buf = new StringBuffer(128); 13710 buf.append('['); 13711 if (array != null) { 13712 for (int i=0; i<array.length; i++) { 13713 if (i > 0) buf.append(", "); 13714 buf.append(array[i]); 13715 } 13716 } 13717 buf.append(']'); 13718 return buf.toString(); 13719 } 13720 13721 static class DumpState { 13722 public static final int DUMP_LIBS = 1 << 0; 13723 public static final int DUMP_FEATURES = 1 << 1; 13724 public static final int DUMP_RESOLVERS = 1 << 2; 13725 public static final int DUMP_PERMISSIONS = 1 << 3; 13726 public static final int DUMP_PACKAGES = 1 << 4; 13727 public static final int DUMP_SHARED_USERS = 1 << 5; 13728 public static final int DUMP_MESSAGES = 1 << 6; 13729 public static final int DUMP_PROVIDERS = 1 << 7; 13730 public static final int DUMP_VERIFIERS = 1 << 8; 13731 public static final int DUMP_PREFERRED = 1 << 9; 13732 public static final int DUMP_PREFERRED_XML = 1 << 10; 13733 public static final int DUMP_KEYSETS = 1 << 11; 13734 public static final int DUMP_VERSION = 1 << 12; 13735 public static final int DUMP_INSTALLS = 1 << 13; 13736 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13737 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13738 13739 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13740 13741 private int mTypes; 13742 13743 private int mOptions; 13744 13745 private boolean mTitlePrinted; 13746 13747 private SharedUserSetting mSharedUser; 13748 13749 public boolean isDumping(int type) { 13750 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13751 return true; 13752 } 13753 13754 return (mTypes & type) != 0; 13755 } 13756 13757 public void setDump(int type) { 13758 mTypes |= type; 13759 } 13760 13761 public boolean isOptionEnabled(int option) { 13762 return (mOptions & option) != 0; 13763 } 13764 13765 public void setOptionEnabled(int option) { 13766 mOptions |= option; 13767 } 13768 13769 public boolean onTitlePrinted() { 13770 final boolean printed = mTitlePrinted; 13771 mTitlePrinted = true; 13772 return printed; 13773 } 13774 13775 public boolean getTitlePrinted() { 13776 return mTitlePrinted; 13777 } 13778 13779 public void setTitlePrinted(boolean enabled) { 13780 mTitlePrinted = enabled; 13781 } 13782 13783 public SharedUserSetting getSharedUser() { 13784 return mSharedUser; 13785 } 13786 13787 public void setSharedUser(SharedUserSetting user) { 13788 mSharedUser = user; 13789 } 13790 } 13791 13792 @Override 13793 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13794 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13795 != PackageManager.PERMISSION_GRANTED) { 13796 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13797 + Binder.getCallingPid() 13798 + ", uid=" + Binder.getCallingUid() 13799 + " without permission " 13800 + android.Manifest.permission.DUMP); 13801 return; 13802 } 13803 13804 DumpState dumpState = new DumpState(); 13805 boolean fullPreferred = false; 13806 boolean checkin = false; 13807 13808 String packageName = null; 13809 13810 int opti = 0; 13811 while (opti < args.length) { 13812 String opt = args[opti]; 13813 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13814 break; 13815 } 13816 opti++; 13817 13818 if ("-a".equals(opt)) { 13819 // Right now we only know how to print all. 13820 } else if ("-h".equals(opt)) { 13821 pw.println("Package manager dump options:"); 13822 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13823 pw.println(" --checkin: dump for a checkin"); 13824 pw.println(" -f: print details of intent filters"); 13825 pw.println(" -h: print this help"); 13826 pw.println(" cmd may be one of:"); 13827 pw.println(" l[ibraries]: list known shared libraries"); 13828 pw.println(" f[ibraries]: list device features"); 13829 pw.println(" k[eysets]: print known keysets"); 13830 pw.println(" r[esolvers]: dump intent resolvers"); 13831 pw.println(" perm[issions]: dump permissions"); 13832 pw.println(" pref[erred]: print preferred package settings"); 13833 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13834 pw.println(" prov[iders]: dump content providers"); 13835 pw.println(" p[ackages]: dump installed packages"); 13836 pw.println(" s[hared-users]: dump shared user IDs"); 13837 pw.println(" m[essages]: print collected runtime messages"); 13838 pw.println(" v[erifiers]: print package verifier info"); 13839 pw.println(" version: print database version info"); 13840 pw.println(" write: write current settings now"); 13841 pw.println(" <package.name>: info about given package"); 13842 pw.println(" installs: details about install sessions"); 13843 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13844 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13845 return; 13846 } else if ("--checkin".equals(opt)) { 13847 checkin = true; 13848 } else if ("-f".equals(opt)) { 13849 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13850 } else { 13851 pw.println("Unknown argument: " + opt + "; use -h for help"); 13852 } 13853 } 13854 13855 // Is the caller requesting to dump a particular piece of data? 13856 if (opti < args.length) { 13857 String cmd = args[opti]; 13858 opti++; 13859 // Is this a package name? 13860 if ("android".equals(cmd) || cmd.contains(".")) { 13861 packageName = cmd; 13862 // When dumping a single package, we always dump all of its 13863 // filter information since the amount of data will be reasonable. 13864 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13865 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13866 dumpState.setDump(DumpState.DUMP_LIBS); 13867 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13868 dumpState.setDump(DumpState.DUMP_FEATURES); 13869 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13870 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13871 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13872 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13873 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13874 dumpState.setDump(DumpState.DUMP_PREFERRED); 13875 } else if ("preferred-xml".equals(cmd)) { 13876 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13877 if (opti < args.length && "--full".equals(args[opti])) { 13878 fullPreferred = true; 13879 opti++; 13880 } 13881 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13882 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13883 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13884 dumpState.setDump(DumpState.DUMP_PACKAGES); 13885 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13886 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13887 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13888 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13889 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13890 dumpState.setDump(DumpState.DUMP_MESSAGES); 13891 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13892 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13893 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13894 || "intent-filter-verifiers".equals(cmd)) { 13895 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13896 } else if ("version".equals(cmd)) { 13897 dumpState.setDump(DumpState.DUMP_VERSION); 13898 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13899 dumpState.setDump(DumpState.DUMP_KEYSETS); 13900 } else if ("installs".equals(cmd)) { 13901 dumpState.setDump(DumpState.DUMP_INSTALLS); 13902 } else if ("write".equals(cmd)) { 13903 synchronized (mPackages) { 13904 mSettings.writeLPr(); 13905 pw.println("Settings written."); 13906 return; 13907 } 13908 } 13909 } 13910 13911 if (checkin) { 13912 pw.println("vers,1"); 13913 } 13914 13915 // reader 13916 synchronized (mPackages) { 13917 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13918 if (!checkin) { 13919 if (dumpState.onTitlePrinted()) 13920 pw.println(); 13921 pw.println("Database versions:"); 13922 pw.print(" SDK Version:"); 13923 pw.print(" internal="); 13924 pw.print(mSettings.mInternalSdkPlatform); 13925 pw.print(" external="); 13926 pw.println(mSettings.mExternalSdkPlatform); 13927 pw.print(" DB Version:"); 13928 pw.print(" internal="); 13929 pw.print(mSettings.mInternalDatabaseVersion); 13930 pw.print(" external="); 13931 pw.println(mSettings.mExternalDatabaseVersion); 13932 } 13933 } 13934 13935 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13936 if (!checkin) { 13937 if (dumpState.onTitlePrinted()) 13938 pw.println(); 13939 pw.println("Verifiers:"); 13940 pw.print(" Required: "); 13941 pw.print(mRequiredVerifierPackage); 13942 pw.print(" (uid="); 13943 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13944 pw.println(")"); 13945 } else if (mRequiredVerifierPackage != null) { 13946 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13947 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13948 } 13949 } 13950 13951 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13952 packageName == null) { 13953 if (mIntentFilterVerifierComponent != null) { 13954 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13955 if (!checkin) { 13956 if (dumpState.onTitlePrinted()) 13957 pw.println(); 13958 pw.println("Intent Filter Verifier:"); 13959 pw.print(" Using: "); 13960 pw.print(verifierPackageName); 13961 pw.print(" (uid="); 13962 pw.print(getPackageUid(verifierPackageName, 0)); 13963 pw.println(")"); 13964 } else if (verifierPackageName != null) { 13965 pw.print("ifv,"); pw.print(verifierPackageName); 13966 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13967 } 13968 } else { 13969 pw.println(); 13970 pw.println("No Intent Filter Verifier available!"); 13971 } 13972 } 13973 13974 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13975 boolean printedHeader = false; 13976 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13977 while (it.hasNext()) { 13978 String name = it.next(); 13979 SharedLibraryEntry ent = mSharedLibraries.get(name); 13980 if (!checkin) { 13981 if (!printedHeader) { 13982 if (dumpState.onTitlePrinted()) 13983 pw.println(); 13984 pw.println("Libraries:"); 13985 printedHeader = true; 13986 } 13987 pw.print(" "); 13988 } else { 13989 pw.print("lib,"); 13990 } 13991 pw.print(name); 13992 if (!checkin) { 13993 pw.print(" -> "); 13994 } 13995 if (ent.path != null) { 13996 if (!checkin) { 13997 pw.print("(jar) "); 13998 pw.print(ent.path); 13999 } else { 14000 pw.print(",jar,"); 14001 pw.print(ent.path); 14002 } 14003 } else { 14004 if (!checkin) { 14005 pw.print("(apk) "); 14006 pw.print(ent.apk); 14007 } else { 14008 pw.print(",apk,"); 14009 pw.print(ent.apk); 14010 } 14011 } 14012 pw.println(); 14013 } 14014 } 14015 14016 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14017 if (dumpState.onTitlePrinted()) 14018 pw.println(); 14019 if (!checkin) { 14020 pw.println("Features:"); 14021 } 14022 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14023 while (it.hasNext()) { 14024 String name = it.next(); 14025 if (!checkin) { 14026 pw.print(" "); 14027 } else { 14028 pw.print("feat,"); 14029 } 14030 pw.println(name); 14031 } 14032 } 14033 14034 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14035 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14036 : "Activity Resolver Table:", " ", packageName, 14037 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14038 dumpState.setTitlePrinted(true); 14039 } 14040 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14041 : "Receiver Resolver Table:", " ", packageName, 14042 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14043 dumpState.setTitlePrinted(true); 14044 } 14045 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14046 : "Service Resolver Table:", " ", packageName, 14047 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14048 dumpState.setTitlePrinted(true); 14049 } 14050 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14051 : "Provider Resolver Table:", " ", packageName, 14052 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14053 dumpState.setTitlePrinted(true); 14054 } 14055 } 14056 14057 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14058 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14059 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14060 int user = mSettings.mPreferredActivities.keyAt(i); 14061 if (pir.dump(pw, 14062 dumpState.getTitlePrinted() 14063 ? "\nPreferred Activities User " + user + ":" 14064 : "Preferred Activities User " + user + ":", " ", 14065 packageName, true, false)) { 14066 dumpState.setTitlePrinted(true); 14067 } 14068 } 14069 } 14070 14071 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14072 pw.flush(); 14073 FileOutputStream fout = new FileOutputStream(fd); 14074 BufferedOutputStream str = new BufferedOutputStream(fout); 14075 XmlSerializer serializer = new FastXmlSerializer(); 14076 try { 14077 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14078 serializer.startDocument(null, true); 14079 serializer.setFeature( 14080 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14081 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14082 serializer.endDocument(); 14083 serializer.flush(); 14084 } catch (IllegalArgumentException e) { 14085 pw.println("Failed writing: " + e); 14086 } catch (IllegalStateException e) { 14087 pw.println("Failed writing: " + e); 14088 } catch (IOException e) { 14089 pw.println("Failed writing: " + e); 14090 } 14091 } 14092 14093 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 14094 pw.println(); 14095 int count = mSettings.mPackages.size(); 14096 if (count == 0) { 14097 pw.println("No domain preferred apps!"); 14098 pw.println(); 14099 } else { 14100 final String prefix = " "; 14101 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14102 if (allPackageSettings.size() == 0) { 14103 pw.println("No domain preferred apps!"); 14104 pw.println(); 14105 } else { 14106 pw.println("Domain preferred apps status:"); 14107 pw.println(); 14108 count = 0; 14109 for (PackageSetting ps : allPackageSettings) { 14110 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14111 if (ivi == null || ivi.getPackageName() == null) continue; 14112 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14113 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14114 pw.println(prefix + "Status: " + ivi.getStatusString()); 14115 pw.println(); 14116 count++; 14117 } 14118 if (count == 0) { 14119 pw.println(prefix + "No domain preferred app status!"); 14120 pw.println(); 14121 } 14122 for (int userId : sUserManager.getUserIds()) { 14123 pw.println("Domain preferred apps for User " + userId + ":"); 14124 pw.println(); 14125 count = 0; 14126 for (PackageSetting ps : allPackageSettings) { 14127 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14128 if (ivi == null || ivi.getPackageName() == null) { 14129 continue; 14130 } 14131 final int status = ps.getDomainVerificationStatusForUser(userId); 14132 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14133 continue; 14134 } 14135 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14136 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14137 String statusStr = IntentFilterVerificationInfo. 14138 getStatusStringFromValue(status); 14139 pw.println(prefix + "Status: " + statusStr); 14140 pw.println(); 14141 count++; 14142 } 14143 if (count == 0) { 14144 pw.println(prefix + "No domain preferred apps!"); 14145 pw.println(); 14146 } 14147 } 14148 } 14149 } 14150 } 14151 14152 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14153 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14154 if (packageName == null) { 14155 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14156 if (iperm == 0) { 14157 if (dumpState.onTitlePrinted()) 14158 pw.println(); 14159 pw.println("AppOp Permissions:"); 14160 } 14161 pw.print(" AppOp Permission "); 14162 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14163 pw.println(":"); 14164 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14165 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14166 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14167 } 14168 } 14169 } 14170 } 14171 14172 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14173 boolean printedSomething = false; 14174 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14175 if (packageName != null && !packageName.equals(p.info.packageName)) { 14176 continue; 14177 } 14178 if (!printedSomething) { 14179 if (dumpState.onTitlePrinted()) 14180 pw.println(); 14181 pw.println("Registered ContentProviders:"); 14182 printedSomething = true; 14183 } 14184 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14185 pw.print(" "); pw.println(p.toString()); 14186 } 14187 printedSomething = false; 14188 for (Map.Entry<String, PackageParser.Provider> entry : 14189 mProvidersByAuthority.entrySet()) { 14190 PackageParser.Provider p = entry.getValue(); 14191 if (packageName != null && !packageName.equals(p.info.packageName)) { 14192 continue; 14193 } 14194 if (!printedSomething) { 14195 if (dumpState.onTitlePrinted()) 14196 pw.println(); 14197 pw.println("ContentProvider Authorities:"); 14198 printedSomething = true; 14199 } 14200 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14201 pw.print(" "); pw.println(p.toString()); 14202 if (p.info != null && p.info.applicationInfo != null) { 14203 final String appInfo = p.info.applicationInfo.toString(); 14204 pw.print(" applicationInfo="); pw.println(appInfo); 14205 } 14206 } 14207 } 14208 14209 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14210 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14211 } 14212 14213 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14214 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14215 } 14216 14217 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14218 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14219 } 14220 14221 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14222 // XXX should handle packageName != null by dumping only install data that 14223 // the given package is involved with. 14224 if (dumpState.onTitlePrinted()) pw.println(); 14225 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14226 } 14227 14228 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14229 if (dumpState.onTitlePrinted()) pw.println(); 14230 mSettings.dumpReadMessagesLPr(pw, dumpState); 14231 14232 pw.println(); 14233 pw.println("Package warning messages:"); 14234 BufferedReader in = null; 14235 String line = null; 14236 try { 14237 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14238 while ((line = in.readLine()) != null) { 14239 if (line.contains("ignored: updated version")) continue; 14240 pw.println(line); 14241 } 14242 } catch (IOException ignored) { 14243 } finally { 14244 IoUtils.closeQuietly(in); 14245 } 14246 } 14247 14248 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14249 BufferedReader in = null; 14250 String line = null; 14251 try { 14252 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14253 while ((line = in.readLine()) != null) { 14254 if (line.contains("ignored: updated version")) continue; 14255 pw.print("msg,"); 14256 pw.println(line); 14257 } 14258 } catch (IOException ignored) { 14259 } finally { 14260 IoUtils.closeQuietly(in); 14261 } 14262 } 14263 } 14264 } 14265 14266 // ------- apps on sdcard specific code ------- 14267 static final boolean DEBUG_SD_INSTALL = false; 14268 14269 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14270 14271 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14272 14273 private boolean mMediaMounted = false; 14274 14275 static String getEncryptKey() { 14276 try { 14277 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14278 SD_ENCRYPTION_KEYSTORE_NAME); 14279 if (sdEncKey == null) { 14280 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14281 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14282 if (sdEncKey == null) { 14283 Slog.e(TAG, "Failed to create encryption keys"); 14284 return null; 14285 } 14286 } 14287 return sdEncKey; 14288 } catch (NoSuchAlgorithmException nsae) { 14289 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14290 return null; 14291 } catch (IOException ioe) { 14292 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14293 return null; 14294 } 14295 } 14296 14297 /* 14298 * Update media status on PackageManager. 14299 */ 14300 @Override 14301 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14302 int callingUid = Binder.getCallingUid(); 14303 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14304 throw new SecurityException("Media status can only be updated by the system"); 14305 } 14306 // reader; this apparently protects mMediaMounted, but should probably 14307 // be a different lock in that case. 14308 synchronized (mPackages) { 14309 Log.i(TAG, "Updating external media status from " 14310 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14311 + (mediaStatus ? "mounted" : "unmounted")); 14312 if (DEBUG_SD_INSTALL) 14313 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14314 + ", mMediaMounted=" + mMediaMounted); 14315 if (mediaStatus == mMediaMounted) { 14316 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14317 : 0, -1); 14318 mHandler.sendMessage(msg); 14319 return; 14320 } 14321 mMediaMounted = mediaStatus; 14322 } 14323 // Queue up an async operation since the package installation may take a 14324 // little while. 14325 mHandler.post(new Runnable() { 14326 public void run() { 14327 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14328 } 14329 }); 14330 } 14331 14332 /** 14333 * Called by MountService when the initial ASECs to scan are available. 14334 * Should block until all the ASEC containers are finished being scanned. 14335 */ 14336 public void scanAvailableAsecs() { 14337 updateExternalMediaStatusInner(true, false, false); 14338 if (mShouldRestoreconData) { 14339 SELinuxMMAC.setRestoreconDone(); 14340 mShouldRestoreconData = false; 14341 } 14342 } 14343 14344 /* 14345 * Collect information of applications on external media, map them against 14346 * existing containers and update information based on current mount status. 14347 * Please note that we always have to report status if reportStatus has been 14348 * set to true especially when unloading packages. 14349 */ 14350 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14351 boolean externalStorage) { 14352 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14353 int[] uidArr = EmptyArray.INT; 14354 14355 final String[] list = PackageHelper.getSecureContainerList(); 14356 if (ArrayUtils.isEmpty(list)) { 14357 Log.i(TAG, "No secure containers found"); 14358 } else { 14359 // Process list of secure containers and categorize them 14360 // as active or stale based on their package internal state. 14361 14362 // reader 14363 synchronized (mPackages) { 14364 for (String cid : list) { 14365 // Leave stages untouched for now; installer service owns them 14366 if (PackageInstallerService.isStageName(cid)) continue; 14367 14368 if (DEBUG_SD_INSTALL) 14369 Log.i(TAG, "Processing container " + cid); 14370 String pkgName = getAsecPackageName(cid); 14371 if (pkgName == null) { 14372 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14373 continue; 14374 } 14375 if (DEBUG_SD_INSTALL) 14376 Log.i(TAG, "Looking for pkg : " + pkgName); 14377 14378 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14379 if (ps == null) { 14380 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14381 continue; 14382 } 14383 14384 /* 14385 * Skip packages that are not external if we're unmounting 14386 * external storage. 14387 */ 14388 if (externalStorage && !isMounted && !isExternal(ps)) { 14389 continue; 14390 } 14391 14392 final AsecInstallArgs args = new AsecInstallArgs(cid, 14393 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14394 // The package status is changed only if the code path 14395 // matches between settings and the container id. 14396 if (ps.codePathString != null 14397 && ps.codePathString.startsWith(args.getCodePath())) { 14398 if (DEBUG_SD_INSTALL) { 14399 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14400 + " at code path: " + ps.codePathString); 14401 } 14402 14403 // We do have a valid package installed on sdcard 14404 processCids.put(args, ps.codePathString); 14405 final int uid = ps.appId; 14406 if (uid != -1) { 14407 uidArr = ArrayUtils.appendInt(uidArr, uid); 14408 } 14409 } else { 14410 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14411 + ps.codePathString); 14412 } 14413 } 14414 } 14415 14416 Arrays.sort(uidArr); 14417 } 14418 14419 // Process packages with valid entries. 14420 if (isMounted) { 14421 if (DEBUG_SD_INSTALL) 14422 Log.i(TAG, "Loading packages"); 14423 loadMediaPackages(processCids, uidArr); 14424 startCleaningPackages(); 14425 mInstallerService.onSecureContainersAvailable(); 14426 } else { 14427 if (DEBUG_SD_INSTALL) 14428 Log.i(TAG, "Unloading packages"); 14429 unloadMediaPackages(processCids, uidArr, reportStatus); 14430 } 14431 } 14432 14433 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14434 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14435 final int size = infos.size(); 14436 final String[] packageNames = new String[size]; 14437 final int[] packageUids = new int[size]; 14438 for (int i = 0; i < size; i++) { 14439 final ApplicationInfo info = infos.get(i); 14440 packageNames[i] = info.packageName; 14441 packageUids[i] = info.uid; 14442 } 14443 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14444 finishedReceiver); 14445 } 14446 14447 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14448 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14449 sendResourcesChangedBroadcast(mediaStatus, replacing, 14450 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14451 } 14452 14453 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14454 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14455 int size = pkgList.length; 14456 if (size > 0) { 14457 // Send broadcasts here 14458 Bundle extras = new Bundle(); 14459 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14460 if (uidArr != null) { 14461 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14462 } 14463 if (replacing) { 14464 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14465 } 14466 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14467 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14468 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14469 } 14470 } 14471 14472 /* 14473 * Look at potentially valid container ids from processCids If package 14474 * information doesn't match the one on record or package scanning fails, 14475 * the cid is added to list of removeCids. We currently don't delete stale 14476 * containers. 14477 */ 14478 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14479 ArrayList<String> pkgList = new ArrayList<String>(); 14480 Set<AsecInstallArgs> keys = processCids.keySet(); 14481 14482 for (AsecInstallArgs args : keys) { 14483 String codePath = processCids.get(args); 14484 if (DEBUG_SD_INSTALL) 14485 Log.i(TAG, "Loading container : " + args.cid); 14486 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14487 try { 14488 // Make sure there are no container errors first. 14489 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14490 Slog.e(TAG, "Failed to mount cid : " + args.cid 14491 + " when installing from sdcard"); 14492 continue; 14493 } 14494 // Check code path here. 14495 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14496 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14497 + " does not match one in settings " + codePath); 14498 continue; 14499 } 14500 // Parse package 14501 int parseFlags = mDefParseFlags; 14502 if (args.isExternalAsec()) { 14503 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14504 } 14505 if (args.isFwdLocked()) { 14506 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14507 } 14508 14509 synchronized (mInstallLock) { 14510 PackageParser.Package pkg = null; 14511 try { 14512 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14513 } catch (PackageManagerException e) { 14514 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14515 } 14516 // Scan the package 14517 if (pkg != null) { 14518 /* 14519 * TODO why is the lock being held? doPostInstall is 14520 * called in other places without the lock. This needs 14521 * to be straightened out. 14522 */ 14523 // writer 14524 synchronized (mPackages) { 14525 retCode = PackageManager.INSTALL_SUCCEEDED; 14526 pkgList.add(pkg.packageName); 14527 // Post process args 14528 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14529 pkg.applicationInfo.uid); 14530 } 14531 } else { 14532 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14533 } 14534 } 14535 14536 } finally { 14537 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14538 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14539 } 14540 } 14541 } 14542 // writer 14543 synchronized (mPackages) { 14544 // If the platform SDK has changed since the last time we booted, 14545 // we need to re-grant app permission to catch any new ones that 14546 // appear. This is really a hack, and means that apps can in some 14547 // cases get permissions that the user didn't initially explicitly 14548 // allow... it would be nice to have some better way to handle 14549 // this situation. 14550 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14551 if (regrantPermissions) 14552 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14553 + mSdkVersion + "; regranting permissions for external storage"); 14554 mSettings.mExternalSdkPlatform = mSdkVersion; 14555 14556 // Make sure group IDs have been assigned, and any permission 14557 // changes in other apps are accounted for 14558 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14559 | (regrantPermissions 14560 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14561 : 0)); 14562 14563 mSettings.updateExternalDatabaseVersion(); 14564 14565 // can downgrade to reader 14566 // Persist settings 14567 mSettings.writeLPr(); 14568 } 14569 // Send a broadcast to let everyone know we are done processing 14570 if (pkgList.size() > 0) { 14571 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14572 } 14573 } 14574 14575 /* 14576 * Utility method to unload a list of specified containers 14577 */ 14578 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14579 // Just unmount all valid containers. 14580 for (AsecInstallArgs arg : cidArgs) { 14581 synchronized (mInstallLock) { 14582 arg.doPostDeleteLI(false); 14583 } 14584 } 14585 } 14586 14587 /* 14588 * Unload packages mounted on external media. This involves deleting package 14589 * data from internal structures, sending broadcasts about diabled packages, 14590 * gc'ing to free up references, unmounting all secure containers 14591 * corresponding to packages on external media, and posting a 14592 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14593 * that we always have to post this message if status has been requested no 14594 * matter what. 14595 */ 14596 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14597 final boolean reportStatus) { 14598 if (DEBUG_SD_INSTALL) 14599 Log.i(TAG, "unloading media packages"); 14600 ArrayList<String> pkgList = new ArrayList<String>(); 14601 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14602 final Set<AsecInstallArgs> keys = processCids.keySet(); 14603 for (AsecInstallArgs args : keys) { 14604 String pkgName = args.getPackageName(); 14605 if (DEBUG_SD_INSTALL) 14606 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14607 // Delete package internally 14608 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14609 synchronized (mInstallLock) { 14610 boolean res = deletePackageLI(pkgName, null, false, null, null, 14611 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14612 if (res) { 14613 pkgList.add(pkgName); 14614 } else { 14615 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14616 failedList.add(args); 14617 } 14618 } 14619 } 14620 14621 // reader 14622 synchronized (mPackages) { 14623 // We didn't update the settings after removing each package; 14624 // write them now for all packages. 14625 mSettings.writeLPr(); 14626 } 14627 14628 // We have to absolutely send UPDATED_MEDIA_STATUS only 14629 // after confirming that all the receivers processed the ordered 14630 // broadcast when packages get disabled, force a gc to clean things up. 14631 // and unload all the containers. 14632 if (pkgList.size() > 0) { 14633 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14634 new IIntentReceiver.Stub() { 14635 public void performReceive(Intent intent, int resultCode, String data, 14636 Bundle extras, boolean ordered, boolean sticky, 14637 int sendingUser) throws RemoteException { 14638 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14639 reportStatus ? 1 : 0, 1, keys); 14640 mHandler.sendMessage(msg); 14641 } 14642 }); 14643 } else { 14644 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14645 keys); 14646 mHandler.sendMessage(msg); 14647 } 14648 } 14649 14650 private void loadPrivatePackages(VolumeInfo vol) { 14651 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14652 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14653 synchronized (mInstallLock) { 14654 synchronized (mPackages) { 14655 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14656 for (PackageSetting ps : packages) { 14657 final PackageParser.Package pkg; 14658 try { 14659 pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null); 14660 loaded.add(pkg.applicationInfo); 14661 } catch (PackageManagerException e) { 14662 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14663 } 14664 } 14665 14666 // TODO: regrant any permissions that changed based since original install 14667 14668 mSettings.writeLPr(); 14669 } 14670 } 14671 14672 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14673 sendResourcesChangedBroadcast(true, false, loaded, null); 14674 } 14675 14676 private void unloadPrivatePackages(VolumeInfo vol) { 14677 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14678 synchronized (mInstallLock) { 14679 synchronized (mPackages) { 14680 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14681 for (PackageSetting ps : packages) { 14682 if (ps.pkg == null) continue; 14683 14684 final ApplicationInfo info = ps.pkg.applicationInfo; 14685 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14686 if (deletePackageLI(ps.name, null, false, null, null, 14687 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14688 unloaded.add(info); 14689 } else { 14690 Slog.w(TAG, "Failed to unload " + ps.codePath); 14691 } 14692 } 14693 14694 mSettings.writeLPr(); 14695 } 14696 } 14697 14698 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14699 sendResourcesChangedBroadcast(false, false, unloaded, null); 14700 } 14701 14702 private void unfreezePackage(String packageName) { 14703 synchronized (mPackages) { 14704 final PackageSetting ps = mSettings.mPackages.get(packageName); 14705 if (ps != null) { 14706 ps.frozen = false; 14707 } 14708 } 14709 } 14710 14711 @Override 14712 public int movePackage(final String packageName, final String volumeUuid) { 14713 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14714 14715 final int moveId = mNextMoveId.getAndIncrement(); 14716 try { 14717 movePackageInternal(packageName, volumeUuid, moveId); 14718 } catch (PackageManagerException e) { 14719 Slog.w(TAG, "Failed to move " + packageName, e); 14720 mMoveCallbacks.notifyStatusChanged(moveId, 14721 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14722 } 14723 return moveId; 14724 } 14725 14726 private void movePackageInternal(final String packageName, final String volumeUuid, 14727 final int moveId) throws PackageManagerException { 14728 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14729 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14730 final PackageManager pm = mContext.getPackageManager(); 14731 14732 final boolean currentAsec; 14733 final String currentVolumeUuid; 14734 final File codeFile; 14735 final String installerPackageName; 14736 final String packageAbiOverride; 14737 final int appId; 14738 final String seinfo; 14739 final String label; 14740 14741 // reader 14742 synchronized (mPackages) { 14743 final PackageParser.Package pkg = mPackages.get(packageName); 14744 final PackageSetting ps = mSettings.mPackages.get(packageName); 14745 if (pkg == null || ps == null) { 14746 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14747 } 14748 14749 if (pkg.applicationInfo.isSystemApp()) { 14750 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14751 "Cannot move system application"); 14752 } 14753 14754 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14755 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14756 "Package already moved to " + volumeUuid); 14757 } 14758 14759 final File probe = new File(pkg.codePath); 14760 final File probeOat = new File(probe, "oat"); 14761 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14762 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14763 "Move only supported for modern cluster style installs"); 14764 } 14765 14766 if (ps.frozen) { 14767 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14768 "Failed to move already frozen package"); 14769 } 14770 ps.frozen = true; 14771 14772 currentAsec = pkg.applicationInfo.isForwardLocked() 14773 || pkg.applicationInfo.isExternalAsec(); 14774 currentVolumeUuid = ps.volumeUuid; 14775 codeFile = new File(pkg.codePath); 14776 installerPackageName = ps.installerPackageName; 14777 packageAbiOverride = ps.cpuAbiOverrideString; 14778 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14779 seinfo = pkg.applicationInfo.seinfo; 14780 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14781 } 14782 14783 // Now that we're guarded by frozen state, kill app during move 14784 killApplication(packageName, appId, "move pkg"); 14785 14786 final Bundle extras = new Bundle(); 14787 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14788 extras.putString(Intent.EXTRA_TITLE, label); 14789 mMoveCallbacks.notifyCreated(moveId, extras); 14790 14791 int installFlags; 14792 final boolean moveCompleteApp; 14793 final File measurePath; 14794 14795 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14796 installFlags = INSTALL_INTERNAL; 14797 moveCompleteApp = !currentAsec; 14798 measurePath = Environment.getDataAppDirectory(volumeUuid); 14799 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14800 installFlags = INSTALL_EXTERNAL; 14801 moveCompleteApp = false; 14802 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14803 } else { 14804 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14805 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14806 || !volume.isMountedWritable()) { 14807 unfreezePackage(packageName); 14808 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14809 "Move location not mounted private volume"); 14810 } 14811 14812 Preconditions.checkState(!currentAsec); 14813 14814 installFlags = INSTALL_INTERNAL; 14815 moveCompleteApp = true; 14816 measurePath = Environment.getDataAppDirectory(volumeUuid); 14817 } 14818 14819 final PackageStats stats = new PackageStats(null, -1); 14820 synchronized (mInstaller) { 14821 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14822 unfreezePackage(packageName); 14823 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14824 "Failed to measure package size"); 14825 } 14826 } 14827 14828 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14829 + stats.dataSize); 14830 14831 final long startFreeBytes = measurePath.getFreeSpace(); 14832 final long sizeBytes; 14833 if (moveCompleteApp) { 14834 sizeBytes = stats.codeSize + stats.dataSize; 14835 } else { 14836 sizeBytes = stats.codeSize; 14837 } 14838 14839 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14840 unfreezePackage(packageName); 14841 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14842 "Not enough free space to move"); 14843 } 14844 14845 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14846 14847 final CountDownLatch installedLatch = new CountDownLatch(1); 14848 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14849 @Override 14850 public void onUserActionRequired(Intent intent) throws RemoteException { 14851 throw new IllegalStateException(); 14852 } 14853 14854 @Override 14855 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14856 Bundle extras) throws RemoteException { 14857 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14858 + PackageManager.installStatusToString(returnCode, msg)); 14859 14860 installedLatch.countDown(); 14861 14862 // Regardless of success or failure of the move operation, 14863 // always unfreeze the package 14864 unfreezePackage(packageName); 14865 14866 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14867 switch (status) { 14868 case PackageInstaller.STATUS_SUCCESS: 14869 mMoveCallbacks.notifyStatusChanged(moveId, 14870 PackageManager.MOVE_SUCCEEDED); 14871 break; 14872 case PackageInstaller.STATUS_FAILURE_STORAGE: 14873 mMoveCallbacks.notifyStatusChanged(moveId, 14874 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14875 break; 14876 default: 14877 mMoveCallbacks.notifyStatusChanged(moveId, 14878 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14879 break; 14880 } 14881 } 14882 }; 14883 14884 final MoveInfo move; 14885 if (moveCompleteApp) { 14886 // Kick off a thread to report progress estimates 14887 new Thread() { 14888 @Override 14889 public void run() { 14890 while (true) { 14891 try { 14892 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14893 break; 14894 } 14895 } catch (InterruptedException ignored) { 14896 } 14897 14898 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14899 final int progress = 10 + (int) MathUtils.constrain( 14900 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14901 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14902 } 14903 } 14904 }.start(); 14905 14906 final String dataAppName = codeFile.getName(); 14907 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14908 dataAppName, appId, seinfo); 14909 } else { 14910 move = null; 14911 } 14912 14913 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14914 14915 final Message msg = mHandler.obtainMessage(INIT_COPY); 14916 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14917 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14918 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14919 mHandler.sendMessage(msg); 14920 } 14921 14922 @Override 14923 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14924 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14925 14926 final int realMoveId = mNextMoveId.getAndIncrement(); 14927 final Bundle extras = new Bundle(); 14928 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14929 mMoveCallbacks.notifyCreated(realMoveId, extras); 14930 14931 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14932 @Override 14933 public void onCreated(int moveId, Bundle extras) { 14934 // Ignored 14935 } 14936 14937 @Override 14938 public void onStatusChanged(int moveId, int status, long estMillis) { 14939 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14940 } 14941 }; 14942 14943 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14944 storage.setPrimaryStorageUuid(volumeUuid, callback); 14945 return realMoveId; 14946 } 14947 14948 @Override 14949 public int getMoveStatus(int moveId) { 14950 mContext.enforceCallingOrSelfPermission( 14951 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14952 return mMoveCallbacks.mLastStatus.get(moveId); 14953 } 14954 14955 @Override 14956 public void registerMoveCallback(IPackageMoveObserver callback) { 14957 mContext.enforceCallingOrSelfPermission( 14958 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14959 mMoveCallbacks.register(callback); 14960 } 14961 14962 @Override 14963 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14964 mContext.enforceCallingOrSelfPermission( 14965 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14966 mMoveCallbacks.unregister(callback); 14967 } 14968 14969 @Override 14970 public boolean setInstallLocation(int loc) { 14971 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14972 null); 14973 if (getInstallLocation() == loc) { 14974 return true; 14975 } 14976 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14977 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14978 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14979 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14980 return true; 14981 } 14982 return false; 14983 } 14984 14985 @Override 14986 public int getInstallLocation() { 14987 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14988 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14989 PackageHelper.APP_INSTALL_AUTO); 14990 } 14991 14992 /** Called by UserManagerService */ 14993 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14994 mDirtyUsers.remove(userHandle); 14995 mSettings.removeUserLPw(userHandle); 14996 mPendingBroadcasts.remove(userHandle); 14997 if (mInstaller != null) { 14998 // Technically, we shouldn't be doing this with the package lock 14999 // held. However, this is very rare, and there is already so much 15000 // other disk I/O going on, that we'll let it slide for now. 15001 final StorageManager storage = StorageManager.from(mContext); 15002 final List<VolumeInfo> vols = storage.getVolumes(); 15003 for (VolumeInfo vol : vols) { 15004 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15005 final String volumeUuid = vol.getFsUuid(); 15006 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15007 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15008 } 15009 } 15010 } 15011 mUserNeedsBadging.delete(userHandle); 15012 removeUnusedPackagesLILPw(userManager, userHandle); 15013 } 15014 15015 /** 15016 * We're removing userHandle and would like to remove any downloaded packages 15017 * that are no longer in use by any other user. 15018 * @param userHandle the user being removed 15019 */ 15020 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15021 final boolean DEBUG_CLEAN_APKS = false; 15022 int [] users = userManager.getUserIdsLPr(); 15023 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15024 while (psit.hasNext()) { 15025 PackageSetting ps = psit.next(); 15026 if (ps.pkg == null) { 15027 continue; 15028 } 15029 final String packageName = ps.pkg.packageName; 15030 // Skip over if system app 15031 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15032 continue; 15033 } 15034 if (DEBUG_CLEAN_APKS) { 15035 Slog.i(TAG, "Checking package " + packageName); 15036 } 15037 boolean keep = false; 15038 for (int i = 0; i < users.length; i++) { 15039 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15040 keep = true; 15041 if (DEBUG_CLEAN_APKS) { 15042 Slog.i(TAG, " Keeping package " + packageName + " for user " 15043 + users[i]); 15044 } 15045 break; 15046 } 15047 } 15048 if (!keep) { 15049 if (DEBUG_CLEAN_APKS) { 15050 Slog.i(TAG, " Removing package " + packageName); 15051 } 15052 mHandler.post(new Runnable() { 15053 public void run() { 15054 deletePackageX(packageName, userHandle, 0); 15055 } //end run 15056 }); 15057 } 15058 } 15059 } 15060 15061 /** Called by UserManagerService */ 15062 void createNewUserLILPw(int userHandle, File path) { 15063 if (mInstaller != null) { 15064 mInstaller.createUserConfig(userHandle); 15065 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15066 } 15067 } 15068 15069 void newUserCreatedLILPw(int userHandle) { 15070 // Adding a user requires updating runtime permissions for system apps. 15071 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 15072 } 15073 15074 @Override 15075 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15076 mContext.enforceCallingOrSelfPermission( 15077 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15078 "Only package verification agents can read the verifier device identity"); 15079 15080 synchronized (mPackages) { 15081 return mSettings.getVerifierDeviceIdentityLPw(); 15082 } 15083 } 15084 15085 @Override 15086 public void setPermissionEnforced(String permission, boolean enforced) { 15087 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15088 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15089 synchronized (mPackages) { 15090 if (mSettings.mReadExternalStorageEnforced == null 15091 || mSettings.mReadExternalStorageEnforced != enforced) { 15092 mSettings.mReadExternalStorageEnforced = enforced; 15093 mSettings.writeLPr(); 15094 } 15095 } 15096 // kill any non-foreground processes so we restart them and 15097 // grant/revoke the GID. 15098 final IActivityManager am = ActivityManagerNative.getDefault(); 15099 if (am != null) { 15100 final long token = Binder.clearCallingIdentity(); 15101 try { 15102 am.killProcessesBelowForeground("setPermissionEnforcement"); 15103 } catch (RemoteException e) { 15104 } finally { 15105 Binder.restoreCallingIdentity(token); 15106 } 15107 } 15108 } else { 15109 throw new IllegalArgumentException("No selective enforcement for " + permission); 15110 } 15111 } 15112 15113 @Override 15114 @Deprecated 15115 public boolean isPermissionEnforced(String permission) { 15116 return true; 15117 } 15118 15119 @Override 15120 public boolean isStorageLow() { 15121 final long token = Binder.clearCallingIdentity(); 15122 try { 15123 final DeviceStorageMonitorInternal 15124 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15125 if (dsm != null) { 15126 return dsm.isMemoryLow(); 15127 } else { 15128 return false; 15129 } 15130 } finally { 15131 Binder.restoreCallingIdentity(token); 15132 } 15133 } 15134 15135 @Override 15136 public IPackageInstaller getPackageInstaller() { 15137 return mInstallerService; 15138 } 15139 15140 private boolean userNeedsBadging(int userId) { 15141 int index = mUserNeedsBadging.indexOfKey(userId); 15142 if (index < 0) { 15143 final UserInfo userInfo; 15144 final long token = Binder.clearCallingIdentity(); 15145 try { 15146 userInfo = sUserManager.getUserInfo(userId); 15147 } finally { 15148 Binder.restoreCallingIdentity(token); 15149 } 15150 final boolean b; 15151 if (userInfo != null && userInfo.isManagedProfile()) { 15152 b = true; 15153 } else { 15154 b = false; 15155 } 15156 mUserNeedsBadging.put(userId, b); 15157 return b; 15158 } 15159 return mUserNeedsBadging.valueAt(index); 15160 } 15161 15162 @Override 15163 public KeySet getKeySetByAlias(String packageName, String alias) { 15164 if (packageName == null || alias == null) { 15165 return null; 15166 } 15167 synchronized(mPackages) { 15168 final PackageParser.Package pkg = mPackages.get(packageName); 15169 if (pkg == null) { 15170 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15171 throw new IllegalArgumentException("Unknown package: " + packageName); 15172 } 15173 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15174 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15175 } 15176 } 15177 15178 @Override 15179 public KeySet getSigningKeySet(String packageName) { 15180 if (packageName == null) { 15181 return null; 15182 } 15183 synchronized(mPackages) { 15184 final PackageParser.Package pkg = mPackages.get(packageName); 15185 if (pkg == null) { 15186 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15187 throw new IllegalArgumentException("Unknown package: " + packageName); 15188 } 15189 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15190 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15191 throw new SecurityException("May not access signing KeySet of other apps."); 15192 } 15193 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15194 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15195 } 15196 } 15197 15198 @Override 15199 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15200 if (packageName == null || ks == null) { 15201 return false; 15202 } 15203 synchronized(mPackages) { 15204 final PackageParser.Package pkg = mPackages.get(packageName); 15205 if (pkg == null) { 15206 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15207 throw new IllegalArgumentException("Unknown package: " + packageName); 15208 } 15209 IBinder ksh = ks.getToken(); 15210 if (ksh instanceof KeySetHandle) { 15211 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15212 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15213 } 15214 return false; 15215 } 15216 } 15217 15218 @Override 15219 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15220 if (packageName == null || ks == null) { 15221 return false; 15222 } 15223 synchronized(mPackages) { 15224 final PackageParser.Package pkg = mPackages.get(packageName); 15225 if (pkg == null) { 15226 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15227 throw new IllegalArgumentException("Unknown package: " + packageName); 15228 } 15229 IBinder ksh = ks.getToken(); 15230 if (ksh instanceof KeySetHandle) { 15231 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15232 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15233 } 15234 return false; 15235 } 15236 } 15237 15238 public void getUsageStatsIfNoPackageUsageInfo() { 15239 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15240 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15241 if (usm == null) { 15242 throw new IllegalStateException("UsageStatsManager must be initialized"); 15243 } 15244 long now = System.currentTimeMillis(); 15245 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15246 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15247 String packageName = entry.getKey(); 15248 PackageParser.Package pkg = mPackages.get(packageName); 15249 if (pkg == null) { 15250 continue; 15251 } 15252 UsageStats usage = entry.getValue(); 15253 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15254 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15255 } 15256 } 15257 } 15258 15259 /** 15260 * Check and throw if the given before/after packages would be considered a 15261 * downgrade. 15262 */ 15263 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15264 throws PackageManagerException { 15265 if (after.versionCode < before.mVersionCode) { 15266 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15267 "Update version code " + after.versionCode + " is older than current " 15268 + before.mVersionCode); 15269 } else if (after.versionCode == before.mVersionCode) { 15270 if (after.baseRevisionCode < before.baseRevisionCode) { 15271 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15272 "Update base revision code " + after.baseRevisionCode 15273 + " is older than current " + before.baseRevisionCode); 15274 } 15275 15276 if (!ArrayUtils.isEmpty(after.splitNames)) { 15277 for (int i = 0; i < after.splitNames.length; i++) { 15278 final String splitName = after.splitNames[i]; 15279 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15280 if (j != -1) { 15281 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15282 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15283 "Update split " + splitName + " revision code " 15284 + after.splitRevisionCodes[i] + " is older than current " 15285 + before.splitRevisionCodes[j]); 15286 } 15287 } 15288 } 15289 } 15290 } 15291 } 15292 15293 private static class MoveCallbacks extends Handler { 15294 private static final int MSG_CREATED = 1; 15295 private static final int MSG_STATUS_CHANGED = 2; 15296 15297 private final RemoteCallbackList<IPackageMoveObserver> 15298 mCallbacks = new RemoteCallbackList<>(); 15299 15300 private final SparseIntArray mLastStatus = new SparseIntArray(); 15301 15302 public MoveCallbacks(Looper looper) { 15303 super(looper); 15304 } 15305 15306 public void register(IPackageMoveObserver callback) { 15307 mCallbacks.register(callback); 15308 } 15309 15310 public void unregister(IPackageMoveObserver callback) { 15311 mCallbacks.unregister(callback); 15312 } 15313 15314 @Override 15315 public void handleMessage(Message msg) { 15316 final SomeArgs args = (SomeArgs) msg.obj; 15317 final int n = mCallbacks.beginBroadcast(); 15318 for (int i = 0; i < n; i++) { 15319 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15320 try { 15321 invokeCallback(callback, msg.what, args); 15322 } catch (RemoteException ignored) { 15323 } 15324 } 15325 mCallbacks.finishBroadcast(); 15326 args.recycle(); 15327 } 15328 15329 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15330 throws RemoteException { 15331 switch (what) { 15332 case MSG_CREATED: { 15333 callback.onCreated(args.argi1, (Bundle) args.arg2); 15334 break; 15335 } 15336 case MSG_STATUS_CHANGED: { 15337 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15338 break; 15339 } 15340 } 15341 } 15342 15343 private void notifyCreated(int moveId, Bundle extras) { 15344 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15345 15346 final SomeArgs args = SomeArgs.obtain(); 15347 args.argi1 = moveId; 15348 args.arg2 = extras; 15349 obtainMessage(MSG_CREATED, args).sendToTarget(); 15350 } 15351 15352 private void notifyStatusChanged(int moveId, int status) { 15353 notifyStatusChanged(moveId, status, -1); 15354 } 15355 15356 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15357 Slog.v(TAG, "Move " + moveId + " status " + status); 15358 15359 final SomeArgs args = SomeArgs.obtain(); 15360 args.argi1 = moveId; 15361 args.argi2 = status; 15362 args.arg3 = estMillis; 15363 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15364 15365 synchronized (mLastStatus) { 15366 mLastStatus.put(moveId, status); 15367 } 15368 } 15369 } 15370 15371 private final class OnPermissionChangeListeners extends Handler { 15372 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15373 15374 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15375 new RemoteCallbackList<>(); 15376 15377 public OnPermissionChangeListeners(Looper looper) { 15378 super(looper); 15379 } 15380 15381 @Override 15382 public void handleMessage(Message msg) { 15383 switch (msg.what) { 15384 case MSG_ON_PERMISSIONS_CHANGED: { 15385 final int uid = msg.arg1; 15386 handleOnPermissionsChanged(uid); 15387 } break; 15388 } 15389 } 15390 15391 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15392 mPermissionListeners.register(listener); 15393 15394 } 15395 15396 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15397 mPermissionListeners.unregister(listener); 15398 } 15399 15400 public void onPermissionsChanged(int uid) { 15401 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15402 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15403 } 15404 } 15405 15406 private void handleOnPermissionsChanged(int uid) { 15407 final int count = mPermissionListeners.beginBroadcast(); 15408 try { 15409 for (int i = 0; i < count; i++) { 15410 IOnPermissionsChangeListener callback = mPermissionListeners 15411 .getBroadcastItem(i); 15412 try { 15413 callback.onPermissionsChanged(uid); 15414 } catch (RemoteException e) { 15415 Log.e(TAG, "Permission listener is dead", e); 15416 } 15417 } 15418 } finally { 15419 mPermissionListeners.finishBroadcast(); 15420 } 15421 } 15422 } 15423} 15424