PackageManagerService.java revision 3ab6f9e691fac6eeea1af8fb35bd4c41cdd692ca
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.AppGlobals; 77import android.app.IActivityManager; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.app.usage.UsageStats; 81import android.app.usage.UsageStatsManager; 82import android.content.BroadcastReceiver; 83import android.content.ComponentName; 84import android.content.Context; 85import android.content.IIntentReceiver; 86import android.content.Intent; 87import android.content.IntentFilter; 88import android.content.IntentSender; 89import android.content.IntentSender.SendIntentException; 90import android.content.ServiceConnection; 91import android.content.pm.ActivityInfo; 92import android.content.pm.ApplicationInfo; 93import android.content.pm.FeatureInfo; 94import android.content.pm.IOnPermissionsChangeListener; 95import android.content.pm.IPackageDataObserver; 96import android.content.pm.IPackageDeleteObserver; 97import android.content.pm.IPackageDeleteObserver2; 98import android.content.pm.IPackageInstallObserver2; 99import android.content.pm.IPackageInstaller; 100import android.content.pm.IPackageManager; 101import android.content.pm.IPackageMoveObserver; 102import android.content.pm.IPackageStatsObserver; 103import android.content.pm.InstrumentationInfo; 104import android.content.pm.IntentFilterVerificationInfo; 105import android.content.pm.KeySet; 106import android.content.pm.ManifestDigest; 107import android.content.pm.PackageCleanItem; 108import android.content.pm.PackageInfo; 109import android.content.pm.PackageInfoLite; 110import android.content.pm.PackageInstaller; 111import android.content.pm.PackageManager; 112import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 113import android.content.pm.PackageManagerInternal; 114import android.content.pm.PackageParser; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageStats; 119import android.content.pm.PackageUserState; 120import android.content.pm.ParceledListSlice; 121import android.content.pm.PermissionGroupInfo; 122import android.content.pm.PermissionInfo; 123import android.content.pm.ProviderInfo; 124import android.content.pm.ResolveInfo; 125import android.content.pm.ServiceInfo; 126import android.content.pm.Signature; 127import android.content.pm.UserInfo; 128import android.content.pm.VerificationParams; 129import android.content.pm.VerifierDeviceIdentity; 130import android.content.pm.VerifierInfo; 131import android.content.res.Resources; 132import android.hardware.display.DisplayManager; 133import android.net.Uri; 134import android.os.Binder; 135import android.os.Build; 136import android.os.Bundle; 137import android.os.Debug; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.FileUtils; 141import android.os.Handler; 142import android.os.IBinder; 143import android.os.Looper; 144import android.os.Message; 145import android.os.Parcel; 146import android.os.ParcelFileDescriptor; 147import android.os.Process; 148import android.os.RemoteCallbackList; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.os.storage.IMountService; 157import android.os.storage.StorageEventListener; 158import android.os.storage.StorageManager; 159import android.os.storage.VolumeInfo; 160import android.os.storage.VolumeRecord; 161import android.security.KeyStore; 162import android.security.SystemKeyStore; 163import android.system.ErrnoException; 164import android.system.Os; 165import android.system.StructStat; 166import android.text.TextUtils; 167import android.text.format.DateUtils; 168import android.util.ArrayMap; 169import android.util.ArraySet; 170import android.util.AtomicFile; 171import android.util.DisplayMetrics; 172import android.util.EventLog; 173import android.util.ExceptionUtils; 174import android.util.Log; 175import android.util.LogPrinter; 176import android.util.MathUtils; 177import android.util.PrintStreamPrinter; 178import android.util.Slog; 179import android.util.SparseArray; 180import android.util.SparseBooleanArray; 181import android.util.SparseIntArray; 182import android.util.Xml; 183import android.view.Display; 184 185import dalvik.system.DexFile; 186import dalvik.system.VMRuntime; 187 188import libcore.io.IoUtils; 189import libcore.util.EmptyArray; 190 191import com.android.internal.R; 192import com.android.internal.app.IMediaContainerService; 193import com.android.internal.app.ResolverActivity; 194import com.android.internal.content.NativeLibraryHelper; 195import com.android.internal.content.PackageHelper; 196import com.android.internal.os.IParcelFileDescriptorFactory; 197import com.android.internal.os.SomeArgs; 198import com.android.internal.util.ArrayUtils; 199import com.android.internal.util.FastPrintWriter; 200import com.android.internal.util.FastXmlSerializer; 201import com.android.internal.util.IndentingPrintWriter; 202import com.android.internal.util.Preconditions; 203import com.android.server.EventLogTags; 204import com.android.server.FgThread; 205import com.android.server.IntentResolver; 206import com.android.server.LocalServices; 207import com.android.server.ServiceThread; 208import com.android.server.SystemConfig; 209import com.android.server.Watchdog; 210import com.android.server.pm.Settings.DatabaseVersion; 211import com.android.server.pm.PermissionsState.PermissionState; 212import com.android.server.storage.DeviceStorageMonitorInternal; 213 214import org.xmlpull.v1.XmlPullParser; 215import org.xmlpull.v1.XmlSerializer; 216 217import java.io.BufferedInputStream; 218import java.io.BufferedOutputStream; 219import java.io.BufferedReader; 220import java.io.ByteArrayInputStream; 221import java.io.ByteArrayOutputStream; 222import java.io.File; 223import java.io.FileDescriptor; 224import java.io.FileNotFoundException; 225import java.io.FileOutputStream; 226import java.io.FileReader; 227import java.io.FilenameFilter; 228import java.io.IOException; 229import java.io.InputStream; 230import java.io.PrintWriter; 231import java.nio.charset.StandardCharsets; 232import java.security.NoSuchAlgorithmException; 233import java.security.PublicKey; 234import java.security.cert.CertificateEncodingException; 235import java.security.cert.CertificateException; 236import java.text.SimpleDateFormat; 237import java.util.ArrayList; 238import java.util.Arrays; 239import java.util.Collection; 240import java.util.Collections; 241import java.util.Comparator; 242import java.util.Date; 243import java.util.Iterator; 244import java.util.List; 245import java.util.Map; 246import java.util.Objects; 247import java.util.Set; 248import java.util.concurrent.CountDownLatch; 249import java.util.concurrent.TimeUnit; 250import java.util.concurrent.atomic.AtomicBoolean; 251import java.util.concurrent.atomic.AtomicInteger; 252import java.util.concurrent.atomic.AtomicLong; 253 254/** 255 * Keep track of all those .apks everywhere. 256 * 257 * This is very central to the platform's security; please run the unit 258 * tests whenever making modifications here: 259 * 260mmm frameworks/base/tests/AndroidTests 261adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 262adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 263 * 264 * {@hide} 265 */ 266public class PackageManagerService extends IPackageManager.Stub { 267 static final String TAG = "PackageManager"; 268 static final boolean DEBUG_SETTINGS = false; 269 static final boolean DEBUG_PREFERRED = false; 270 static final boolean DEBUG_UPGRADE = false; 271 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 272 private static final boolean DEBUG_BACKUP = true; 273 private static final boolean DEBUG_INSTALL = false; 274 private static final boolean DEBUG_REMOVE = false; 275 private static final boolean DEBUG_BROADCASTS = false; 276 private static final boolean DEBUG_SHOW_INFO = false; 277 private static final boolean DEBUG_PACKAGE_INFO = false; 278 private static final boolean DEBUG_INTENT_MATCHING = false; 279 private static final boolean DEBUG_PACKAGE_SCANNING = false; 280 private static final boolean DEBUG_VERIFY = false; 281 private static final boolean DEBUG_DEXOPT = false; 282 private static final boolean DEBUG_ABI_SELECTION = false; 283 284 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE; 285 286 private static final int RADIO_UID = Process.PHONE_UID; 287 private static final int LOG_UID = Process.LOG_UID; 288 private static final int NFC_UID = Process.NFC_UID; 289 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 290 private static final int SHELL_UID = Process.SHELL_UID; 291 292 // Cap the size of permission trees that 3rd party apps can define 293 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 294 295 // Suffix used during package installation when copying/moving 296 // package apks to install directory. 297 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 298 299 static final int SCAN_NO_DEX = 1<<1; 300 static final int SCAN_FORCE_DEX = 1<<2; 301 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 302 static final int SCAN_NEW_INSTALL = 1<<4; 303 static final int SCAN_NO_PATHS = 1<<5; 304 static final int SCAN_UPDATE_TIME = 1<<6; 305 static final int SCAN_DEFER_DEX = 1<<7; 306 static final int SCAN_BOOTING = 1<<8; 307 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 308 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 309 static final int SCAN_REQUIRE_KNOWN = 1<<12; 310 static final int SCAN_MOVE = 1<<13; 311 312 static final int REMOVE_CHATTY = 1<<16; 313 314 private static final int[] EMPTY_INT_ARRAY = new int[0]; 315 316 /** 317 * Timeout (in milliseconds) after which the watchdog should declare that 318 * our handler thread is wedged. The usual default for such things is one 319 * minute but we sometimes do very lengthy I/O operations on this thread, 320 * such as installing multi-gigabyte applications, so ours needs to be longer. 321 */ 322 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 323 324 /** 325 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 326 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 327 * settings entry if available, otherwise we use the hardcoded default. If it's been 328 * more than this long since the last fstrim, we force one during the boot sequence. 329 * 330 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 331 * one gets run at the next available charging+idle time. This final mandatory 332 * no-fstrim check kicks in only of the other scheduling criteria is never met. 333 */ 334 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 335 336 /** 337 * Whether verification is enabled by default. 338 */ 339 private static final boolean DEFAULT_VERIFY_ENABLE = true; 340 341 /** 342 * The default maximum time to wait for the verification agent to return in 343 * milliseconds. 344 */ 345 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 346 347 /** 348 * The default response for package verification timeout. 349 * 350 * This can be either PackageManager.VERIFICATION_ALLOW or 351 * PackageManager.VERIFICATION_REJECT. 352 */ 353 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 354 355 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 356 357 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 358 DEFAULT_CONTAINER_PACKAGE, 359 "com.android.defcontainer.DefaultContainerService"); 360 361 private static final String KILL_APP_REASON_GIDS_CHANGED = 362 "permission grant or revoke changed gids"; 363 364 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 365 "permissions revoked"; 366 367 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 368 369 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 370 371 /** Permission grant: not grant the permission. */ 372 private static final int GRANT_DENIED = 1; 373 374 /** Permission grant: grant the permission as an install permission. */ 375 private static final int GRANT_INSTALL = 2; 376 377 /** Permission grant: grant the permission as an install permission for a legacy app. */ 378 private static final int GRANT_INSTALL_LEGACY = 3; 379 380 /** Permission grant: grant the permission as a runtime one. */ 381 private static final int GRANT_RUNTIME = 4; 382 383 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 384 private static final int GRANT_UPGRADE = 5; 385 386 final ServiceThread mHandlerThread; 387 388 final PackageHandler mHandler; 389 390 /** 391 * Messages for {@link #mHandler} that need to wait for system ready before 392 * being dispatched. 393 */ 394 private ArrayList<Message> mPostSystemReadyMessages; 395 396 final int mSdkVersion = Build.VERSION.SDK_INT; 397 398 final Context mContext; 399 final boolean mFactoryTest; 400 final boolean mOnlyCore; 401 final boolean mLazyDexOpt; 402 final long mDexOptLRUThresholdInMills; 403 final DisplayMetrics mMetrics; 404 final int mDefParseFlags; 405 final String[] mSeparateProcesses; 406 final boolean mIsUpgrade; 407 408 // This is where all application persistent data goes. 409 final File mAppDataDir; 410 411 // This is where all application persistent data goes for secondary users. 412 final File mUserAppDataDir; 413 414 /** The location for ASEC container files on internal storage. */ 415 final String mAsecInternalPath; 416 417 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 418 // LOCK HELD. Can be called with mInstallLock held. 419 final Installer mInstaller; 420 421 /** Directory where installed third-party apps stored */ 422 final File mAppInstallDir; 423 424 /** 425 * Directory to which applications installed internally have their 426 * 32 bit native libraries copied. 427 */ 428 private File mAppLib32InstallDir; 429 430 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 431 // apps. 432 final File mDrmAppPrivateInstallDir; 433 434 // ---------------------------------------------------------------- 435 436 // Lock for state used when installing and doing other long running 437 // operations. Methods that must be called with this lock held have 438 // the suffix "LI". 439 final Object mInstallLock = new Object(); 440 441 // ---------------------------------------------------------------- 442 443 // Keys are String (package name), values are Package. This also serves 444 // as the lock for the global state. Methods that must be called with 445 // this lock held have the prefix "LP". 446 final ArrayMap<String, PackageParser.Package> mPackages = 447 new ArrayMap<String, PackageParser.Package>(); 448 449 // Tracks available target package names -> overlay package paths. 450 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 451 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 452 453 final Settings mSettings; 454 boolean mRestoredSettings; 455 456 // System configuration read by SystemConfig. 457 final int[] mGlobalGids; 458 final SparseArray<ArraySet<String>> mSystemPermissions; 459 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 460 461 // If mac_permissions.xml was found for seinfo labeling. 462 boolean mFoundPolicyFile; 463 464 // If a recursive restorecon of /data/data/<pkg> is needed. 465 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 466 467 public static final class SharedLibraryEntry { 468 public final String path; 469 public final String apk; 470 471 SharedLibraryEntry(String _path, String _apk) { 472 path = _path; 473 apk = _apk; 474 } 475 } 476 477 // Currently known shared libraries. 478 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 479 new ArrayMap<String, SharedLibraryEntry>(); 480 481 // All available activities, for your resolving pleasure. 482 final ActivityIntentResolver mActivities = 483 new ActivityIntentResolver(); 484 485 // All available receivers, for your resolving pleasure. 486 final ActivityIntentResolver mReceivers = 487 new ActivityIntentResolver(); 488 489 // All available services, for your resolving pleasure. 490 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 491 492 // All available providers, for your resolving pleasure. 493 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 494 495 // Mapping from provider base names (first directory in content URI codePath) 496 // to the provider information. 497 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 498 new ArrayMap<String, PackageParser.Provider>(); 499 500 // Mapping from instrumentation class names to info about them. 501 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 502 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 503 504 // Mapping from permission names to info about them. 505 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 506 new ArrayMap<String, PackageParser.PermissionGroup>(); 507 508 // Packages whose data we have transfered into another package, thus 509 // should no longer exist. 510 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 511 512 // Broadcast actions that are only available to the system. 513 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 514 515 /** List of packages waiting for verification. */ 516 final SparseArray<PackageVerificationState> mPendingVerification 517 = new SparseArray<PackageVerificationState>(); 518 519 /** Set of packages associated with each app op permission. */ 520 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 521 522 final PackageInstallerService mInstallerService; 523 524 private final PackageDexOptimizer mPackageDexOptimizer; 525 526 private AtomicInteger mNextMoveId = new AtomicInteger(); 527 private final MoveCallbacks mMoveCallbacks; 528 529 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 530 531 // Cache of users who need badging. 532 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 533 534 /** Token for keys in mPendingVerification. */ 535 private int mPendingVerificationToken = 0; 536 537 volatile boolean mSystemReady; 538 volatile boolean mSafeMode; 539 volatile boolean mHasSystemUidErrors; 540 541 ApplicationInfo mAndroidApplication; 542 final ActivityInfo mResolveActivity = new ActivityInfo(); 543 final ResolveInfo mResolveInfo = new ResolveInfo(); 544 ComponentName mResolveComponentName; 545 PackageParser.Package mPlatformPackage; 546 ComponentName mCustomResolverComponentName; 547 548 boolean mResolverReplaced = false; 549 550 private final ComponentName mIntentFilterVerifierComponent; 551 private int mIntentFilterVerificationToken = 0; 552 553 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 554 = new SparseArray<IntentFilterVerificationState>(); 555 556 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 557 new DefaultPermissionGrantPolicy(this); 558 559 private interface IntentFilterVerifier<T extends IntentFilter> { 560 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 561 T filter, String packageName); 562 void startVerifications(int userId); 563 void receiveVerificationResponse(int verificationId); 564 } 565 566 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 567 private Context mContext; 568 private ComponentName mIntentFilterVerifierComponent; 569 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 570 571 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 572 mContext = context; 573 mIntentFilterVerifierComponent = verifierComponent; 574 } 575 576 private String getDefaultScheme() { 577 return IntentFilter.SCHEME_HTTPS; 578 } 579 580 @Override 581 public void startVerifications(int userId) { 582 // Launch verifications requests 583 int count = mCurrentIntentFilterVerifications.size(); 584 for (int n=0; n<count; n++) { 585 int verificationId = mCurrentIntentFilterVerifications.get(n); 586 final IntentFilterVerificationState ivs = 587 mIntentFilterVerificationStates.get(verificationId); 588 589 String packageName = ivs.getPackageName(); 590 591 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 592 final int filterCount = filters.size(); 593 ArraySet<String> domainsSet = new ArraySet<>(); 594 for (int m=0; m<filterCount; m++) { 595 PackageParser.ActivityIntentInfo filter = filters.get(m); 596 domainsSet.addAll(filter.getHostsList()); 597 } 598 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 599 synchronized (mPackages) { 600 if (mSettings.createIntentFilterVerificationIfNeededLPw( 601 packageName, domainsList) != null) { 602 scheduleWriteSettingsLocked(); 603 } 604 } 605 sendVerificationRequest(userId, verificationId, ivs); 606 } 607 mCurrentIntentFilterVerifications.clear(); 608 } 609 610 private void sendVerificationRequest(int userId, int verificationId, 611 IntentFilterVerificationState ivs) { 612 613 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 614 verificationIntent.putExtra( 615 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 616 verificationId); 617 verificationIntent.putExtra( 618 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 619 getDefaultScheme()); 620 verificationIntent.putExtra( 621 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 622 ivs.getHostsString()); 623 verificationIntent.putExtra( 624 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 625 ivs.getPackageName()); 626 verificationIntent.setComponent(mIntentFilterVerifierComponent); 627 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 628 629 UserHandle user = new UserHandle(userId); 630 mContext.sendBroadcastAsUser(verificationIntent, user); 631 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 632 "Sending IntenFilter verification broadcast"); 633 } 634 635 public void receiveVerificationResponse(int verificationId) { 636 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 637 638 final boolean verified = ivs.isVerified(); 639 640 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 641 final int count = filters.size(); 642 for (int n=0; n<count; n++) { 643 PackageParser.ActivityIntentInfo filter = filters.get(n); 644 filter.setVerified(verified); 645 646 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 647 + " verified with result:" + verified + " and hosts:" 648 + ivs.getHostsString()); 649 } 650 651 mIntentFilterVerificationStates.remove(verificationId); 652 653 final String packageName = ivs.getPackageName(); 654 IntentFilterVerificationInfo ivi = null; 655 656 synchronized (mPackages) { 657 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 658 } 659 if (ivi == null) { 660 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 661 + verificationId + " packageName:" + packageName); 662 return; 663 } 664 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 665 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 666 667 synchronized (mPackages) { 668 if (verified) { 669 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 670 } else { 671 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 672 } 673 scheduleWriteSettingsLocked(); 674 675 final int userId = ivs.getUserId(); 676 if (userId != UserHandle.USER_ALL) { 677 final int userStatus = 678 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 679 680 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 681 boolean needUpdate = false; 682 683 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 684 // already been set by the User thru the Disambiguation dialog 685 switch (userStatus) { 686 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 687 if (verified) { 688 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 689 } else { 690 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 691 } 692 needUpdate = true; 693 break; 694 695 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 696 if (verified) { 697 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 698 needUpdate = true; 699 } 700 break; 701 702 default: 703 // Nothing to do 704 } 705 706 if (needUpdate) { 707 mSettings.updateIntentFilterVerificationStatusLPw( 708 packageName, updatedStatus, userId); 709 scheduleWritePackageRestrictionsLocked(userId); 710 } 711 } 712 } 713 } 714 715 @Override 716 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 717 ActivityIntentInfo filter, String packageName) { 718 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 719 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 720 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 721 "IntentFilter does not contain HTTP nor HTTPS data scheme"); 722 return false; 723 } 724 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 725 if (ivs == null) { 726 ivs = createDomainVerificationState(verifierId, userId, verificationId, 727 packageName); 728 } 729 if (!hasValidDomains(filter)) { 730 return false; 731 } 732 ivs.addFilter(filter); 733 return true; 734 } 735 736 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 737 int userId, int verificationId, String packageName) { 738 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 739 verifierId, userId, packageName); 740 ivs.setPendingState(); 741 synchronized (mPackages) { 742 mIntentFilterVerificationStates.append(verificationId, ivs); 743 mCurrentIntentFilterVerifications.add(verificationId); 744 } 745 return ivs; 746 } 747 } 748 749 private static boolean hasValidDomains(ActivityIntentInfo filter) { 750 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 751 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 752 if (!hasHTTPorHTTPS) { 753 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 754 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 755 return false; 756 } 757 return true; 758 } 759 760 private IntentFilterVerifier mIntentFilterVerifier; 761 762 // Set of pending broadcasts for aggregating enable/disable of components. 763 static class PendingPackageBroadcasts { 764 // for each user id, a map of <package name -> components within that package> 765 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 766 767 public PendingPackageBroadcasts() { 768 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 769 } 770 771 public ArrayList<String> get(int userId, String packageName) { 772 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 773 return packages.get(packageName); 774 } 775 776 public void put(int userId, String packageName, ArrayList<String> components) { 777 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 778 packages.put(packageName, components); 779 } 780 781 public void remove(int userId, String packageName) { 782 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 783 if (packages != null) { 784 packages.remove(packageName); 785 } 786 } 787 788 public void remove(int userId) { 789 mUidMap.remove(userId); 790 } 791 792 public int userIdCount() { 793 return mUidMap.size(); 794 } 795 796 public int userIdAt(int n) { 797 return mUidMap.keyAt(n); 798 } 799 800 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 801 return mUidMap.get(userId); 802 } 803 804 public int size() { 805 // total number of pending broadcast entries across all userIds 806 int num = 0; 807 for (int i = 0; i< mUidMap.size(); i++) { 808 num += mUidMap.valueAt(i).size(); 809 } 810 return num; 811 } 812 813 public void clear() { 814 mUidMap.clear(); 815 } 816 817 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 818 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 819 if (map == null) { 820 map = new ArrayMap<String, ArrayList<String>>(); 821 mUidMap.put(userId, map); 822 } 823 return map; 824 } 825 } 826 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 827 828 // Service Connection to remote media container service to copy 829 // package uri's from external media onto secure containers 830 // or internal storage. 831 private IMediaContainerService mContainerService = null; 832 833 static final int SEND_PENDING_BROADCAST = 1; 834 static final int MCS_BOUND = 3; 835 static final int END_COPY = 4; 836 static final int INIT_COPY = 5; 837 static final int MCS_UNBIND = 6; 838 static final int START_CLEANING_PACKAGE = 7; 839 static final int FIND_INSTALL_LOC = 8; 840 static final int POST_INSTALL = 9; 841 static final int MCS_RECONNECT = 10; 842 static final int MCS_GIVE_UP = 11; 843 static final int UPDATED_MEDIA_STATUS = 12; 844 static final int WRITE_SETTINGS = 13; 845 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 846 static final int PACKAGE_VERIFIED = 15; 847 static final int CHECK_PENDING_VERIFICATION = 16; 848 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 849 static final int INTENT_FILTER_VERIFIED = 18; 850 851 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 852 853 // Delay time in millisecs 854 static final int BROADCAST_DELAY = 10 * 1000; 855 856 static UserManagerService sUserManager; 857 858 // Stores a list of users whose package restrictions file needs to be updated 859 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 860 861 final private DefaultContainerConnection mDefContainerConn = 862 new DefaultContainerConnection(); 863 class DefaultContainerConnection implements ServiceConnection { 864 public void onServiceConnected(ComponentName name, IBinder service) { 865 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 866 IMediaContainerService imcs = 867 IMediaContainerService.Stub.asInterface(service); 868 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 869 } 870 871 public void onServiceDisconnected(ComponentName name) { 872 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 873 } 874 } 875 876 // Recordkeeping of restore-after-install operations that are currently in flight 877 // between the Package Manager and the Backup Manager 878 class PostInstallData { 879 public InstallArgs args; 880 public PackageInstalledInfo res; 881 882 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 883 args = _a; 884 res = _r; 885 } 886 } 887 888 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 889 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 890 891 // backup/restore of preferred activity state 892 private static final String TAG_PREFERRED_BACKUP = "pa"; 893 894 private final String mRequiredVerifierPackage; 895 896 private final PackageUsage mPackageUsage = new PackageUsage(); 897 898 private class PackageUsage { 899 private static final int WRITE_INTERVAL 900 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 901 902 private final Object mFileLock = new Object(); 903 private final AtomicLong mLastWritten = new AtomicLong(0); 904 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 905 906 private boolean mIsHistoricalPackageUsageAvailable = true; 907 908 boolean isHistoricalPackageUsageAvailable() { 909 return mIsHistoricalPackageUsageAvailable; 910 } 911 912 void write(boolean force) { 913 if (force) { 914 writeInternal(); 915 return; 916 } 917 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 918 && !DEBUG_DEXOPT) { 919 return; 920 } 921 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 922 new Thread("PackageUsage_DiskWriter") { 923 @Override 924 public void run() { 925 try { 926 writeInternal(); 927 } finally { 928 mBackgroundWriteRunning.set(false); 929 } 930 } 931 }.start(); 932 } 933 } 934 935 private void writeInternal() { 936 synchronized (mPackages) { 937 synchronized (mFileLock) { 938 AtomicFile file = getFile(); 939 FileOutputStream f = null; 940 try { 941 f = file.startWrite(); 942 BufferedOutputStream out = new BufferedOutputStream(f); 943 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 944 StringBuilder sb = new StringBuilder(); 945 for (PackageParser.Package pkg : mPackages.values()) { 946 if (pkg.mLastPackageUsageTimeInMills == 0) { 947 continue; 948 } 949 sb.setLength(0); 950 sb.append(pkg.packageName); 951 sb.append(' '); 952 sb.append((long)pkg.mLastPackageUsageTimeInMills); 953 sb.append('\n'); 954 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 955 } 956 out.flush(); 957 file.finishWrite(f); 958 } catch (IOException e) { 959 if (f != null) { 960 file.failWrite(f); 961 } 962 Log.e(TAG, "Failed to write package usage times", e); 963 } 964 } 965 } 966 mLastWritten.set(SystemClock.elapsedRealtime()); 967 } 968 969 void readLP() { 970 synchronized (mFileLock) { 971 AtomicFile file = getFile(); 972 BufferedInputStream in = null; 973 try { 974 in = new BufferedInputStream(file.openRead()); 975 StringBuffer sb = new StringBuffer(); 976 while (true) { 977 String packageName = readToken(in, sb, ' '); 978 if (packageName == null) { 979 break; 980 } 981 String timeInMillisString = readToken(in, sb, '\n'); 982 if (timeInMillisString == null) { 983 throw new IOException("Failed to find last usage time for package " 984 + packageName); 985 } 986 PackageParser.Package pkg = mPackages.get(packageName); 987 if (pkg == null) { 988 continue; 989 } 990 long timeInMillis; 991 try { 992 timeInMillis = Long.parseLong(timeInMillisString.toString()); 993 } catch (NumberFormatException e) { 994 throw new IOException("Failed to parse " + timeInMillisString 995 + " as a long.", e); 996 } 997 pkg.mLastPackageUsageTimeInMills = timeInMillis; 998 } 999 } catch (FileNotFoundException expected) { 1000 mIsHistoricalPackageUsageAvailable = false; 1001 } catch (IOException e) { 1002 Log.w(TAG, "Failed to read package usage times", e); 1003 } finally { 1004 IoUtils.closeQuietly(in); 1005 } 1006 } 1007 mLastWritten.set(SystemClock.elapsedRealtime()); 1008 } 1009 1010 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1011 throws IOException { 1012 sb.setLength(0); 1013 while (true) { 1014 int ch = in.read(); 1015 if (ch == -1) { 1016 if (sb.length() == 0) { 1017 return null; 1018 } 1019 throw new IOException("Unexpected EOF"); 1020 } 1021 if (ch == endOfToken) { 1022 return sb.toString(); 1023 } 1024 sb.append((char)ch); 1025 } 1026 } 1027 1028 private AtomicFile getFile() { 1029 File dataDir = Environment.getDataDirectory(); 1030 File systemDir = new File(dataDir, "system"); 1031 File fname = new File(systemDir, "package-usage.list"); 1032 return new AtomicFile(fname); 1033 } 1034 } 1035 1036 class PackageHandler extends Handler { 1037 private boolean mBound = false; 1038 final ArrayList<HandlerParams> mPendingInstalls = 1039 new ArrayList<HandlerParams>(); 1040 1041 private boolean connectToService() { 1042 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1043 " DefaultContainerService"); 1044 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1045 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1046 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1047 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1048 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1049 mBound = true; 1050 return true; 1051 } 1052 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1053 return false; 1054 } 1055 1056 private void disconnectService() { 1057 mContainerService = null; 1058 mBound = false; 1059 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1060 mContext.unbindService(mDefContainerConn); 1061 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1062 } 1063 1064 PackageHandler(Looper looper) { 1065 super(looper); 1066 } 1067 1068 public void handleMessage(Message msg) { 1069 try { 1070 doHandleMessage(msg); 1071 } finally { 1072 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1073 } 1074 } 1075 1076 void doHandleMessage(Message msg) { 1077 switch (msg.what) { 1078 case INIT_COPY: { 1079 HandlerParams params = (HandlerParams) msg.obj; 1080 int idx = mPendingInstalls.size(); 1081 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1082 // If a bind was already initiated we dont really 1083 // need to do anything. The pending install 1084 // will be processed later on. 1085 if (!mBound) { 1086 // If this is the only one pending we might 1087 // have to bind to the service again. 1088 if (!connectToService()) { 1089 Slog.e(TAG, "Failed to bind to media container service"); 1090 params.serviceError(); 1091 return; 1092 } else { 1093 // Once we bind to the service, the first 1094 // pending request will be processed. 1095 mPendingInstalls.add(idx, params); 1096 } 1097 } else { 1098 mPendingInstalls.add(idx, params); 1099 // Already bound to the service. Just make 1100 // sure we trigger off processing the first request. 1101 if (idx == 0) { 1102 mHandler.sendEmptyMessage(MCS_BOUND); 1103 } 1104 } 1105 break; 1106 } 1107 case MCS_BOUND: { 1108 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1109 if (msg.obj != null) { 1110 mContainerService = (IMediaContainerService) msg.obj; 1111 } 1112 if (mContainerService == null) { 1113 if (!mBound) { 1114 // Something seriously wrong since we are not bound and we are not 1115 // waiting for connection. Bail out. 1116 Slog.e(TAG, "Cannot bind to media container service"); 1117 for (HandlerParams params : mPendingInstalls) { 1118 // Indicate service bind error 1119 params.serviceError(); 1120 } 1121 mPendingInstalls.clear(); 1122 } else { 1123 Slog.w(TAG, "Waiting to connect to media container service"); 1124 } 1125 } else if (mPendingInstalls.size() > 0) { 1126 HandlerParams params = mPendingInstalls.get(0); 1127 if (params != null) { 1128 if (params.startCopy()) { 1129 // We are done... look for more work or to 1130 // go idle. 1131 if (DEBUG_SD_INSTALL) Log.i(TAG, 1132 "Checking for more work or unbind..."); 1133 // Delete pending install 1134 if (mPendingInstalls.size() > 0) { 1135 mPendingInstalls.remove(0); 1136 } 1137 if (mPendingInstalls.size() == 0) { 1138 if (mBound) { 1139 if (DEBUG_SD_INSTALL) Log.i(TAG, 1140 "Posting delayed MCS_UNBIND"); 1141 removeMessages(MCS_UNBIND); 1142 Message ubmsg = obtainMessage(MCS_UNBIND); 1143 // Unbind after a little delay, to avoid 1144 // continual thrashing. 1145 sendMessageDelayed(ubmsg, 10000); 1146 } 1147 } else { 1148 // There are more pending requests in queue. 1149 // Just post MCS_BOUND message to trigger processing 1150 // of next pending install. 1151 if (DEBUG_SD_INSTALL) Log.i(TAG, 1152 "Posting MCS_BOUND for next work"); 1153 mHandler.sendEmptyMessage(MCS_BOUND); 1154 } 1155 } 1156 } 1157 } else { 1158 // Should never happen ideally. 1159 Slog.w(TAG, "Empty queue"); 1160 } 1161 break; 1162 } 1163 case MCS_RECONNECT: { 1164 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1165 if (mPendingInstalls.size() > 0) { 1166 if (mBound) { 1167 disconnectService(); 1168 } 1169 if (!connectToService()) { 1170 Slog.e(TAG, "Failed to bind to media container service"); 1171 for (HandlerParams params : mPendingInstalls) { 1172 // Indicate service bind error 1173 params.serviceError(); 1174 } 1175 mPendingInstalls.clear(); 1176 } 1177 } 1178 break; 1179 } 1180 case MCS_UNBIND: { 1181 // If there is no actual work left, then time to unbind. 1182 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1183 1184 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1185 if (mBound) { 1186 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1187 1188 disconnectService(); 1189 } 1190 } else if (mPendingInstalls.size() > 0) { 1191 // There are more pending requests in queue. 1192 // Just post MCS_BOUND message to trigger processing 1193 // of next pending install. 1194 mHandler.sendEmptyMessage(MCS_BOUND); 1195 } 1196 1197 break; 1198 } 1199 case MCS_GIVE_UP: { 1200 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1201 mPendingInstalls.remove(0); 1202 break; 1203 } 1204 case SEND_PENDING_BROADCAST: { 1205 String packages[]; 1206 ArrayList<String> components[]; 1207 int size = 0; 1208 int uids[]; 1209 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1210 synchronized (mPackages) { 1211 if (mPendingBroadcasts == null) { 1212 return; 1213 } 1214 size = mPendingBroadcasts.size(); 1215 if (size <= 0) { 1216 // Nothing to be done. Just return 1217 return; 1218 } 1219 packages = new String[size]; 1220 components = new ArrayList[size]; 1221 uids = new int[size]; 1222 int i = 0; // filling out the above arrays 1223 1224 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1225 int packageUserId = mPendingBroadcasts.userIdAt(n); 1226 Iterator<Map.Entry<String, ArrayList<String>>> it 1227 = mPendingBroadcasts.packagesForUserId(packageUserId) 1228 .entrySet().iterator(); 1229 while (it.hasNext() && i < size) { 1230 Map.Entry<String, ArrayList<String>> ent = it.next(); 1231 packages[i] = ent.getKey(); 1232 components[i] = ent.getValue(); 1233 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1234 uids[i] = (ps != null) 1235 ? UserHandle.getUid(packageUserId, ps.appId) 1236 : -1; 1237 i++; 1238 } 1239 } 1240 size = i; 1241 mPendingBroadcasts.clear(); 1242 } 1243 // Send broadcasts 1244 for (int i = 0; i < size; i++) { 1245 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1246 } 1247 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1248 break; 1249 } 1250 case START_CLEANING_PACKAGE: { 1251 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1252 final String packageName = (String)msg.obj; 1253 final int userId = msg.arg1; 1254 final boolean andCode = msg.arg2 != 0; 1255 synchronized (mPackages) { 1256 if (userId == UserHandle.USER_ALL) { 1257 int[] users = sUserManager.getUserIds(); 1258 for (int user : users) { 1259 mSettings.addPackageToCleanLPw( 1260 new PackageCleanItem(user, packageName, andCode)); 1261 } 1262 } else { 1263 mSettings.addPackageToCleanLPw( 1264 new PackageCleanItem(userId, packageName, andCode)); 1265 } 1266 } 1267 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1268 startCleaningPackages(); 1269 } break; 1270 case POST_INSTALL: { 1271 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1272 PostInstallData data = mRunningInstalls.get(msg.arg1); 1273 mRunningInstalls.delete(msg.arg1); 1274 boolean deleteOld = false; 1275 1276 if (data != null) { 1277 InstallArgs args = data.args; 1278 PackageInstalledInfo res = data.res; 1279 1280 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1281 res.removedInfo.sendBroadcast(false, true, false); 1282 Bundle extras = new Bundle(1); 1283 extras.putInt(Intent.EXTRA_UID, res.uid); 1284 1285 // Now that we successfully installed the package, grant runtime 1286 // permissions if requested before broadcasting the install. 1287 if ((args.installFlags 1288 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1289 grantRequestedRuntimePermissions(res.pkg, 1290 args.user.getIdentifier()); 1291 } 1292 1293 // Determine the set of users who are adding this 1294 // package for the first time vs. those who are seeing 1295 // an update. 1296 int[] firstUsers; 1297 int[] updateUsers = new int[0]; 1298 if (res.origUsers == null || res.origUsers.length == 0) { 1299 firstUsers = res.newUsers; 1300 } else { 1301 firstUsers = new int[0]; 1302 for (int i=0; i<res.newUsers.length; i++) { 1303 int user = res.newUsers[i]; 1304 boolean isNew = true; 1305 for (int j=0; j<res.origUsers.length; j++) { 1306 if (res.origUsers[j] == user) { 1307 isNew = false; 1308 break; 1309 } 1310 } 1311 if (isNew) { 1312 int[] newFirst = new int[firstUsers.length+1]; 1313 System.arraycopy(firstUsers, 0, newFirst, 0, 1314 firstUsers.length); 1315 newFirst[firstUsers.length] = user; 1316 firstUsers = newFirst; 1317 } else { 1318 int[] newUpdate = new int[updateUsers.length+1]; 1319 System.arraycopy(updateUsers, 0, newUpdate, 0, 1320 updateUsers.length); 1321 newUpdate[updateUsers.length] = user; 1322 updateUsers = newUpdate; 1323 } 1324 } 1325 } 1326 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1327 res.pkg.applicationInfo.packageName, 1328 extras, null, null, firstUsers); 1329 final boolean update = res.removedInfo.removedPackage != null; 1330 if (update) { 1331 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1332 } 1333 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1334 res.pkg.applicationInfo.packageName, 1335 extras, null, null, updateUsers); 1336 if (update) { 1337 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1338 res.pkg.applicationInfo.packageName, 1339 extras, null, null, updateUsers); 1340 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1341 null, null, 1342 res.pkg.applicationInfo.packageName, null, updateUsers); 1343 1344 // treat asec-hosted packages like removable media on upgrade 1345 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1346 if (DEBUG_INSTALL) { 1347 Slog.i(TAG, "upgrading pkg " + res.pkg 1348 + " is ASEC-hosted -> AVAILABLE"); 1349 } 1350 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1351 ArrayList<String> pkgList = new ArrayList<String>(1); 1352 pkgList.add(res.pkg.applicationInfo.packageName); 1353 sendResourcesChangedBroadcast(true, true, 1354 pkgList,uidArray, null); 1355 } 1356 } 1357 if (res.removedInfo.args != null) { 1358 // Remove the replaced package's older resources safely now 1359 deleteOld = true; 1360 } 1361 1362 // Log current value of "unknown sources" setting 1363 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1364 getUnknownSourcesSettings()); 1365 } 1366 // Force a gc to clear up things 1367 Runtime.getRuntime().gc(); 1368 // We delete after a gc for applications on sdcard. 1369 if (deleteOld) { 1370 synchronized (mInstallLock) { 1371 res.removedInfo.args.doPostDeleteLI(true); 1372 } 1373 } 1374 if (args.observer != null) { 1375 try { 1376 Bundle extras = extrasForInstallResult(res); 1377 args.observer.onPackageInstalled(res.name, res.returnCode, 1378 res.returnMsg, extras); 1379 } catch (RemoteException e) { 1380 Slog.i(TAG, "Observer no longer exists."); 1381 } 1382 } 1383 } else { 1384 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1385 } 1386 } break; 1387 case UPDATED_MEDIA_STATUS: { 1388 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1389 boolean reportStatus = msg.arg1 == 1; 1390 boolean doGc = msg.arg2 == 1; 1391 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1392 if (doGc) { 1393 // Force a gc to clear up stale containers. 1394 Runtime.getRuntime().gc(); 1395 } 1396 if (msg.obj != null) { 1397 @SuppressWarnings("unchecked") 1398 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1399 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1400 // Unload containers 1401 unloadAllContainers(args); 1402 } 1403 if (reportStatus) { 1404 try { 1405 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1406 PackageHelper.getMountService().finishMediaUpdate(); 1407 } catch (RemoteException e) { 1408 Log.e(TAG, "MountService not running?"); 1409 } 1410 } 1411 } break; 1412 case WRITE_SETTINGS: { 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 synchronized (mPackages) { 1415 removeMessages(WRITE_SETTINGS); 1416 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1417 mSettings.writeLPr(); 1418 mDirtyUsers.clear(); 1419 } 1420 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1421 } break; 1422 case WRITE_PACKAGE_RESTRICTIONS: { 1423 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1424 synchronized (mPackages) { 1425 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1426 for (int userId : mDirtyUsers) { 1427 mSettings.writePackageRestrictionsLPr(userId); 1428 } 1429 mDirtyUsers.clear(); 1430 } 1431 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1432 } break; 1433 case CHECK_PENDING_VERIFICATION: { 1434 final int verificationId = msg.arg1; 1435 final PackageVerificationState state = mPendingVerification.get(verificationId); 1436 1437 if ((state != null) && !state.timeoutExtended()) { 1438 final InstallArgs args = state.getInstallArgs(); 1439 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1440 1441 Slog.i(TAG, "Verification timed out for " + originUri); 1442 mPendingVerification.remove(verificationId); 1443 1444 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1445 1446 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1447 Slog.i(TAG, "Continuing with installation of " + originUri); 1448 state.setVerifierResponse(Binder.getCallingUid(), 1449 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1450 broadcastPackageVerified(verificationId, originUri, 1451 PackageManager.VERIFICATION_ALLOW, 1452 state.getInstallArgs().getUser()); 1453 try { 1454 ret = args.copyApk(mContainerService, true); 1455 } catch (RemoteException e) { 1456 Slog.e(TAG, "Could not contact the ContainerService"); 1457 } 1458 } else { 1459 broadcastPackageVerified(verificationId, originUri, 1460 PackageManager.VERIFICATION_REJECT, 1461 state.getInstallArgs().getUser()); 1462 } 1463 1464 processPendingInstall(args, ret); 1465 mHandler.sendEmptyMessage(MCS_UNBIND); 1466 } 1467 break; 1468 } 1469 case PACKAGE_VERIFIED: { 1470 final int verificationId = msg.arg1; 1471 1472 final PackageVerificationState state = mPendingVerification.get(verificationId); 1473 if (state == null) { 1474 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1475 break; 1476 } 1477 1478 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1479 1480 state.setVerifierResponse(response.callerUid, response.code); 1481 1482 if (state.isVerificationComplete()) { 1483 mPendingVerification.remove(verificationId); 1484 1485 final InstallArgs args = state.getInstallArgs(); 1486 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1487 1488 int ret; 1489 if (state.isInstallAllowed()) { 1490 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1491 broadcastPackageVerified(verificationId, originUri, 1492 response.code, state.getInstallArgs().getUser()); 1493 try { 1494 ret = args.copyApk(mContainerService, true); 1495 } catch (RemoteException e) { 1496 Slog.e(TAG, "Could not contact the ContainerService"); 1497 } 1498 } else { 1499 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1500 } 1501 1502 processPendingInstall(args, ret); 1503 1504 mHandler.sendEmptyMessage(MCS_UNBIND); 1505 } 1506 1507 break; 1508 } 1509 case START_INTENT_FILTER_VERIFICATIONS: { 1510 int userId = msg.arg1; 1511 int verifierUid = msg.arg2; 1512 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1513 1514 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1515 break; 1516 } 1517 case INTENT_FILTER_VERIFIED: { 1518 final int verificationId = msg.arg1; 1519 1520 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1521 verificationId); 1522 if (state == null) { 1523 Slog.w(TAG, "Invalid IntentFilter verification token " 1524 + verificationId + " received"); 1525 break; 1526 } 1527 1528 final int userId = state.getUserId(); 1529 1530 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1531 "Processing IntentFilter verification with token:" 1532 + verificationId + " and userId:" + userId); 1533 1534 final IntentFilterVerificationResponse response = 1535 (IntentFilterVerificationResponse) msg.obj; 1536 1537 state.setVerifierResponse(response.callerUid, response.code); 1538 1539 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1540 "IntentFilter verification with token:" + verificationId 1541 + " and userId:" + userId 1542 + " is settings verifier response with response code:" 1543 + response.code); 1544 1545 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1546 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1547 + response.getFailedDomainsString()); 1548 } 1549 1550 if (state.isVerificationComplete()) { 1551 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1552 } else { 1553 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1554 "IntentFilter verification with token:" + verificationId 1555 + " was not said to be complete"); 1556 } 1557 1558 break; 1559 } 1560 } 1561 } 1562 } 1563 1564 private StorageEventListener mStorageListener = new StorageEventListener() { 1565 @Override 1566 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1567 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1568 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1569 // TODO: ensure that private directories exist for all active users 1570 // TODO: remove user data whose serial number doesn't match 1571 loadPrivatePackages(vol); 1572 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1573 unloadPrivatePackages(vol); 1574 } 1575 } 1576 1577 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1578 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1579 updateExternalMediaStatus(true, false); 1580 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1581 updateExternalMediaStatus(false, false); 1582 } 1583 } 1584 } 1585 1586 @Override 1587 public void onVolumeForgotten(String fsUuid) { 1588 // TODO: remove all packages hosted on this uuid 1589 } 1590 }; 1591 1592 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1593 if (userId >= UserHandle.USER_OWNER) { 1594 grantRequestedRuntimePermissionsForUser(pkg, userId); 1595 } else if (userId == UserHandle.USER_ALL) { 1596 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1597 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1598 } 1599 } 1600 1601 // We could have touched GID membership, so flush out packages.list 1602 synchronized (mPackages) { 1603 mSettings.writePackageListLPr(); 1604 } 1605 } 1606 1607 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1608 SettingBase sb = (SettingBase) pkg.mExtras; 1609 if (sb == null) { 1610 return; 1611 } 1612 1613 PermissionsState permissionsState = sb.getPermissionsState(); 1614 1615 for (String permission : pkg.requestedPermissions) { 1616 BasePermission bp = mSettings.mPermissions.get(permission); 1617 if (bp != null && bp.isRuntime()) { 1618 permissionsState.grantRuntimePermission(bp, userId); 1619 } 1620 } 1621 } 1622 1623 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1624 Bundle extras = null; 1625 switch (res.returnCode) { 1626 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1627 extras = new Bundle(); 1628 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1629 res.origPermission); 1630 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1631 res.origPackage); 1632 break; 1633 } 1634 case PackageManager.INSTALL_SUCCEEDED: { 1635 extras = new Bundle(); 1636 extras.putBoolean(Intent.EXTRA_REPLACING, 1637 res.removedInfo != null && res.removedInfo.removedPackage != null); 1638 break; 1639 } 1640 } 1641 return extras; 1642 } 1643 1644 void scheduleWriteSettingsLocked() { 1645 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1646 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1647 } 1648 } 1649 1650 void scheduleWritePackageRestrictionsLocked(int userId) { 1651 if (!sUserManager.exists(userId)) return; 1652 mDirtyUsers.add(userId); 1653 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1654 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1655 } 1656 } 1657 1658 public static PackageManagerService main(Context context, Installer installer, 1659 boolean factoryTest, boolean onlyCore) { 1660 PackageManagerService m = new PackageManagerService(context, installer, 1661 factoryTest, onlyCore); 1662 ServiceManager.addService("package", m); 1663 return m; 1664 } 1665 1666 static String[] splitString(String str, char sep) { 1667 int count = 1; 1668 int i = 0; 1669 while ((i=str.indexOf(sep, i)) >= 0) { 1670 count++; 1671 i++; 1672 } 1673 1674 String[] res = new String[count]; 1675 i=0; 1676 count = 0; 1677 int lastI=0; 1678 while ((i=str.indexOf(sep, i)) >= 0) { 1679 res[count] = str.substring(lastI, i); 1680 count++; 1681 i++; 1682 lastI = i; 1683 } 1684 res[count] = str.substring(lastI, str.length()); 1685 return res; 1686 } 1687 1688 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1689 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1690 Context.DISPLAY_SERVICE); 1691 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1692 } 1693 1694 public PackageManagerService(Context context, Installer installer, 1695 boolean factoryTest, boolean onlyCore) { 1696 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1697 SystemClock.uptimeMillis()); 1698 1699 if (mSdkVersion <= 0) { 1700 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1701 } 1702 1703 mContext = context; 1704 mFactoryTest = factoryTest; 1705 mOnlyCore = onlyCore; 1706 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1707 mMetrics = new DisplayMetrics(); 1708 mSettings = new Settings(mPackages); 1709 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1710 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1711 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1712 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1713 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1714 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1715 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1716 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1717 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1718 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1719 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1720 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1721 1722 // TODO: add a property to control this? 1723 long dexOptLRUThresholdInMinutes; 1724 if (mLazyDexOpt) { 1725 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1726 } else { 1727 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1728 } 1729 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1730 1731 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1732 if (separateProcesses != null && separateProcesses.length() > 0) { 1733 if ("*".equals(separateProcesses)) { 1734 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1735 mSeparateProcesses = null; 1736 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1737 } else { 1738 mDefParseFlags = 0; 1739 mSeparateProcesses = separateProcesses.split(","); 1740 Slog.w(TAG, "Running with debug.separate_processes: " 1741 + separateProcesses); 1742 } 1743 } else { 1744 mDefParseFlags = 0; 1745 mSeparateProcesses = null; 1746 } 1747 1748 mInstaller = installer; 1749 mPackageDexOptimizer = new PackageDexOptimizer(this); 1750 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1751 1752 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1753 FgThread.get().getLooper()); 1754 1755 getDefaultDisplayMetrics(context, mMetrics); 1756 1757 SystemConfig systemConfig = SystemConfig.getInstance(); 1758 mGlobalGids = systemConfig.getGlobalGids(); 1759 mSystemPermissions = systemConfig.getSystemPermissions(); 1760 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1761 1762 synchronized (mInstallLock) { 1763 // writer 1764 synchronized (mPackages) { 1765 mHandlerThread = new ServiceThread(TAG, 1766 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1767 mHandlerThread.start(); 1768 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1769 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1770 1771 File dataDir = Environment.getDataDirectory(); 1772 mAppDataDir = new File(dataDir, "data"); 1773 mAppInstallDir = new File(dataDir, "app"); 1774 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1775 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1776 mUserAppDataDir = new File(dataDir, "user"); 1777 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1778 1779 sUserManager = new UserManagerService(context, this, 1780 mInstallLock, mPackages); 1781 1782 // Propagate permission configuration in to package manager. 1783 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1784 = systemConfig.getPermissions(); 1785 for (int i=0; i<permConfig.size(); i++) { 1786 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1787 BasePermission bp = mSettings.mPermissions.get(perm.name); 1788 if (bp == null) { 1789 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1790 mSettings.mPermissions.put(perm.name, bp); 1791 } 1792 if (perm.gids != null) { 1793 bp.setGids(perm.gids, perm.perUser); 1794 } 1795 } 1796 1797 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1798 for (int i=0; i<libConfig.size(); i++) { 1799 mSharedLibraries.put(libConfig.keyAt(i), 1800 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1801 } 1802 1803 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1804 1805 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1806 mSdkVersion, mOnlyCore); 1807 1808 String customResolverActivity = Resources.getSystem().getString( 1809 R.string.config_customResolverActivity); 1810 if (TextUtils.isEmpty(customResolverActivity)) { 1811 customResolverActivity = null; 1812 } else { 1813 mCustomResolverComponentName = ComponentName.unflattenFromString( 1814 customResolverActivity); 1815 } 1816 1817 long startTime = SystemClock.uptimeMillis(); 1818 1819 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1820 startTime); 1821 1822 // Set flag to monitor and not change apk file paths when 1823 // scanning install directories. 1824 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1825 1826 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1827 1828 /** 1829 * Add everything in the in the boot class path to the 1830 * list of process files because dexopt will have been run 1831 * if necessary during zygote startup. 1832 */ 1833 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1834 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1835 1836 if (bootClassPath != null) { 1837 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1838 for (String element : bootClassPathElements) { 1839 alreadyDexOpted.add(element); 1840 } 1841 } else { 1842 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1843 } 1844 1845 if (systemServerClassPath != null) { 1846 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1847 for (String element : systemServerClassPathElements) { 1848 alreadyDexOpted.add(element); 1849 } 1850 } else { 1851 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1852 } 1853 1854 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1855 final String[] dexCodeInstructionSets = 1856 getDexCodeInstructionSets( 1857 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1858 1859 /** 1860 * Ensure all external libraries have had dexopt run on them. 1861 */ 1862 if (mSharedLibraries.size() > 0) { 1863 // NOTE: For now, we're compiling these system "shared libraries" 1864 // (and framework jars) into all available architectures. It's possible 1865 // to compile them only when we come across an app that uses them (there's 1866 // already logic for that in scanPackageLI) but that adds some complexity. 1867 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1868 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1869 final String lib = libEntry.path; 1870 if (lib == null) { 1871 continue; 1872 } 1873 1874 try { 1875 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1876 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1877 alreadyDexOpted.add(lib); 1878 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1879 } 1880 } catch (FileNotFoundException e) { 1881 Slog.w(TAG, "Library not found: " + lib); 1882 } catch (IOException e) { 1883 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1884 + e.getMessage()); 1885 } 1886 } 1887 } 1888 } 1889 1890 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1891 1892 // Gross hack for now: we know this file doesn't contain any 1893 // code, so don't dexopt it to avoid the resulting log spew. 1894 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1895 1896 // Gross hack for now: we know this file is only part of 1897 // the boot class path for art, so don't dexopt it to 1898 // avoid the resulting log spew. 1899 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1900 1901 /** 1902 * There are a number of commands implemented in Java, which 1903 * we currently need to do the dexopt on so that they can be 1904 * run from a non-root shell. 1905 */ 1906 String[] frameworkFiles = frameworkDir.list(); 1907 if (frameworkFiles != null) { 1908 // TODO: We could compile these only for the most preferred ABI. We should 1909 // first double check that the dex files for these commands are not referenced 1910 // by other system apps. 1911 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1912 for (int i=0; i<frameworkFiles.length; i++) { 1913 File libPath = new File(frameworkDir, frameworkFiles[i]); 1914 String path = libPath.getPath(); 1915 // Skip the file if we already did it. 1916 if (alreadyDexOpted.contains(path)) { 1917 continue; 1918 } 1919 // Skip the file if it is not a type we want to dexopt. 1920 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1921 continue; 1922 } 1923 try { 1924 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1925 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1926 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1927 } 1928 } catch (FileNotFoundException e) { 1929 Slog.w(TAG, "Jar not found: " + path); 1930 } catch (IOException e) { 1931 Slog.w(TAG, "Exception reading jar: " + path, e); 1932 } 1933 } 1934 } 1935 } 1936 1937 // Collect vendor overlay packages. 1938 // (Do this before scanning any apps.) 1939 // For security and version matching reason, only consider 1940 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1941 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1942 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1943 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1944 1945 // Find base frameworks (resource packages without code). 1946 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1947 | PackageParser.PARSE_IS_SYSTEM_DIR 1948 | PackageParser.PARSE_IS_PRIVILEGED, 1949 scanFlags | SCAN_NO_DEX, 0); 1950 1951 // Collected privileged system packages. 1952 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1953 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1954 | PackageParser.PARSE_IS_SYSTEM_DIR 1955 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1956 1957 // Collect ordinary system packages. 1958 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1959 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1960 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1961 1962 // Collect all vendor packages. 1963 File vendorAppDir = new File("/vendor/app"); 1964 try { 1965 vendorAppDir = vendorAppDir.getCanonicalFile(); 1966 } catch (IOException e) { 1967 // failed to look up canonical path, continue with original one 1968 } 1969 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1970 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1971 1972 // Collect all OEM packages. 1973 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1974 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1975 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1976 1977 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1978 mInstaller.moveFiles(); 1979 1980 // Prune any system packages that no longer exist. 1981 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1982 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1983 if (!mOnlyCore) { 1984 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1985 while (psit.hasNext()) { 1986 PackageSetting ps = psit.next(); 1987 1988 /* 1989 * If this is not a system app, it can't be a 1990 * disable system app. 1991 */ 1992 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1993 continue; 1994 } 1995 1996 /* 1997 * If the package is scanned, it's not erased. 1998 */ 1999 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2000 if (scannedPkg != null) { 2001 /* 2002 * If the system app is both scanned and in the 2003 * disabled packages list, then it must have been 2004 * added via OTA. Remove it from the currently 2005 * scanned package so the previously user-installed 2006 * application can be scanned. 2007 */ 2008 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2009 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2010 + ps.name + "; removing system app. Last known codePath=" 2011 + ps.codePathString + ", installStatus=" + ps.installStatus 2012 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2013 + scannedPkg.mVersionCode); 2014 removePackageLI(ps, true); 2015 expectingBetter.put(ps.name, ps.codePath); 2016 } 2017 2018 continue; 2019 } 2020 2021 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2022 psit.remove(); 2023 logCriticalInfo(Log.WARN, "System package " + ps.name 2024 + " no longer exists; wiping its data"); 2025 removeDataDirsLI(null, ps.name); 2026 } else { 2027 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2028 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2029 possiblyDeletedUpdatedSystemApps.add(ps.name); 2030 } 2031 } 2032 } 2033 } 2034 2035 //look for any incomplete package installations 2036 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2037 //clean up list 2038 for(int i = 0; i < deletePkgsList.size(); i++) { 2039 //clean up here 2040 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2041 } 2042 //delete tmp files 2043 deleteTempPackageFiles(); 2044 2045 // Remove any shared userIDs that have no associated packages 2046 mSettings.pruneSharedUsersLPw(); 2047 2048 if (!mOnlyCore) { 2049 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2050 SystemClock.uptimeMillis()); 2051 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2052 2053 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2054 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2055 2056 /** 2057 * Remove disable package settings for any updated system 2058 * apps that were removed via an OTA. If they're not a 2059 * previously-updated app, remove them completely. 2060 * Otherwise, just revoke their system-level permissions. 2061 */ 2062 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2063 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2064 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2065 2066 String msg; 2067 if (deletedPkg == null) { 2068 msg = "Updated system package " + deletedAppName 2069 + " no longer exists; wiping its data"; 2070 removeDataDirsLI(null, deletedAppName); 2071 } else { 2072 msg = "Updated system app + " + deletedAppName 2073 + " no longer present; removing system privileges for " 2074 + deletedAppName; 2075 2076 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2077 2078 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2079 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2080 } 2081 logCriticalInfo(Log.WARN, msg); 2082 } 2083 2084 /** 2085 * Make sure all system apps that we expected to appear on 2086 * the userdata partition actually showed up. If they never 2087 * appeared, crawl back and revive the system version. 2088 */ 2089 for (int i = 0; i < expectingBetter.size(); i++) { 2090 final String packageName = expectingBetter.keyAt(i); 2091 if (!mPackages.containsKey(packageName)) { 2092 final File scanFile = expectingBetter.valueAt(i); 2093 2094 logCriticalInfo(Log.WARN, "Expected better " + packageName 2095 + " but never showed up; reverting to system"); 2096 2097 final int reparseFlags; 2098 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2099 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2100 | PackageParser.PARSE_IS_SYSTEM_DIR 2101 | PackageParser.PARSE_IS_PRIVILEGED; 2102 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2103 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2104 | PackageParser.PARSE_IS_SYSTEM_DIR; 2105 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2106 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2107 | PackageParser.PARSE_IS_SYSTEM_DIR; 2108 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2109 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2110 | PackageParser.PARSE_IS_SYSTEM_DIR; 2111 } else { 2112 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2113 continue; 2114 } 2115 2116 mSettings.enableSystemPackageLPw(packageName); 2117 2118 try { 2119 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2120 } catch (PackageManagerException e) { 2121 Slog.e(TAG, "Failed to parse original system package: " 2122 + e.getMessage()); 2123 } 2124 } 2125 } 2126 } 2127 2128 // Now that we know all of the shared libraries, update all clients to have 2129 // the correct library paths. 2130 updateAllSharedLibrariesLPw(); 2131 2132 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2133 // NOTE: We ignore potential failures here during a system scan (like 2134 // the rest of the commands above) because there's precious little we 2135 // can do about it. A settings error is reported, though. 2136 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2137 false /* force dexopt */, false /* defer dexopt */); 2138 } 2139 2140 // Now that we know all the packages we are keeping, 2141 // read and update their last usage times. 2142 mPackageUsage.readLP(); 2143 2144 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2145 SystemClock.uptimeMillis()); 2146 Slog.i(TAG, "Time to scan packages: " 2147 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2148 + " seconds"); 2149 2150 // If the platform SDK has changed since the last time we booted, 2151 // we need to re-grant app permission to catch any new ones that 2152 // appear. This is really a hack, and means that apps can in some 2153 // cases get permissions that the user didn't initially explicitly 2154 // allow... it would be nice to have some better way to handle 2155 // this situation. 2156 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2157 != mSdkVersion; 2158 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2159 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2160 + "; regranting permissions for internal storage"); 2161 mSettings.mInternalSdkPlatform = mSdkVersion; 2162 2163 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2164 | (regrantPermissions 2165 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2166 : 0)); 2167 2168 // If this is the first boot, and it is a normal boot, then 2169 // we need to initialize the default preferred apps. 2170 if (!mRestoredSettings && !onlyCore) { 2171 mSettings.readDefaultPreferredAppsLPw(this, 0); 2172 } 2173 2174 // If this is first boot after an OTA, and a normal boot, then 2175 // we need to clear code cache directories. 2176 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2177 if (mIsUpgrade && !onlyCore) { 2178 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2179 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2180 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2181 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2182 } 2183 mSettings.mFingerprint = Build.FINGERPRINT; 2184 } 2185 2186 primeDomainVerificationsLPw(); 2187 checkDefaultBrowser(); 2188 2189 // All the changes are done during package scanning. 2190 mSettings.updateInternalDatabaseVersion(); 2191 2192 // can downgrade to reader 2193 mSettings.writeLPr(); 2194 2195 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2196 SystemClock.uptimeMillis()); 2197 2198 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2199 2200 mInstallerService = new PackageInstallerService(context, this); 2201 2202 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2203 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2204 mIntentFilterVerifierComponent); 2205 2206 } // synchronized (mPackages) 2207 } // synchronized (mInstallLock) 2208 2209 // Now after opening every single application zip, make sure they 2210 // are all flushed. Not really needed, but keeps things nice and 2211 // tidy. 2212 Runtime.getRuntime().gc(); 2213 2214 // Expose private service for system components to use. 2215 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2216 } 2217 2218 @Override 2219 public boolean isFirstBoot() { 2220 return !mRestoredSettings; 2221 } 2222 2223 @Override 2224 public boolean isOnlyCoreApps() { 2225 return mOnlyCore; 2226 } 2227 2228 @Override 2229 public boolean isUpgrade() { 2230 return mIsUpgrade; 2231 } 2232 2233 private String getRequiredVerifierLPr() { 2234 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2235 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2236 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2237 2238 String requiredVerifier = null; 2239 2240 final int N = receivers.size(); 2241 for (int i = 0; i < N; i++) { 2242 final ResolveInfo info = receivers.get(i); 2243 2244 if (info.activityInfo == null) { 2245 continue; 2246 } 2247 2248 final String packageName = info.activityInfo.packageName; 2249 2250 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2251 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2252 continue; 2253 } 2254 2255 if (requiredVerifier != null) { 2256 throw new RuntimeException("There can be only one required verifier"); 2257 } 2258 2259 requiredVerifier = packageName; 2260 } 2261 2262 return requiredVerifier; 2263 } 2264 2265 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2266 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2267 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2268 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2269 2270 ComponentName verifierComponentName = null; 2271 2272 int priority = -1000; 2273 final int N = receivers.size(); 2274 for (int i = 0; i < N; i++) { 2275 final ResolveInfo info = receivers.get(i); 2276 2277 if (info.activityInfo == null) { 2278 continue; 2279 } 2280 2281 final String packageName = info.activityInfo.packageName; 2282 2283 final PackageSetting ps = mSettings.mPackages.get(packageName); 2284 if (ps == null) { 2285 continue; 2286 } 2287 2288 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2289 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2290 continue; 2291 } 2292 2293 // Select the IntentFilterVerifier with the highest priority 2294 if (priority < info.priority) { 2295 priority = info.priority; 2296 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2297 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2298 + verifierComponentName + " with priority: " + info.priority); 2299 } 2300 } 2301 2302 return verifierComponentName; 2303 } 2304 2305 private void primeDomainVerificationsLPw() { 2306 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2307 boolean updated = false; 2308 ArraySet<String> allHostsSet = new ArraySet<>(); 2309 for (PackageParser.Package pkg : mPackages.values()) { 2310 final String packageName = pkg.packageName; 2311 if (!hasDomainURLs(pkg)) { 2312 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2313 "package with no domain URLs: " + packageName); 2314 continue; 2315 } 2316 if (!pkg.isSystemApp()) { 2317 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2318 "No priming domain verifications for a non system package : " + 2319 packageName); 2320 continue; 2321 } 2322 for (PackageParser.Activity a : pkg.activities) { 2323 for (ActivityIntentInfo filter : a.intents) { 2324 if (hasValidDomains(filter)) { 2325 allHostsSet.addAll(filter.getHostsList()); 2326 } 2327 } 2328 } 2329 if (allHostsSet.size() == 0) { 2330 allHostsSet.add("*"); 2331 } 2332 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2333 IntentFilterVerificationInfo ivi = 2334 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2335 if (ivi != null) { 2336 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2337 "Priming domain verifications for package: " + packageName + 2338 " with hosts:" + ivi.getDomainsString()); 2339 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2340 updated = true; 2341 } 2342 else { 2343 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2344 "No priming domain verifications for package: " + packageName); 2345 } 2346 allHostsSet.clear(); 2347 } 2348 if (updated) { 2349 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2350 "Will need to write primed domain verifications"); 2351 } 2352 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2353 } 2354 2355 private void checkDefaultBrowser() { 2356 final int myUserId = UserHandle.myUserId(); 2357 final String packageName = getDefaultBrowserPackageName(myUserId); 2358 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2359 if (info == null) { 2360 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2361 packageName); 2362 setDefaultBrowserPackageName(null, myUserId); 2363 } 2364 } 2365 2366 @Override 2367 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2368 throws RemoteException { 2369 try { 2370 return super.onTransact(code, data, reply, flags); 2371 } catch (RuntimeException e) { 2372 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2373 Slog.wtf(TAG, "Package Manager Crash", e); 2374 } 2375 throw e; 2376 } 2377 } 2378 2379 void cleanupInstallFailedPackage(PackageSetting ps) { 2380 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2381 2382 removeDataDirsLI(ps.volumeUuid, ps.name); 2383 if (ps.codePath != null) { 2384 if (ps.codePath.isDirectory()) { 2385 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2386 } else { 2387 ps.codePath.delete(); 2388 } 2389 } 2390 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2391 if (ps.resourcePath.isDirectory()) { 2392 FileUtils.deleteContents(ps.resourcePath); 2393 } 2394 ps.resourcePath.delete(); 2395 } 2396 mSettings.removePackageLPw(ps.name); 2397 } 2398 2399 static int[] appendInts(int[] cur, int[] add) { 2400 if (add == null) return cur; 2401 if (cur == null) return add; 2402 final int N = add.length; 2403 for (int i=0; i<N; i++) { 2404 cur = appendInt(cur, add[i]); 2405 } 2406 return cur; 2407 } 2408 2409 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2410 if (!sUserManager.exists(userId)) return null; 2411 final PackageSetting ps = (PackageSetting) p.mExtras; 2412 if (ps == null) { 2413 return null; 2414 } 2415 2416 final PermissionsState permissionsState = ps.getPermissionsState(); 2417 2418 final int[] gids = permissionsState.computeGids(userId); 2419 final Set<String> permissions = permissionsState.getPermissions(userId); 2420 final PackageUserState state = ps.readUserState(userId); 2421 2422 return PackageParser.generatePackageInfo(p, gids, flags, 2423 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2424 } 2425 2426 @Override 2427 public boolean isPackageFrozen(String packageName) { 2428 synchronized (mPackages) { 2429 final PackageSetting ps = mSettings.mPackages.get(packageName); 2430 if (ps != null) { 2431 return ps.frozen; 2432 } 2433 } 2434 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2435 return true; 2436 } 2437 2438 @Override 2439 public boolean isPackageAvailable(String packageName, int userId) { 2440 if (!sUserManager.exists(userId)) return false; 2441 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2442 synchronized (mPackages) { 2443 PackageParser.Package p = mPackages.get(packageName); 2444 if (p != null) { 2445 final PackageSetting ps = (PackageSetting) p.mExtras; 2446 if (ps != null) { 2447 final PackageUserState state = ps.readUserState(userId); 2448 if (state != null) { 2449 return PackageParser.isAvailable(state); 2450 } 2451 } 2452 } 2453 } 2454 return false; 2455 } 2456 2457 @Override 2458 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2459 if (!sUserManager.exists(userId)) return null; 2460 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2461 // reader 2462 synchronized (mPackages) { 2463 PackageParser.Package p = mPackages.get(packageName); 2464 if (DEBUG_PACKAGE_INFO) 2465 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2466 if (p != null) { 2467 return generatePackageInfo(p, flags, userId); 2468 } 2469 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2470 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2471 } 2472 } 2473 return null; 2474 } 2475 2476 @Override 2477 public String[] currentToCanonicalPackageNames(String[] names) { 2478 String[] out = new String[names.length]; 2479 // reader 2480 synchronized (mPackages) { 2481 for (int i=names.length-1; i>=0; i--) { 2482 PackageSetting ps = mSettings.mPackages.get(names[i]); 2483 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2484 } 2485 } 2486 return out; 2487 } 2488 2489 @Override 2490 public String[] canonicalToCurrentPackageNames(String[] names) { 2491 String[] out = new String[names.length]; 2492 // reader 2493 synchronized (mPackages) { 2494 for (int i=names.length-1; i>=0; i--) { 2495 String cur = mSettings.mRenamedPackages.get(names[i]); 2496 out[i] = cur != null ? cur : names[i]; 2497 } 2498 } 2499 return out; 2500 } 2501 2502 @Override 2503 public int getPackageUid(String packageName, int userId) { 2504 if (!sUserManager.exists(userId)) return -1; 2505 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2506 2507 // reader 2508 synchronized (mPackages) { 2509 PackageParser.Package p = mPackages.get(packageName); 2510 if(p != null) { 2511 return UserHandle.getUid(userId, p.applicationInfo.uid); 2512 } 2513 PackageSetting ps = mSettings.mPackages.get(packageName); 2514 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2515 return -1; 2516 } 2517 p = ps.pkg; 2518 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2519 } 2520 } 2521 2522 @Override 2523 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2524 if (!sUserManager.exists(userId)) { 2525 return null; 2526 } 2527 2528 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2529 "getPackageGids"); 2530 2531 // reader 2532 synchronized (mPackages) { 2533 PackageParser.Package p = mPackages.get(packageName); 2534 if (DEBUG_PACKAGE_INFO) { 2535 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2536 } 2537 if (p != null) { 2538 PackageSetting ps = (PackageSetting) p.mExtras; 2539 return ps.getPermissionsState().computeGids(userId); 2540 } 2541 } 2542 2543 return null; 2544 } 2545 2546 static PermissionInfo generatePermissionInfo( 2547 BasePermission bp, int flags) { 2548 if (bp.perm != null) { 2549 return PackageParser.generatePermissionInfo(bp.perm, flags); 2550 } 2551 PermissionInfo pi = new PermissionInfo(); 2552 pi.name = bp.name; 2553 pi.packageName = bp.sourcePackage; 2554 pi.nonLocalizedLabel = bp.name; 2555 pi.protectionLevel = bp.protectionLevel; 2556 return pi; 2557 } 2558 2559 @Override 2560 public PermissionInfo getPermissionInfo(String name, int flags) { 2561 // reader 2562 synchronized (mPackages) { 2563 final BasePermission p = mSettings.mPermissions.get(name); 2564 if (p != null) { 2565 return generatePermissionInfo(p, flags); 2566 } 2567 return null; 2568 } 2569 } 2570 2571 @Override 2572 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2573 // reader 2574 synchronized (mPackages) { 2575 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2576 for (BasePermission p : mSettings.mPermissions.values()) { 2577 if (group == null) { 2578 if (p.perm == null || p.perm.info.group == null) { 2579 out.add(generatePermissionInfo(p, flags)); 2580 } 2581 } else { 2582 if (p.perm != null && group.equals(p.perm.info.group)) { 2583 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2584 } 2585 } 2586 } 2587 2588 if (out.size() > 0) { 2589 return out; 2590 } 2591 return mPermissionGroups.containsKey(group) ? out : null; 2592 } 2593 } 2594 2595 @Override 2596 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2597 // reader 2598 synchronized (mPackages) { 2599 return PackageParser.generatePermissionGroupInfo( 2600 mPermissionGroups.get(name), flags); 2601 } 2602 } 2603 2604 @Override 2605 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2606 // reader 2607 synchronized (mPackages) { 2608 final int N = mPermissionGroups.size(); 2609 ArrayList<PermissionGroupInfo> out 2610 = new ArrayList<PermissionGroupInfo>(N); 2611 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2612 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2613 } 2614 return out; 2615 } 2616 } 2617 2618 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2619 int userId) { 2620 if (!sUserManager.exists(userId)) return null; 2621 PackageSetting ps = mSettings.mPackages.get(packageName); 2622 if (ps != null) { 2623 if (ps.pkg == null) { 2624 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2625 flags, userId); 2626 if (pInfo != null) { 2627 return pInfo.applicationInfo; 2628 } 2629 return null; 2630 } 2631 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2632 ps.readUserState(userId), userId); 2633 } 2634 return null; 2635 } 2636 2637 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2638 int userId) { 2639 if (!sUserManager.exists(userId)) return null; 2640 PackageSetting ps = mSettings.mPackages.get(packageName); 2641 if (ps != null) { 2642 PackageParser.Package pkg = ps.pkg; 2643 if (pkg == null) { 2644 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2645 return null; 2646 } 2647 // Only data remains, so we aren't worried about code paths 2648 pkg = new PackageParser.Package(packageName); 2649 pkg.applicationInfo.packageName = packageName; 2650 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2651 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2652 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2653 packageName, userId).getAbsolutePath(); 2654 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2655 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2656 } 2657 return generatePackageInfo(pkg, flags, userId); 2658 } 2659 return null; 2660 } 2661 2662 @Override 2663 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2664 if (!sUserManager.exists(userId)) return null; 2665 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2666 // writer 2667 synchronized (mPackages) { 2668 PackageParser.Package p = mPackages.get(packageName); 2669 if (DEBUG_PACKAGE_INFO) Log.v( 2670 TAG, "getApplicationInfo " + packageName 2671 + ": " + p); 2672 if (p != null) { 2673 PackageSetting ps = mSettings.mPackages.get(packageName); 2674 if (ps == null) return null; 2675 // Note: isEnabledLP() does not apply here - always return info 2676 return PackageParser.generateApplicationInfo( 2677 p, flags, ps.readUserState(userId), userId); 2678 } 2679 if ("android".equals(packageName)||"system".equals(packageName)) { 2680 return mAndroidApplication; 2681 } 2682 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2683 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2684 } 2685 } 2686 return null; 2687 } 2688 2689 @Override 2690 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2691 final IPackageDataObserver observer) { 2692 mContext.enforceCallingOrSelfPermission( 2693 android.Manifest.permission.CLEAR_APP_CACHE, null); 2694 // Queue up an async operation since clearing cache may take a little while. 2695 mHandler.post(new Runnable() { 2696 public void run() { 2697 mHandler.removeCallbacks(this); 2698 int retCode = -1; 2699 synchronized (mInstallLock) { 2700 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2701 if (retCode < 0) { 2702 Slog.w(TAG, "Couldn't clear application caches"); 2703 } 2704 } 2705 if (observer != null) { 2706 try { 2707 observer.onRemoveCompleted(null, (retCode >= 0)); 2708 } catch (RemoteException e) { 2709 Slog.w(TAG, "RemoveException when invoking call back"); 2710 } 2711 } 2712 } 2713 }); 2714 } 2715 2716 @Override 2717 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2718 final IntentSender pi) { 2719 mContext.enforceCallingOrSelfPermission( 2720 android.Manifest.permission.CLEAR_APP_CACHE, null); 2721 // Queue up an async operation since clearing cache may take a little while. 2722 mHandler.post(new Runnable() { 2723 public void run() { 2724 mHandler.removeCallbacks(this); 2725 int retCode = -1; 2726 synchronized (mInstallLock) { 2727 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2728 if (retCode < 0) { 2729 Slog.w(TAG, "Couldn't clear application caches"); 2730 } 2731 } 2732 if(pi != null) { 2733 try { 2734 // Callback via pending intent 2735 int code = (retCode >= 0) ? 1 : 0; 2736 pi.sendIntent(null, code, null, 2737 null, null); 2738 } catch (SendIntentException e1) { 2739 Slog.i(TAG, "Failed to send pending intent"); 2740 } 2741 } 2742 } 2743 }); 2744 } 2745 2746 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2747 synchronized (mInstallLock) { 2748 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2749 throw new IOException("Failed to free enough space"); 2750 } 2751 } 2752 } 2753 2754 @Override 2755 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2756 if (!sUserManager.exists(userId)) return null; 2757 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2758 synchronized (mPackages) { 2759 PackageParser.Activity a = mActivities.mActivities.get(component); 2760 2761 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2762 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2763 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2764 if (ps == null) return null; 2765 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2766 userId); 2767 } 2768 if (mResolveComponentName.equals(component)) { 2769 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2770 new PackageUserState(), userId); 2771 } 2772 } 2773 return null; 2774 } 2775 2776 @Override 2777 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2778 String resolvedType) { 2779 synchronized (mPackages) { 2780 PackageParser.Activity a = mActivities.mActivities.get(component); 2781 if (a == null) { 2782 return false; 2783 } 2784 for (int i=0; i<a.intents.size(); i++) { 2785 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2786 intent.getData(), intent.getCategories(), TAG) >= 0) { 2787 return true; 2788 } 2789 } 2790 return false; 2791 } 2792 } 2793 2794 @Override 2795 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2796 if (!sUserManager.exists(userId)) return null; 2797 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2798 synchronized (mPackages) { 2799 PackageParser.Activity a = mReceivers.mActivities.get(component); 2800 if (DEBUG_PACKAGE_INFO) Log.v( 2801 TAG, "getReceiverInfo " + component + ": " + a); 2802 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2803 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2804 if (ps == null) return null; 2805 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2806 userId); 2807 } 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2814 if (!sUserManager.exists(userId)) return null; 2815 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2816 synchronized (mPackages) { 2817 PackageParser.Service s = mServices.mServices.get(component); 2818 if (DEBUG_PACKAGE_INFO) Log.v( 2819 TAG, "getServiceInfo " + component + ": " + s); 2820 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2821 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2822 if (ps == null) return null; 2823 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2824 userId); 2825 } 2826 } 2827 return null; 2828 } 2829 2830 @Override 2831 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2832 if (!sUserManager.exists(userId)) return null; 2833 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2834 synchronized (mPackages) { 2835 PackageParser.Provider p = mProviders.mProviders.get(component); 2836 if (DEBUG_PACKAGE_INFO) Log.v( 2837 TAG, "getProviderInfo " + component + ": " + p); 2838 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2839 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2840 if (ps == null) return null; 2841 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2842 userId); 2843 } 2844 } 2845 return null; 2846 } 2847 2848 @Override 2849 public String[] getSystemSharedLibraryNames() { 2850 Set<String> libSet; 2851 synchronized (mPackages) { 2852 libSet = mSharedLibraries.keySet(); 2853 int size = libSet.size(); 2854 if (size > 0) { 2855 String[] libs = new String[size]; 2856 libSet.toArray(libs); 2857 return libs; 2858 } 2859 } 2860 return null; 2861 } 2862 2863 /** 2864 * @hide 2865 */ 2866 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2867 synchronized (mPackages) { 2868 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2869 if (lib != null && lib.apk != null) { 2870 return mPackages.get(lib.apk); 2871 } 2872 } 2873 return null; 2874 } 2875 2876 @Override 2877 public FeatureInfo[] getSystemAvailableFeatures() { 2878 Collection<FeatureInfo> featSet; 2879 synchronized (mPackages) { 2880 featSet = mAvailableFeatures.values(); 2881 int size = featSet.size(); 2882 if (size > 0) { 2883 FeatureInfo[] features = new FeatureInfo[size+1]; 2884 featSet.toArray(features); 2885 FeatureInfo fi = new FeatureInfo(); 2886 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2887 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2888 features[size] = fi; 2889 return features; 2890 } 2891 } 2892 return null; 2893 } 2894 2895 @Override 2896 public boolean hasSystemFeature(String name) { 2897 synchronized (mPackages) { 2898 return mAvailableFeatures.containsKey(name); 2899 } 2900 } 2901 2902 private void checkValidCaller(int uid, int userId) { 2903 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2904 return; 2905 2906 throw new SecurityException("Caller uid=" + uid 2907 + " is not privileged to communicate with user=" + userId); 2908 } 2909 2910 @Override 2911 public int checkPermission(String permName, String pkgName, int userId) { 2912 if (!sUserManager.exists(userId)) { 2913 return PackageManager.PERMISSION_DENIED; 2914 } 2915 2916 synchronized (mPackages) { 2917 final PackageParser.Package p = mPackages.get(pkgName); 2918 if (p != null && p.mExtras != null) { 2919 final PackageSetting ps = (PackageSetting) p.mExtras; 2920 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2921 return PackageManager.PERMISSION_GRANTED; 2922 } 2923 } 2924 } 2925 2926 return PackageManager.PERMISSION_DENIED; 2927 } 2928 2929 @Override 2930 public int checkUidPermission(String permName, int uid) { 2931 final int userId = UserHandle.getUserId(uid); 2932 2933 if (!sUserManager.exists(userId)) { 2934 return PackageManager.PERMISSION_DENIED; 2935 } 2936 2937 synchronized (mPackages) { 2938 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2939 if (obj != null) { 2940 final SettingBase ps = (SettingBase) obj; 2941 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2942 return PackageManager.PERMISSION_GRANTED; 2943 } 2944 } else { 2945 ArraySet<String> perms = mSystemPermissions.get(uid); 2946 if (perms != null && perms.contains(permName)) { 2947 return PackageManager.PERMISSION_GRANTED; 2948 } 2949 } 2950 } 2951 2952 return PackageManager.PERMISSION_DENIED; 2953 } 2954 2955 /** 2956 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2957 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2958 * @param checkShell TODO(yamasani): 2959 * @param message the message to log on security exception 2960 */ 2961 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2962 boolean checkShell, String message) { 2963 if (userId < 0) { 2964 throw new IllegalArgumentException("Invalid userId " + userId); 2965 } 2966 if (checkShell) { 2967 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2968 } 2969 if (userId == UserHandle.getUserId(callingUid)) return; 2970 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2971 if (requireFullPermission) { 2972 mContext.enforceCallingOrSelfPermission( 2973 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2974 } else { 2975 try { 2976 mContext.enforceCallingOrSelfPermission( 2977 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2978 } catch (SecurityException se) { 2979 mContext.enforceCallingOrSelfPermission( 2980 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2981 } 2982 } 2983 } 2984 } 2985 2986 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2987 if (callingUid == Process.SHELL_UID) { 2988 if (userHandle >= 0 2989 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2990 throw new SecurityException("Shell does not have permission to access user " 2991 + userHandle); 2992 } else if (userHandle < 0) { 2993 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2994 + Debug.getCallers(3)); 2995 } 2996 } 2997 } 2998 2999 private BasePermission findPermissionTreeLP(String permName) { 3000 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3001 if (permName.startsWith(bp.name) && 3002 permName.length() > bp.name.length() && 3003 permName.charAt(bp.name.length()) == '.') { 3004 return bp; 3005 } 3006 } 3007 return null; 3008 } 3009 3010 private BasePermission checkPermissionTreeLP(String permName) { 3011 if (permName != null) { 3012 BasePermission bp = findPermissionTreeLP(permName); 3013 if (bp != null) { 3014 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3015 return bp; 3016 } 3017 throw new SecurityException("Calling uid " 3018 + Binder.getCallingUid() 3019 + " is not allowed to add to permission tree " 3020 + bp.name + " owned by uid " + bp.uid); 3021 } 3022 } 3023 throw new SecurityException("No permission tree found for " + permName); 3024 } 3025 3026 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3027 if (s1 == null) { 3028 return s2 == null; 3029 } 3030 if (s2 == null) { 3031 return false; 3032 } 3033 if (s1.getClass() != s2.getClass()) { 3034 return false; 3035 } 3036 return s1.equals(s2); 3037 } 3038 3039 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3040 if (pi1.icon != pi2.icon) return false; 3041 if (pi1.logo != pi2.logo) return false; 3042 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3043 if (!compareStrings(pi1.name, pi2.name)) return false; 3044 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3045 // We'll take care of setting this one. 3046 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3047 // These are not currently stored in settings. 3048 //if (!compareStrings(pi1.group, pi2.group)) return false; 3049 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3050 //if (pi1.labelRes != pi2.labelRes) return false; 3051 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3052 return true; 3053 } 3054 3055 int permissionInfoFootprint(PermissionInfo info) { 3056 int size = info.name.length(); 3057 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3058 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3059 return size; 3060 } 3061 3062 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3063 int size = 0; 3064 for (BasePermission perm : mSettings.mPermissions.values()) { 3065 if (perm.uid == tree.uid) { 3066 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3067 } 3068 } 3069 return size; 3070 } 3071 3072 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3073 // We calculate the max size of permissions defined by this uid and throw 3074 // if that plus the size of 'info' would exceed our stated maximum. 3075 if (tree.uid != Process.SYSTEM_UID) { 3076 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3077 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3078 throw new SecurityException("Permission tree size cap exceeded"); 3079 } 3080 } 3081 } 3082 3083 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3084 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3085 throw new SecurityException("Label must be specified in permission"); 3086 } 3087 BasePermission tree = checkPermissionTreeLP(info.name); 3088 BasePermission bp = mSettings.mPermissions.get(info.name); 3089 boolean added = bp == null; 3090 boolean changed = true; 3091 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3092 if (added) { 3093 enforcePermissionCapLocked(info, tree); 3094 bp = new BasePermission(info.name, tree.sourcePackage, 3095 BasePermission.TYPE_DYNAMIC); 3096 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3097 throw new SecurityException( 3098 "Not allowed to modify non-dynamic permission " 3099 + info.name); 3100 } else { 3101 if (bp.protectionLevel == fixedLevel 3102 && bp.perm.owner.equals(tree.perm.owner) 3103 && bp.uid == tree.uid 3104 && comparePermissionInfos(bp.perm.info, info)) { 3105 changed = false; 3106 } 3107 } 3108 bp.protectionLevel = fixedLevel; 3109 info = new PermissionInfo(info); 3110 info.protectionLevel = fixedLevel; 3111 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3112 bp.perm.info.packageName = tree.perm.info.packageName; 3113 bp.uid = tree.uid; 3114 if (added) { 3115 mSettings.mPermissions.put(info.name, bp); 3116 } 3117 if (changed) { 3118 if (!async) { 3119 mSettings.writeLPr(); 3120 } else { 3121 scheduleWriteSettingsLocked(); 3122 } 3123 } 3124 return added; 3125 } 3126 3127 @Override 3128 public boolean addPermission(PermissionInfo info) { 3129 synchronized (mPackages) { 3130 return addPermissionLocked(info, false); 3131 } 3132 } 3133 3134 @Override 3135 public boolean addPermissionAsync(PermissionInfo info) { 3136 synchronized (mPackages) { 3137 return addPermissionLocked(info, true); 3138 } 3139 } 3140 3141 @Override 3142 public void removePermission(String name) { 3143 synchronized (mPackages) { 3144 checkPermissionTreeLP(name); 3145 BasePermission bp = mSettings.mPermissions.get(name); 3146 if (bp != null) { 3147 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3148 throw new SecurityException( 3149 "Not allowed to modify non-dynamic permission " 3150 + name); 3151 } 3152 mSettings.mPermissions.remove(name); 3153 mSettings.writeLPr(); 3154 } 3155 } 3156 } 3157 3158 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3159 BasePermission bp) { 3160 int index = pkg.requestedPermissions.indexOf(bp.name); 3161 if (index == -1) { 3162 throw new SecurityException("Package " + pkg.packageName 3163 + " has not requested permission " + bp.name); 3164 } 3165 if (!bp.isRuntime()) { 3166 throw new SecurityException("Permission " + bp.name 3167 + " is not a changeable permission type"); 3168 } 3169 } 3170 3171 @Override 3172 public void grantRuntimePermission(String packageName, String name, final int userId) { 3173 if (!sUserManager.exists(userId)) { 3174 Log.e(TAG, "No such user:" + userId); 3175 return; 3176 } 3177 3178 mContext.enforceCallingOrSelfPermission( 3179 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3180 "grantRuntimePermission"); 3181 3182 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3183 "grantRuntimePermission"); 3184 3185 final SettingBase sb; 3186 3187 synchronized (mPackages) { 3188 final PackageParser.Package pkg = mPackages.get(packageName); 3189 if (pkg == null) { 3190 throw new IllegalArgumentException("Unknown package: " + packageName); 3191 } 3192 3193 final BasePermission bp = mSettings.mPermissions.get(name); 3194 if (bp == null) { 3195 throw new IllegalArgumentException("Unknown permission: " + name); 3196 } 3197 3198 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3199 3200 sb = (SettingBase) pkg.mExtras; 3201 if (sb == null) { 3202 throw new IllegalArgumentException("Unknown package: " + packageName); 3203 } 3204 3205 final PermissionsState permissionsState = sb.getPermissionsState(); 3206 3207 final int flags = permissionsState.getPermissionFlags(name, userId); 3208 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3209 throw new SecurityException("Cannot grant system fixed permission: " 3210 + name + " for package: " + packageName); 3211 } 3212 3213 final int result = permissionsState.grantRuntimePermission(bp, userId); 3214 switch (result) { 3215 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3216 return; 3217 } 3218 3219 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3220 mHandler.post(new Runnable() { 3221 @Override 3222 public void run() { 3223 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3224 } 3225 }); 3226 } break; 3227 } 3228 3229 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3230 3231 // Not critical if that is lost - app has to request again. 3232 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3233 } 3234 } 3235 3236 @Override 3237 public void revokeRuntimePermission(String packageName, String name, int userId) { 3238 if (!sUserManager.exists(userId)) { 3239 Log.e(TAG, "No such user:" + userId); 3240 return; 3241 } 3242 3243 mContext.enforceCallingOrSelfPermission( 3244 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3245 "revokeRuntimePermission"); 3246 3247 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3248 "revokeRuntimePermission"); 3249 3250 final SettingBase sb; 3251 3252 synchronized (mPackages) { 3253 final PackageParser.Package pkg = mPackages.get(packageName); 3254 if (pkg == null) { 3255 throw new IllegalArgumentException("Unknown package: " + packageName); 3256 } 3257 3258 final BasePermission bp = mSettings.mPermissions.get(name); 3259 if (bp == null) { 3260 throw new IllegalArgumentException("Unknown permission: " + name); 3261 } 3262 3263 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3264 3265 sb = (SettingBase) pkg.mExtras; 3266 if (sb == null) { 3267 throw new IllegalArgumentException("Unknown package: " + packageName); 3268 } 3269 3270 final PermissionsState permissionsState = sb.getPermissionsState(); 3271 3272 final int flags = permissionsState.getPermissionFlags(name, userId); 3273 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3274 throw new SecurityException("Cannot revoke system fixed permission: " 3275 + name + " for package: " + packageName); 3276 } 3277 3278 if (permissionsState.revokeRuntimePermission(bp, userId) == 3279 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3280 return; 3281 } 3282 3283 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3284 3285 // Critical, after this call app should never have the permission. 3286 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3287 } 3288 3289 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3290 } 3291 3292 @Override 3293 public int getPermissionFlags(String name, String packageName, int userId) { 3294 if (!sUserManager.exists(userId)) { 3295 return 0; 3296 } 3297 3298 mContext.enforceCallingOrSelfPermission( 3299 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3300 "getPermissionFlags"); 3301 3302 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3303 "getPermissionFlags"); 3304 3305 synchronized (mPackages) { 3306 final PackageParser.Package pkg = mPackages.get(packageName); 3307 if (pkg == null) { 3308 throw new IllegalArgumentException("Unknown package: " + packageName); 3309 } 3310 3311 final BasePermission bp = mSettings.mPermissions.get(name); 3312 if (bp == null) { 3313 throw new IllegalArgumentException("Unknown permission: " + name); 3314 } 3315 3316 SettingBase sb = (SettingBase) pkg.mExtras; 3317 if (sb == null) { 3318 throw new IllegalArgumentException("Unknown package: " + packageName); 3319 } 3320 3321 PermissionsState permissionsState = sb.getPermissionsState(); 3322 return permissionsState.getPermissionFlags(name, userId); 3323 } 3324 } 3325 3326 @Override 3327 public void updatePermissionFlags(String name, String packageName, int flagMask, 3328 int flagValues, int userId) { 3329 if (!sUserManager.exists(userId)) { 3330 return; 3331 } 3332 3333 mContext.enforceCallingOrSelfPermission( 3334 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3335 "updatePermissionFlags"); 3336 3337 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3338 "updatePermissionFlags"); 3339 3340 // Only the system can change policy and system fixed flags. 3341 if (getCallingUid() != Process.SYSTEM_UID) { 3342 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3343 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3344 3345 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3346 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3347 } 3348 3349 synchronized (mPackages) { 3350 final PackageParser.Package pkg = mPackages.get(packageName); 3351 if (pkg == null) { 3352 throw new IllegalArgumentException("Unknown package: " + packageName); 3353 } 3354 3355 final BasePermission bp = mSettings.mPermissions.get(name); 3356 if (bp == null) { 3357 throw new IllegalArgumentException("Unknown permission: " + name); 3358 } 3359 3360 SettingBase sb = (SettingBase) pkg.mExtras; 3361 if (sb == null) { 3362 throw new IllegalArgumentException("Unknown package: " + packageName); 3363 } 3364 3365 PermissionsState permissionsState = sb.getPermissionsState(); 3366 3367 // Only the package manager can change flags for system component permissions. 3368 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3369 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3370 return; 3371 } 3372 3373 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3374 // Install and runtime permissions are stored in different places, 3375 // so figure out what permission changed and persist the change. 3376 if (permissionsState.getInstallPermissionState(name) != null) { 3377 scheduleWriteSettingsLocked(); 3378 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3379 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3380 } 3381 } 3382 } 3383 } 3384 3385 @Override 3386 public boolean shouldShowRequestPermissionRationale(String permissionName, 3387 String packageName, int userId) { 3388 if (UserHandle.getCallingUserId() != userId) { 3389 mContext.enforceCallingPermission( 3390 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3391 "canShowRequestPermissionRationale for user " + userId); 3392 } 3393 3394 final int uid = getPackageUid(packageName, userId); 3395 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3396 return false; 3397 } 3398 3399 if (checkPermission(permissionName, packageName, userId) 3400 == PackageManager.PERMISSION_GRANTED) { 3401 return false; 3402 } 3403 3404 final int flags; 3405 3406 final long identity = Binder.clearCallingIdentity(); 3407 try { 3408 flags = getPermissionFlags(permissionName, 3409 packageName, userId); 3410 } finally { 3411 Binder.restoreCallingIdentity(identity); 3412 } 3413 3414 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3415 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3416 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3417 3418 if ((flags & fixedFlags) != 0) { 3419 return false; 3420 } 3421 3422 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3423 } 3424 3425 void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) { 3426 BasePermission bp = mSettings.mPermissions.get(permission); 3427 if (bp == null) { 3428 throw new SecurityException("Missing " + permission + " permission"); 3429 } 3430 3431 SettingBase sb = (SettingBase) pkg.mExtras; 3432 PermissionsState permissionsState = sb.getPermissionsState(); 3433 3434 if (permissionsState.grantInstallPermission(bp) != 3435 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3436 scheduleWriteSettingsLocked(); 3437 } 3438 } 3439 3440 @Override 3441 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3442 mContext.enforceCallingOrSelfPermission( 3443 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3444 "addOnPermissionsChangeListener"); 3445 3446 synchronized (mPackages) { 3447 mOnPermissionChangeListeners.addListenerLocked(listener); 3448 } 3449 } 3450 3451 @Override 3452 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3453 synchronized (mPackages) { 3454 mOnPermissionChangeListeners.removeListenerLocked(listener); 3455 } 3456 } 3457 3458 @Override 3459 public boolean isProtectedBroadcast(String actionName) { 3460 synchronized (mPackages) { 3461 return mProtectedBroadcasts.contains(actionName); 3462 } 3463 } 3464 3465 @Override 3466 public int checkSignatures(String pkg1, String pkg2) { 3467 synchronized (mPackages) { 3468 final PackageParser.Package p1 = mPackages.get(pkg1); 3469 final PackageParser.Package p2 = mPackages.get(pkg2); 3470 if (p1 == null || p1.mExtras == null 3471 || p2 == null || p2.mExtras == null) { 3472 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3473 } 3474 return compareSignatures(p1.mSignatures, p2.mSignatures); 3475 } 3476 } 3477 3478 @Override 3479 public int checkUidSignatures(int uid1, int uid2) { 3480 // Map to base uids. 3481 uid1 = UserHandle.getAppId(uid1); 3482 uid2 = UserHandle.getAppId(uid2); 3483 // reader 3484 synchronized (mPackages) { 3485 Signature[] s1; 3486 Signature[] s2; 3487 Object obj = mSettings.getUserIdLPr(uid1); 3488 if (obj != null) { 3489 if (obj instanceof SharedUserSetting) { 3490 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3491 } else if (obj instanceof PackageSetting) { 3492 s1 = ((PackageSetting)obj).signatures.mSignatures; 3493 } else { 3494 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3495 } 3496 } else { 3497 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3498 } 3499 obj = mSettings.getUserIdLPr(uid2); 3500 if (obj != null) { 3501 if (obj instanceof SharedUserSetting) { 3502 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3503 } else if (obj instanceof PackageSetting) { 3504 s2 = ((PackageSetting)obj).signatures.mSignatures; 3505 } else { 3506 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3507 } 3508 } else { 3509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3510 } 3511 return compareSignatures(s1, s2); 3512 } 3513 } 3514 3515 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3516 final long identity = Binder.clearCallingIdentity(); 3517 try { 3518 if (sb instanceof SharedUserSetting) { 3519 SharedUserSetting sus = (SharedUserSetting) sb; 3520 final int packageCount = sus.packages.size(); 3521 for (int i = 0; i < packageCount; i++) { 3522 PackageSetting susPs = sus.packages.valueAt(i); 3523 if (userId == UserHandle.USER_ALL) { 3524 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3525 } else { 3526 final int uid = UserHandle.getUid(userId, susPs.appId); 3527 killUid(uid, reason); 3528 } 3529 } 3530 } else if (sb instanceof PackageSetting) { 3531 PackageSetting ps = (PackageSetting) sb; 3532 if (userId == UserHandle.USER_ALL) { 3533 killApplication(ps.pkg.packageName, ps.appId, reason); 3534 } else { 3535 final int uid = UserHandle.getUid(userId, ps.appId); 3536 killUid(uid, reason); 3537 } 3538 } 3539 } finally { 3540 Binder.restoreCallingIdentity(identity); 3541 } 3542 } 3543 3544 private static void killUid(int uid, String reason) { 3545 IActivityManager am = ActivityManagerNative.getDefault(); 3546 if (am != null) { 3547 try { 3548 am.killUid(uid, reason); 3549 } catch (RemoteException e) { 3550 /* ignore - same process */ 3551 } 3552 } 3553 } 3554 3555 /** 3556 * Compares two sets of signatures. Returns: 3557 * <br /> 3558 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3559 * <br /> 3560 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3561 * <br /> 3562 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3563 * <br /> 3564 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3565 * <br /> 3566 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3567 */ 3568 static int compareSignatures(Signature[] s1, Signature[] s2) { 3569 if (s1 == null) { 3570 return s2 == null 3571 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3572 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3573 } 3574 3575 if (s2 == null) { 3576 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3577 } 3578 3579 if (s1.length != s2.length) { 3580 return PackageManager.SIGNATURE_NO_MATCH; 3581 } 3582 3583 // Since both signature sets are of size 1, we can compare without HashSets. 3584 if (s1.length == 1) { 3585 return s1[0].equals(s2[0]) ? 3586 PackageManager.SIGNATURE_MATCH : 3587 PackageManager.SIGNATURE_NO_MATCH; 3588 } 3589 3590 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3591 for (Signature sig : s1) { 3592 set1.add(sig); 3593 } 3594 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3595 for (Signature sig : s2) { 3596 set2.add(sig); 3597 } 3598 // Make sure s2 contains all signatures in s1. 3599 if (set1.equals(set2)) { 3600 return PackageManager.SIGNATURE_MATCH; 3601 } 3602 return PackageManager.SIGNATURE_NO_MATCH; 3603 } 3604 3605 /** 3606 * If the database version for this type of package (internal storage or 3607 * external storage) is less than the version where package signatures 3608 * were updated, return true. 3609 */ 3610 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3611 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3612 DatabaseVersion.SIGNATURE_END_ENTITY)) 3613 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3614 DatabaseVersion.SIGNATURE_END_ENTITY)); 3615 } 3616 3617 /** 3618 * Used for backward compatibility to make sure any packages with 3619 * certificate chains get upgraded to the new style. {@code existingSigs} 3620 * will be in the old format (since they were stored on disk from before the 3621 * system upgrade) and {@code scannedSigs} will be in the newer format. 3622 */ 3623 private int compareSignaturesCompat(PackageSignatures existingSigs, 3624 PackageParser.Package scannedPkg) { 3625 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3626 return PackageManager.SIGNATURE_NO_MATCH; 3627 } 3628 3629 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3630 for (Signature sig : existingSigs.mSignatures) { 3631 existingSet.add(sig); 3632 } 3633 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3634 for (Signature sig : scannedPkg.mSignatures) { 3635 try { 3636 Signature[] chainSignatures = sig.getChainSignatures(); 3637 for (Signature chainSig : chainSignatures) { 3638 scannedCompatSet.add(chainSig); 3639 } 3640 } catch (CertificateEncodingException e) { 3641 scannedCompatSet.add(sig); 3642 } 3643 } 3644 /* 3645 * Make sure the expanded scanned set contains all signatures in the 3646 * existing one. 3647 */ 3648 if (scannedCompatSet.equals(existingSet)) { 3649 // Migrate the old signatures to the new scheme. 3650 existingSigs.assignSignatures(scannedPkg.mSignatures); 3651 // The new KeySets will be re-added later in the scanning process. 3652 synchronized (mPackages) { 3653 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3654 } 3655 return PackageManager.SIGNATURE_MATCH; 3656 } 3657 return PackageManager.SIGNATURE_NO_MATCH; 3658 } 3659 3660 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3661 if (isExternal(scannedPkg)) { 3662 return mSettings.isExternalDatabaseVersionOlderThan( 3663 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3664 } else { 3665 return mSettings.isInternalDatabaseVersionOlderThan( 3666 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3667 } 3668 } 3669 3670 private int compareSignaturesRecover(PackageSignatures existingSigs, 3671 PackageParser.Package scannedPkg) { 3672 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3673 return PackageManager.SIGNATURE_NO_MATCH; 3674 } 3675 3676 String msg = null; 3677 try { 3678 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3679 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3680 + scannedPkg.packageName); 3681 return PackageManager.SIGNATURE_MATCH; 3682 } 3683 } catch (CertificateException e) { 3684 msg = e.getMessage(); 3685 } 3686 3687 logCriticalInfo(Log.INFO, 3688 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3689 return PackageManager.SIGNATURE_NO_MATCH; 3690 } 3691 3692 @Override 3693 public String[] getPackagesForUid(int uid) { 3694 uid = UserHandle.getAppId(uid); 3695 // reader 3696 synchronized (mPackages) { 3697 Object obj = mSettings.getUserIdLPr(uid); 3698 if (obj instanceof SharedUserSetting) { 3699 final SharedUserSetting sus = (SharedUserSetting) obj; 3700 final int N = sus.packages.size(); 3701 final String[] res = new String[N]; 3702 final Iterator<PackageSetting> it = sus.packages.iterator(); 3703 int i = 0; 3704 while (it.hasNext()) { 3705 res[i++] = it.next().name; 3706 } 3707 return res; 3708 } else if (obj instanceof PackageSetting) { 3709 final PackageSetting ps = (PackageSetting) obj; 3710 return new String[] { ps.name }; 3711 } 3712 } 3713 return null; 3714 } 3715 3716 @Override 3717 public String getNameForUid(int uid) { 3718 // reader 3719 synchronized (mPackages) { 3720 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3721 if (obj instanceof SharedUserSetting) { 3722 final SharedUserSetting sus = (SharedUserSetting) obj; 3723 return sus.name + ":" + sus.userId; 3724 } else if (obj instanceof PackageSetting) { 3725 final PackageSetting ps = (PackageSetting) obj; 3726 return ps.name; 3727 } 3728 } 3729 return null; 3730 } 3731 3732 @Override 3733 public int getUidForSharedUser(String sharedUserName) { 3734 if(sharedUserName == null) { 3735 return -1; 3736 } 3737 // reader 3738 synchronized (mPackages) { 3739 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3740 if (suid == null) { 3741 return -1; 3742 } 3743 return suid.userId; 3744 } 3745 } 3746 3747 @Override 3748 public int getFlagsForUid(int uid) { 3749 synchronized (mPackages) { 3750 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3751 if (obj instanceof SharedUserSetting) { 3752 final SharedUserSetting sus = (SharedUserSetting) obj; 3753 return sus.pkgFlags; 3754 } else if (obj instanceof PackageSetting) { 3755 final PackageSetting ps = (PackageSetting) obj; 3756 return ps.pkgFlags; 3757 } 3758 } 3759 return 0; 3760 } 3761 3762 @Override 3763 public int getPrivateFlagsForUid(int uid) { 3764 synchronized (mPackages) { 3765 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3766 if (obj instanceof SharedUserSetting) { 3767 final SharedUserSetting sus = (SharedUserSetting) obj; 3768 return sus.pkgPrivateFlags; 3769 } else if (obj instanceof PackageSetting) { 3770 final PackageSetting ps = (PackageSetting) obj; 3771 return ps.pkgPrivateFlags; 3772 } 3773 } 3774 return 0; 3775 } 3776 3777 @Override 3778 public boolean isUidPrivileged(int uid) { 3779 uid = UserHandle.getAppId(uid); 3780 // reader 3781 synchronized (mPackages) { 3782 Object obj = mSettings.getUserIdLPr(uid); 3783 if (obj instanceof SharedUserSetting) { 3784 final SharedUserSetting sus = (SharedUserSetting) obj; 3785 final Iterator<PackageSetting> it = sus.packages.iterator(); 3786 while (it.hasNext()) { 3787 if (it.next().isPrivileged()) { 3788 return true; 3789 } 3790 } 3791 } else if (obj instanceof PackageSetting) { 3792 final PackageSetting ps = (PackageSetting) obj; 3793 return ps.isPrivileged(); 3794 } 3795 } 3796 return false; 3797 } 3798 3799 @Override 3800 public String[] getAppOpPermissionPackages(String permissionName) { 3801 synchronized (mPackages) { 3802 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3803 if (pkgs == null) { 3804 return null; 3805 } 3806 return pkgs.toArray(new String[pkgs.size()]); 3807 } 3808 } 3809 3810 @Override 3811 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3812 int flags, int userId) { 3813 if (!sUserManager.exists(userId)) return null; 3814 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3815 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3816 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3817 } 3818 3819 @Override 3820 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3821 IntentFilter filter, int match, ComponentName activity) { 3822 final int userId = UserHandle.getCallingUserId(); 3823 if (DEBUG_PREFERRED) { 3824 Log.v(TAG, "setLastChosenActivity intent=" + intent 3825 + " resolvedType=" + resolvedType 3826 + " flags=" + flags 3827 + " filter=" + filter 3828 + " match=" + match 3829 + " activity=" + activity); 3830 filter.dump(new PrintStreamPrinter(System.out), " "); 3831 } 3832 intent.setComponent(null); 3833 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3834 // Find any earlier preferred or last chosen entries and nuke them 3835 findPreferredActivity(intent, resolvedType, 3836 flags, query, 0, false, true, false, userId); 3837 // Add the new activity as the last chosen for this filter 3838 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3839 "Setting last chosen"); 3840 } 3841 3842 @Override 3843 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3844 final int userId = UserHandle.getCallingUserId(); 3845 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3846 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3847 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3848 false, false, false, userId); 3849 } 3850 3851 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3852 int flags, List<ResolveInfo> query, int userId) { 3853 if (query != null) { 3854 final int N = query.size(); 3855 if (N == 1) { 3856 return query.get(0); 3857 } else if (N > 1) { 3858 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3859 // If there is more than one activity with the same priority, 3860 // then let the user decide between them. 3861 ResolveInfo r0 = query.get(0); 3862 ResolveInfo r1 = query.get(1); 3863 if (DEBUG_INTENT_MATCHING || debug) { 3864 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3865 + r1.activityInfo.name + "=" + r1.priority); 3866 } 3867 // If the first activity has a higher priority, or a different 3868 // default, then it is always desireable to pick it. 3869 if (r0.priority != r1.priority 3870 || r0.preferredOrder != r1.preferredOrder 3871 || r0.isDefault != r1.isDefault) { 3872 return query.get(0); 3873 } 3874 // If we have saved a preference for a preferred activity for 3875 // this Intent, use that. 3876 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3877 flags, query, r0.priority, true, false, debug, userId); 3878 if (ri != null) { 3879 return ri; 3880 } 3881 if (userId != 0) { 3882 ri = new ResolveInfo(mResolveInfo); 3883 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3884 ri.activityInfo.applicationInfo = new ApplicationInfo( 3885 ri.activityInfo.applicationInfo); 3886 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3887 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3888 return ri; 3889 } 3890 return mResolveInfo; 3891 } 3892 } 3893 return null; 3894 } 3895 3896 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3897 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3898 final int N = query.size(); 3899 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3900 .get(userId); 3901 // Get the list of persistent preferred activities that handle the intent 3902 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3903 List<PersistentPreferredActivity> pprefs = ppir != null 3904 ? ppir.queryIntent(intent, resolvedType, 3905 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3906 : null; 3907 if (pprefs != null && pprefs.size() > 0) { 3908 final int M = pprefs.size(); 3909 for (int i=0; i<M; i++) { 3910 final PersistentPreferredActivity ppa = pprefs.get(i); 3911 if (DEBUG_PREFERRED || debug) { 3912 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3913 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3914 + "\n component=" + ppa.mComponent); 3915 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3916 } 3917 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3918 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3919 if (DEBUG_PREFERRED || debug) { 3920 Slog.v(TAG, "Found persistent preferred activity:"); 3921 if (ai != null) { 3922 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3923 } else { 3924 Slog.v(TAG, " null"); 3925 } 3926 } 3927 if (ai == null) { 3928 // This previously registered persistent preferred activity 3929 // component is no longer known. Ignore it and do NOT remove it. 3930 continue; 3931 } 3932 for (int j=0; j<N; j++) { 3933 final ResolveInfo ri = query.get(j); 3934 if (!ri.activityInfo.applicationInfo.packageName 3935 .equals(ai.applicationInfo.packageName)) { 3936 continue; 3937 } 3938 if (!ri.activityInfo.name.equals(ai.name)) { 3939 continue; 3940 } 3941 // Found a persistent preference that can handle the intent. 3942 if (DEBUG_PREFERRED || debug) { 3943 Slog.v(TAG, "Returning persistent preferred activity: " + 3944 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3945 } 3946 return ri; 3947 } 3948 } 3949 } 3950 return null; 3951 } 3952 3953 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3954 List<ResolveInfo> query, int priority, boolean always, 3955 boolean removeMatches, boolean debug, int userId) { 3956 if (!sUserManager.exists(userId)) return null; 3957 // writer 3958 synchronized (mPackages) { 3959 if (intent.getSelector() != null) { 3960 intent = intent.getSelector(); 3961 } 3962 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3963 3964 // Try to find a matching persistent preferred activity. 3965 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3966 debug, userId); 3967 3968 // If a persistent preferred activity matched, use it. 3969 if (pri != null) { 3970 return pri; 3971 } 3972 3973 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3974 // Get the list of preferred activities that handle the intent 3975 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3976 List<PreferredActivity> prefs = pir != null 3977 ? pir.queryIntent(intent, resolvedType, 3978 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3979 : null; 3980 if (prefs != null && prefs.size() > 0) { 3981 boolean changed = false; 3982 try { 3983 // First figure out how good the original match set is. 3984 // We will only allow preferred activities that came 3985 // from the same match quality. 3986 int match = 0; 3987 3988 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3989 3990 final int N = query.size(); 3991 for (int j=0; j<N; j++) { 3992 final ResolveInfo ri = query.get(j); 3993 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3994 + ": 0x" + Integer.toHexString(match)); 3995 if (ri.match > match) { 3996 match = ri.match; 3997 } 3998 } 3999 4000 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 4001 + Integer.toHexString(match)); 4002 4003 match &= IntentFilter.MATCH_CATEGORY_MASK; 4004 final int M = prefs.size(); 4005 for (int i=0; i<M; i++) { 4006 final PreferredActivity pa = prefs.get(i); 4007 if (DEBUG_PREFERRED || debug) { 4008 Slog.v(TAG, "Checking PreferredActivity ds=" 4009 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 4010 + "\n component=" + pa.mPref.mComponent); 4011 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4012 } 4013 if (pa.mPref.mMatch != match) { 4014 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 4015 + Integer.toHexString(pa.mPref.mMatch)); 4016 continue; 4017 } 4018 // If it's not an "always" type preferred activity and that's what we're 4019 // looking for, skip it. 4020 if (always && !pa.mPref.mAlways) { 4021 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 4022 continue; 4023 } 4024 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 4025 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 4026 if (DEBUG_PREFERRED || debug) { 4027 Slog.v(TAG, "Found preferred activity:"); 4028 if (ai != null) { 4029 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4030 } else { 4031 Slog.v(TAG, " null"); 4032 } 4033 } 4034 if (ai == null) { 4035 // This previously registered preferred activity 4036 // component is no longer known. Most likely an update 4037 // to the app was installed and in the new version this 4038 // component no longer exists. Clean it up by removing 4039 // it from the preferred activities list, and skip it. 4040 Slog.w(TAG, "Removing dangling preferred activity: " 4041 + pa.mPref.mComponent); 4042 pir.removeFilter(pa); 4043 changed = true; 4044 continue; 4045 } 4046 for (int j=0; j<N; j++) { 4047 final ResolveInfo ri = query.get(j); 4048 if (!ri.activityInfo.applicationInfo.packageName 4049 .equals(ai.applicationInfo.packageName)) { 4050 continue; 4051 } 4052 if (!ri.activityInfo.name.equals(ai.name)) { 4053 continue; 4054 } 4055 4056 if (removeMatches) { 4057 pir.removeFilter(pa); 4058 changed = true; 4059 if (DEBUG_PREFERRED) { 4060 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4061 } 4062 break; 4063 } 4064 4065 // Okay we found a previously set preferred or last chosen app. 4066 // If the result set is different from when this 4067 // was created, we need to clear it and re-ask the 4068 // user their preference, if we're looking for an "always" type entry. 4069 if (always && !pa.mPref.sameSet(query)) { 4070 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4071 + intent + " type " + resolvedType); 4072 if (DEBUG_PREFERRED) { 4073 Slog.v(TAG, "Removing preferred activity since set changed " 4074 + pa.mPref.mComponent); 4075 } 4076 pir.removeFilter(pa); 4077 // Re-add the filter as a "last chosen" entry (!always) 4078 PreferredActivity lastChosen = new PreferredActivity( 4079 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4080 pir.addFilter(lastChosen); 4081 changed = true; 4082 return null; 4083 } 4084 4085 // Yay! Either the set matched or we're looking for the last chosen 4086 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4087 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4088 return ri; 4089 } 4090 } 4091 } finally { 4092 if (changed) { 4093 if (DEBUG_PREFERRED) { 4094 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4095 } 4096 scheduleWritePackageRestrictionsLocked(userId); 4097 } 4098 } 4099 } 4100 } 4101 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4102 return null; 4103 } 4104 4105 /* 4106 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4107 */ 4108 @Override 4109 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4110 int targetUserId) { 4111 mContext.enforceCallingOrSelfPermission( 4112 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4113 List<CrossProfileIntentFilter> matches = 4114 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4115 if (matches != null) { 4116 int size = matches.size(); 4117 for (int i = 0; i < size; i++) { 4118 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4119 } 4120 } 4121 if (hasWebURI(intent)) { 4122 // cross-profile app linking works only towards the parent. 4123 final UserInfo parent = getProfileParent(sourceUserId); 4124 synchronized(mPackages) { 4125 return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId, 4126 parent.id) != null; 4127 } 4128 } 4129 return false; 4130 } 4131 4132 private UserInfo getProfileParent(int userId) { 4133 final long identity = Binder.clearCallingIdentity(); 4134 try { 4135 return sUserManager.getProfileParent(userId); 4136 } finally { 4137 Binder.restoreCallingIdentity(identity); 4138 } 4139 } 4140 4141 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4142 String resolvedType, int userId) { 4143 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4144 if (resolver != null) { 4145 return resolver.queryIntent(intent, resolvedType, false, userId); 4146 } 4147 return null; 4148 } 4149 4150 @Override 4151 public List<ResolveInfo> queryIntentActivities(Intent intent, 4152 String resolvedType, int flags, int userId) { 4153 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4154 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4155 ComponentName comp = intent.getComponent(); 4156 if (comp == null) { 4157 if (intent.getSelector() != null) { 4158 intent = intent.getSelector(); 4159 comp = intent.getComponent(); 4160 } 4161 } 4162 4163 if (comp != null) { 4164 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4165 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4166 if (ai != null) { 4167 final ResolveInfo ri = new ResolveInfo(); 4168 ri.activityInfo = ai; 4169 list.add(ri); 4170 } 4171 return list; 4172 } 4173 4174 // reader 4175 synchronized (mPackages) { 4176 final String pkgName = intent.getPackage(); 4177 if (pkgName == null) { 4178 List<CrossProfileIntentFilter> matchingFilters = 4179 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4180 // Check for results that need to skip the current profile. 4181 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4182 resolvedType, flags, userId); 4183 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4184 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4185 result.add(xpResolveInfo); 4186 return filterIfNotPrimaryUser(result, userId); 4187 } 4188 4189 // Check for results in the current profile. 4190 List<ResolveInfo> result = mActivities.queryIntent( 4191 intent, resolvedType, flags, userId); 4192 4193 // Check for cross profile results. 4194 xpResolveInfo = queryCrossProfileIntents( 4195 matchingFilters, intent, resolvedType, flags, userId); 4196 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 4197 result.add(xpResolveInfo); 4198 Collections.sort(result, mResolvePrioritySorter); 4199 } 4200 result = filterIfNotPrimaryUser(result, userId); 4201 if (hasWebURI(intent)) { 4202 CrossProfileDomainInfo xpDomainInfo = null; 4203 final UserInfo parent = getProfileParent(userId); 4204 if (parent != null) { 4205 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 4206 flags, userId, parent.id); 4207 } 4208 if (xpDomainInfo != null) { 4209 if (xpResolveInfo != null) { 4210 // If we didn't remove it, the cross-profile ResolveInfo would be twice 4211 // in the result. 4212 result.remove(xpResolveInfo); 4213 } 4214 if (result.size() == 0) { 4215 result.add(xpDomainInfo.resolveInfo); 4216 return result; 4217 } 4218 } else if (result.size() <= 1) { 4219 return result; 4220 } 4221 result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result, 4222 xpDomainInfo); 4223 Collections.sort(result, mResolvePrioritySorter); 4224 } 4225 return result; 4226 } 4227 final PackageParser.Package pkg = mPackages.get(pkgName); 4228 if (pkg != null) { 4229 return filterIfNotPrimaryUser( 4230 mActivities.queryIntentForPackage( 4231 intent, resolvedType, flags, pkg.activities, userId), 4232 userId); 4233 } 4234 return new ArrayList<ResolveInfo>(); 4235 } 4236 } 4237 4238 private static class CrossProfileDomainInfo { 4239 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 4240 ResolveInfo resolveInfo; 4241 /* Best domain verification status of the activities found in the other profile */ 4242 int bestDomainVerificationStatus; 4243 } 4244 4245 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 4246 String resolvedType, int flags, int sourceUserId, int parentUserId) { 4247 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_APP_LINKING, 4248 sourceUserId)) { 4249 return null; 4250 } 4251 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4252 resolvedType, flags, parentUserId); 4253 4254 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 4255 return null; 4256 } 4257 CrossProfileDomainInfo result = null; 4258 int size = resultTargetUser.size(); 4259 for (int i = 0; i < size; i++) { 4260 ResolveInfo riTargetUser = resultTargetUser.get(i); 4261 // Intent filter verification is only for filters that specify a host. So don't return 4262 // those that handle all web uris. 4263 if (riTargetUser.handleAllWebDataURI) { 4264 continue; 4265 } 4266 String packageName = riTargetUser.activityInfo.packageName; 4267 PackageSetting ps = mSettings.mPackages.get(packageName); 4268 if (ps == null) { 4269 continue; 4270 } 4271 int status = getDomainVerificationStatusLPr(ps, parentUserId); 4272 if (result == null) { 4273 result = new CrossProfileDomainInfo(); 4274 result.resolveInfo = 4275 createForwardingResolveInfo(null, sourceUserId, parentUserId); 4276 result.bestDomainVerificationStatus = status; 4277 } else { 4278 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 4279 result.bestDomainVerificationStatus); 4280 } 4281 } 4282 return result; 4283 } 4284 4285 /** 4286 * Verification statuses are ordered from the worse to the best, except for 4287 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 4288 */ 4289 private int bestDomainVerificationStatus(int status1, int status2) { 4290 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4291 return status2; 4292 } 4293 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4294 return status1; 4295 } 4296 return (int) MathUtils.max(status1, status2); 4297 } 4298 4299 private boolean isUserEnabled(int userId) { 4300 long callingId = Binder.clearCallingIdentity(); 4301 try { 4302 UserInfo userInfo = sUserManager.getUserInfo(userId); 4303 return userInfo != null && userInfo.isEnabled(); 4304 } finally { 4305 Binder.restoreCallingIdentity(callingId); 4306 } 4307 } 4308 4309 /** 4310 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4311 * 4312 * @return filtered list 4313 */ 4314 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4315 if (userId == UserHandle.USER_OWNER) { 4316 return resolveInfos; 4317 } 4318 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4319 ResolveInfo info = resolveInfos.get(i); 4320 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4321 resolveInfos.remove(i); 4322 } 4323 } 4324 return resolveInfos; 4325 } 4326 4327 private static boolean hasWebURI(Intent intent) { 4328 if (intent.getData() == null) { 4329 return false; 4330 } 4331 final String scheme = intent.getScheme(); 4332 if (TextUtils.isEmpty(scheme)) { 4333 return false; 4334 } 4335 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4336 } 4337 4338 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr( 4339 int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) { 4340 if (DEBUG_PREFERRED) { 4341 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4342 candidates.size()); 4343 } 4344 4345 final int userId = UserHandle.getCallingUserId(); 4346 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4347 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4348 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4349 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4350 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4351 4352 synchronized (mPackages) { 4353 final int count = candidates.size(); 4354 // First, try to use the domain prefered App. Partition the candidates into four lists: 4355 // one for the final results, one for the "do not use ever", one for "undefined status" 4356 // and finally one for "Browser App type". 4357 for (int n=0; n<count; n++) { 4358 ResolveInfo info = candidates.get(n); 4359 String packageName = info.activityInfo.packageName; 4360 PackageSetting ps = mSettings.mPackages.get(packageName); 4361 if (ps != null) { 4362 // Add to the special match all list (Browser use case) 4363 if (info.handleAllWebDataURI) { 4364 matchAllList.add(info); 4365 continue; 4366 } 4367 // Try to get the status from User settings first 4368 int status = getDomainVerificationStatusLPr(ps, userId); 4369 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4370 alwaysList.add(info); 4371 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4372 neverList.add(info); 4373 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4374 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4375 undefinedList.add(info); 4376 } 4377 } 4378 } 4379 // First try to add the "always" resolution for the current user if there is any 4380 if (alwaysList.size() > 0) { 4381 result.addAll(alwaysList); 4382 // if there is an "always" for the parent user, add it. 4383 } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus 4384 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4385 result.add(xpDomainInfo.resolveInfo); 4386 } else { 4387 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4388 result.addAll(undefinedList); 4389 if (xpDomainInfo != null && ( 4390 xpDomainInfo.bestDomainVerificationStatus 4391 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 4392 || xpDomainInfo.bestDomainVerificationStatus 4393 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) { 4394 result.add(xpDomainInfo.resolveInfo); 4395 } 4396 // Also add Browsers (all of them or only the default one) 4397 if ((flags & MATCH_ALL) != 0) { 4398 result.addAll(matchAllList); 4399 } else { 4400 // Try to add the Default Browser if we can 4401 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4402 UserHandle.myUserId()); 4403 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4404 boolean defaultBrowserFound = false; 4405 final int browserCount = matchAllList.size(); 4406 for (int n=0; n<browserCount; n++) { 4407 ResolveInfo browser = matchAllList.get(n); 4408 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4409 result.add(browser); 4410 defaultBrowserFound = true; 4411 break; 4412 } 4413 } 4414 if (!defaultBrowserFound) { 4415 result.addAll(matchAllList); 4416 } 4417 } else { 4418 result.addAll(matchAllList); 4419 } 4420 } 4421 4422 // If there is nothing selected, add all candidates and remove the ones that the User 4423 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4424 if (result.size() == 0) { 4425 result.addAll(candidates); 4426 result.removeAll(neverList); 4427 } 4428 } 4429 } 4430 if (DEBUG_PREFERRED) { 4431 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4432 result.size()); 4433 } 4434 return result; 4435 } 4436 4437 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4438 int status = ps.getDomainVerificationStatusForUser(userId); 4439 // if none available, get the master status 4440 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4441 if (ps.getIntentFilterVerificationInfo() != null) { 4442 status = ps.getIntentFilterVerificationInfo().getStatus(); 4443 } 4444 } 4445 return status; 4446 } 4447 4448 private ResolveInfo querySkipCurrentProfileIntents( 4449 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4450 int flags, int sourceUserId) { 4451 if (matchingFilters != null) { 4452 int size = matchingFilters.size(); 4453 for (int i = 0; i < size; i ++) { 4454 CrossProfileIntentFilter filter = matchingFilters.get(i); 4455 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4456 // Checking if there are activities in the target user that can handle the 4457 // intent. 4458 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4459 flags, sourceUserId); 4460 if (resolveInfo != null) { 4461 return resolveInfo; 4462 } 4463 } 4464 } 4465 } 4466 return null; 4467 } 4468 4469 // Return matching ResolveInfo if any for skip current profile intent filters. 4470 private ResolveInfo queryCrossProfileIntents( 4471 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4472 int flags, int sourceUserId) { 4473 if (matchingFilters != null) { 4474 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4475 // match the same intent. For performance reasons, it is better not to 4476 // run queryIntent twice for the same userId 4477 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4478 int size = matchingFilters.size(); 4479 for (int i = 0; i < size; i++) { 4480 CrossProfileIntentFilter filter = matchingFilters.get(i); 4481 int targetUserId = filter.getTargetUserId(); 4482 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4483 && !alreadyTriedUserIds.get(targetUserId)) { 4484 // Checking if there are activities in the target user that can handle the 4485 // intent. 4486 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4487 flags, sourceUserId); 4488 if (resolveInfo != null) return resolveInfo; 4489 alreadyTriedUserIds.put(targetUserId, true); 4490 } 4491 } 4492 } 4493 return null; 4494 } 4495 4496 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4497 String resolvedType, int flags, int sourceUserId) { 4498 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4499 resolvedType, flags, filter.getTargetUserId()); 4500 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4501 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4502 } 4503 return null; 4504 } 4505 4506 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4507 int sourceUserId, int targetUserId) { 4508 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4509 String className; 4510 if (targetUserId == UserHandle.USER_OWNER) { 4511 className = FORWARD_INTENT_TO_USER_OWNER; 4512 } else { 4513 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4514 } 4515 ComponentName forwardingActivityComponentName = new ComponentName( 4516 mAndroidApplication.packageName, className); 4517 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4518 sourceUserId); 4519 if (targetUserId == UserHandle.USER_OWNER) { 4520 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4521 forwardingResolveInfo.noResourceId = true; 4522 } 4523 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4524 forwardingResolveInfo.priority = 0; 4525 forwardingResolveInfo.preferredOrder = 0; 4526 forwardingResolveInfo.match = 0; 4527 forwardingResolveInfo.isDefault = true; 4528 forwardingResolveInfo.filter = filter; 4529 forwardingResolveInfo.targetUserId = targetUserId; 4530 return forwardingResolveInfo; 4531 } 4532 4533 @Override 4534 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4535 Intent[] specifics, String[] specificTypes, Intent intent, 4536 String resolvedType, int flags, int userId) { 4537 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4538 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4539 false, "query intent activity options"); 4540 final String resultsAction = intent.getAction(); 4541 4542 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4543 | PackageManager.GET_RESOLVED_FILTER, userId); 4544 4545 if (DEBUG_INTENT_MATCHING) { 4546 Log.v(TAG, "Query " + intent + ": " + results); 4547 } 4548 4549 int specificsPos = 0; 4550 int N; 4551 4552 // todo: note that the algorithm used here is O(N^2). This 4553 // isn't a problem in our current environment, but if we start running 4554 // into situations where we have more than 5 or 10 matches then this 4555 // should probably be changed to something smarter... 4556 4557 // First we go through and resolve each of the specific items 4558 // that were supplied, taking care of removing any corresponding 4559 // duplicate items in the generic resolve list. 4560 if (specifics != null) { 4561 for (int i=0; i<specifics.length; i++) { 4562 final Intent sintent = specifics[i]; 4563 if (sintent == null) { 4564 continue; 4565 } 4566 4567 if (DEBUG_INTENT_MATCHING) { 4568 Log.v(TAG, "Specific #" + i + ": " + sintent); 4569 } 4570 4571 String action = sintent.getAction(); 4572 if (resultsAction != null && resultsAction.equals(action)) { 4573 // If this action was explicitly requested, then don't 4574 // remove things that have it. 4575 action = null; 4576 } 4577 4578 ResolveInfo ri = null; 4579 ActivityInfo ai = null; 4580 4581 ComponentName comp = sintent.getComponent(); 4582 if (comp == null) { 4583 ri = resolveIntent( 4584 sintent, 4585 specificTypes != null ? specificTypes[i] : null, 4586 flags, userId); 4587 if (ri == null) { 4588 continue; 4589 } 4590 if (ri == mResolveInfo) { 4591 // ACK! Must do something better with this. 4592 } 4593 ai = ri.activityInfo; 4594 comp = new ComponentName(ai.applicationInfo.packageName, 4595 ai.name); 4596 } else { 4597 ai = getActivityInfo(comp, flags, userId); 4598 if (ai == null) { 4599 continue; 4600 } 4601 } 4602 4603 // Look for any generic query activities that are duplicates 4604 // of this specific one, and remove them from the results. 4605 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4606 N = results.size(); 4607 int j; 4608 for (j=specificsPos; j<N; j++) { 4609 ResolveInfo sri = results.get(j); 4610 if ((sri.activityInfo.name.equals(comp.getClassName()) 4611 && sri.activityInfo.applicationInfo.packageName.equals( 4612 comp.getPackageName())) 4613 || (action != null && sri.filter.matchAction(action))) { 4614 results.remove(j); 4615 if (DEBUG_INTENT_MATCHING) Log.v( 4616 TAG, "Removing duplicate item from " + j 4617 + " due to specific " + specificsPos); 4618 if (ri == null) { 4619 ri = sri; 4620 } 4621 j--; 4622 N--; 4623 } 4624 } 4625 4626 // Add this specific item to its proper place. 4627 if (ri == null) { 4628 ri = new ResolveInfo(); 4629 ri.activityInfo = ai; 4630 } 4631 results.add(specificsPos, ri); 4632 ri.specificIndex = i; 4633 specificsPos++; 4634 } 4635 } 4636 4637 // Now we go through the remaining generic results and remove any 4638 // duplicate actions that are found here. 4639 N = results.size(); 4640 for (int i=specificsPos; i<N-1; i++) { 4641 final ResolveInfo rii = results.get(i); 4642 if (rii.filter == null) { 4643 continue; 4644 } 4645 4646 // Iterate over all of the actions of this result's intent 4647 // filter... typically this should be just one. 4648 final Iterator<String> it = rii.filter.actionsIterator(); 4649 if (it == null) { 4650 continue; 4651 } 4652 while (it.hasNext()) { 4653 final String action = it.next(); 4654 if (resultsAction != null && resultsAction.equals(action)) { 4655 // If this action was explicitly requested, then don't 4656 // remove things that have it. 4657 continue; 4658 } 4659 for (int j=i+1; j<N; j++) { 4660 final ResolveInfo rij = results.get(j); 4661 if (rij.filter != null && rij.filter.hasAction(action)) { 4662 results.remove(j); 4663 if (DEBUG_INTENT_MATCHING) Log.v( 4664 TAG, "Removing duplicate item from " + j 4665 + " due to action " + action + " at " + i); 4666 j--; 4667 N--; 4668 } 4669 } 4670 } 4671 4672 // If the caller didn't request filter information, drop it now 4673 // so we don't have to marshall/unmarshall it. 4674 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4675 rii.filter = null; 4676 } 4677 } 4678 4679 // Filter out the caller activity if so requested. 4680 if (caller != null) { 4681 N = results.size(); 4682 for (int i=0; i<N; i++) { 4683 ActivityInfo ainfo = results.get(i).activityInfo; 4684 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4685 && caller.getClassName().equals(ainfo.name)) { 4686 results.remove(i); 4687 break; 4688 } 4689 } 4690 } 4691 4692 // If the caller didn't request filter information, 4693 // drop them now so we don't have to 4694 // marshall/unmarshall it. 4695 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4696 N = results.size(); 4697 for (int i=0; i<N; i++) { 4698 results.get(i).filter = null; 4699 } 4700 } 4701 4702 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4703 return results; 4704 } 4705 4706 @Override 4707 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4708 int userId) { 4709 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4710 ComponentName comp = intent.getComponent(); 4711 if (comp == null) { 4712 if (intent.getSelector() != null) { 4713 intent = intent.getSelector(); 4714 comp = intent.getComponent(); 4715 } 4716 } 4717 if (comp != null) { 4718 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4719 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4720 if (ai != null) { 4721 ResolveInfo ri = new ResolveInfo(); 4722 ri.activityInfo = ai; 4723 list.add(ri); 4724 } 4725 return list; 4726 } 4727 4728 // reader 4729 synchronized (mPackages) { 4730 String pkgName = intent.getPackage(); 4731 if (pkgName == null) { 4732 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4733 } 4734 final PackageParser.Package pkg = mPackages.get(pkgName); 4735 if (pkg != null) { 4736 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4737 userId); 4738 } 4739 return null; 4740 } 4741 } 4742 4743 @Override 4744 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4745 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4746 if (!sUserManager.exists(userId)) return null; 4747 if (query != null) { 4748 if (query.size() >= 1) { 4749 // If there is more than one service with the same priority, 4750 // just arbitrarily pick the first one. 4751 return query.get(0); 4752 } 4753 } 4754 return null; 4755 } 4756 4757 @Override 4758 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4759 int userId) { 4760 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4761 ComponentName comp = intent.getComponent(); 4762 if (comp == null) { 4763 if (intent.getSelector() != null) { 4764 intent = intent.getSelector(); 4765 comp = intent.getComponent(); 4766 } 4767 } 4768 if (comp != null) { 4769 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4770 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4771 if (si != null) { 4772 final ResolveInfo ri = new ResolveInfo(); 4773 ri.serviceInfo = si; 4774 list.add(ri); 4775 } 4776 return list; 4777 } 4778 4779 // reader 4780 synchronized (mPackages) { 4781 String pkgName = intent.getPackage(); 4782 if (pkgName == null) { 4783 return mServices.queryIntent(intent, resolvedType, flags, userId); 4784 } 4785 final PackageParser.Package pkg = mPackages.get(pkgName); 4786 if (pkg != null) { 4787 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4788 userId); 4789 } 4790 return null; 4791 } 4792 } 4793 4794 @Override 4795 public List<ResolveInfo> queryIntentContentProviders( 4796 Intent intent, String resolvedType, int flags, int userId) { 4797 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4798 ComponentName comp = intent.getComponent(); 4799 if (comp == null) { 4800 if (intent.getSelector() != null) { 4801 intent = intent.getSelector(); 4802 comp = intent.getComponent(); 4803 } 4804 } 4805 if (comp != null) { 4806 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4807 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4808 if (pi != null) { 4809 final ResolveInfo ri = new ResolveInfo(); 4810 ri.providerInfo = pi; 4811 list.add(ri); 4812 } 4813 return list; 4814 } 4815 4816 // reader 4817 synchronized (mPackages) { 4818 String pkgName = intent.getPackage(); 4819 if (pkgName == null) { 4820 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4821 } 4822 final PackageParser.Package pkg = mPackages.get(pkgName); 4823 if (pkg != null) { 4824 return mProviders.queryIntentForPackage( 4825 intent, resolvedType, flags, pkg.providers, userId); 4826 } 4827 return null; 4828 } 4829 } 4830 4831 @Override 4832 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4833 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4834 4835 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4836 4837 // writer 4838 synchronized (mPackages) { 4839 ArrayList<PackageInfo> list; 4840 if (listUninstalled) { 4841 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4842 for (PackageSetting ps : mSettings.mPackages.values()) { 4843 PackageInfo pi; 4844 if (ps.pkg != null) { 4845 pi = generatePackageInfo(ps.pkg, flags, userId); 4846 } else { 4847 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4848 } 4849 if (pi != null) { 4850 list.add(pi); 4851 } 4852 } 4853 } else { 4854 list = new ArrayList<PackageInfo>(mPackages.size()); 4855 for (PackageParser.Package p : mPackages.values()) { 4856 PackageInfo pi = generatePackageInfo(p, flags, userId); 4857 if (pi != null) { 4858 list.add(pi); 4859 } 4860 } 4861 } 4862 4863 return new ParceledListSlice<PackageInfo>(list); 4864 } 4865 } 4866 4867 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4868 String[] permissions, boolean[] tmp, int flags, int userId) { 4869 int numMatch = 0; 4870 final PermissionsState permissionsState = ps.getPermissionsState(); 4871 for (int i=0; i<permissions.length; i++) { 4872 final String permission = permissions[i]; 4873 if (permissionsState.hasPermission(permission, userId)) { 4874 tmp[i] = true; 4875 numMatch++; 4876 } else { 4877 tmp[i] = false; 4878 } 4879 } 4880 if (numMatch == 0) { 4881 return; 4882 } 4883 PackageInfo pi; 4884 if (ps.pkg != null) { 4885 pi = generatePackageInfo(ps.pkg, flags, userId); 4886 } else { 4887 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4888 } 4889 // The above might return null in cases of uninstalled apps or install-state 4890 // skew across users/profiles. 4891 if (pi != null) { 4892 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4893 if (numMatch == permissions.length) { 4894 pi.requestedPermissions = permissions; 4895 } else { 4896 pi.requestedPermissions = new String[numMatch]; 4897 numMatch = 0; 4898 for (int i=0; i<permissions.length; i++) { 4899 if (tmp[i]) { 4900 pi.requestedPermissions[numMatch] = permissions[i]; 4901 numMatch++; 4902 } 4903 } 4904 } 4905 } 4906 list.add(pi); 4907 } 4908 } 4909 4910 @Override 4911 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4912 String[] permissions, int flags, int userId) { 4913 if (!sUserManager.exists(userId)) return null; 4914 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4915 4916 // writer 4917 synchronized (mPackages) { 4918 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4919 boolean[] tmpBools = new boolean[permissions.length]; 4920 if (listUninstalled) { 4921 for (PackageSetting ps : mSettings.mPackages.values()) { 4922 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4923 } 4924 } else { 4925 for (PackageParser.Package pkg : mPackages.values()) { 4926 PackageSetting ps = (PackageSetting)pkg.mExtras; 4927 if (ps != null) { 4928 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4929 userId); 4930 } 4931 } 4932 } 4933 4934 return new ParceledListSlice<PackageInfo>(list); 4935 } 4936 } 4937 4938 @Override 4939 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4940 if (!sUserManager.exists(userId)) return null; 4941 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4942 4943 // writer 4944 synchronized (mPackages) { 4945 ArrayList<ApplicationInfo> list; 4946 if (listUninstalled) { 4947 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4948 for (PackageSetting ps : mSettings.mPackages.values()) { 4949 ApplicationInfo ai; 4950 if (ps.pkg != null) { 4951 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4952 ps.readUserState(userId), userId); 4953 } else { 4954 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4955 } 4956 if (ai != null) { 4957 list.add(ai); 4958 } 4959 } 4960 } else { 4961 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4962 for (PackageParser.Package p : mPackages.values()) { 4963 if (p.mExtras != null) { 4964 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4965 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4966 if (ai != null) { 4967 list.add(ai); 4968 } 4969 } 4970 } 4971 } 4972 4973 return new ParceledListSlice<ApplicationInfo>(list); 4974 } 4975 } 4976 4977 public List<ApplicationInfo> getPersistentApplications(int flags) { 4978 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4979 4980 // reader 4981 synchronized (mPackages) { 4982 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4983 final int userId = UserHandle.getCallingUserId(); 4984 while (i.hasNext()) { 4985 final PackageParser.Package p = i.next(); 4986 if (p.applicationInfo != null 4987 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4988 && (!mSafeMode || isSystemApp(p))) { 4989 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4990 if (ps != null) { 4991 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4992 ps.readUserState(userId), userId); 4993 if (ai != null) { 4994 finalList.add(ai); 4995 } 4996 } 4997 } 4998 } 4999 } 5000 5001 return finalList; 5002 } 5003 5004 @Override 5005 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 5006 if (!sUserManager.exists(userId)) return null; 5007 // reader 5008 synchronized (mPackages) { 5009 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 5010 PackageSetting ps = provider != null 5011 ? mSettings.mPackages.get(provider.owner.packageName) 5012 : null; 5013 return ps != null 5014 && mSettings.isEnabledLPr(provider.info, flags, userId) 5015 && (!mSafeMode || (provider.info.applicationInfo.flags 5016 &ApplicationInfo.FLAG_SYSTEM) != 0) 5017 ? PackageParser.generateProviderInfo(provider, flags, 5018 ps.readUserState(userId), userId) 5019 : null; 5020 } 5021 } 5022 5023 /** 5024 * @deprecated 5025 */ 5026 @Deprecated 5027 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 5028 // reader 5029 synchronized (mPackages) { 5030 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 5031 .entrySet().iterator(); 5032 final int userId = UserHandle.getCallingUserId(); 5033 while (i.hasNext()) { 5034 Map.Entry<String, PackageParser.Provider> entry = i.next(); 5035 PackageParser.Provider p = entry.getValue(); 5036 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5037 5038 if (ps != null && p.syncable 5039 && (!mSafeMode || (p.info.applicationInfo.flags 5040 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 5041 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 5042 ps.readUserState(userId), userId); 5043 if (info != null) { 5044 outNames.add(entry.getKey()); 5045 outInfo.add(info); 5046 } 5047 } 5048 } 5049 } 5050 } 5051 5052 @Override 5053 public List<ProviderInfo> queryContentProviders(String processName, 5054 int uid, int flags) { 5055 ArrayList<ProviderInfo> finalList = null; 5056 // reader 5057 synchronized (mPackages) { 5058 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 5059 final int userId = processName != null ? 5060 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 5061 while (i.hasNext()) { 5062 final PackageParser.Provider p = i.next(); 5063 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 5064 if (ps != null && p.info.authority != null 5065 && (processName == null 5066 || (p.info.processName.equals(processName) 5067 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 5068 && mSettings.isEnabledLPr(p.info, flags, userId) 5069 && (!mSafeMode 5070 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 5071 if (finalList == null) { 5072 finalList = new ArrayList<ProviderInfo>(3); 5073 } 5074 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 5075 ps.readUserState(userId), userId); 5076 if (info != null) { 5077 finalList.add(info); 5078 } 5079 } 5080 } 5081 } 5082 5083 if (finalList != null) { 5084 Collections.sort(finalList, mProviderInitOrderSorter); 5085 } 5086 5087 return finalList; 5088 } 5089 5090 @Override 5091 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 5092 int flags) { 5093 // reader 5094 synchronized (mPackages) { 5095 final PackageParser.Instrumentation i = mInstrumentation.get(name); 5096 return PackageParser.generateInstrumentationInfo(i, flags); 5097 } 5098 } 5099 5100 @Override 5101 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 5102 int flags) { 5103 ArrayList<InstrumentationInfo> finalList = 5104 new ArrayList<InstrumentationInfo>(); 5105 5106 // reader 5107 synchronized (mPackages) { 5108 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 5109 while (i.hasNext()) { 5110 final PackageParser.Instrumentation p = i.next(); 5111 if (targetPackage == null 5112 || targetPackage.equals(p.info.targetPackage)) { 5113 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 5114 flags); 5115 if (ii != null) { 5116 finalList.add(ii); 5117 } 5118 } 5119 } 5120 } 5121 5122 return finalList; 5123 } 5124 5125 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 5126 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 5127 if (overlays == null) { 5128 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 5129 return; 5130 } 5131 for (PackageParser.Package opkg : overlays.values()) { 5132 // Not much to do if idmap fails: we already logged the error 5133 // and we certainly don't want to abort installation of pkg simply 5134 // because an overlay didn't fit properly. For these reasons, 5135 // ignore the return value of createIdmapForPackagePairLI. 5136 createIdmapForPackagePairLI(pkg, opkg); 5137 } 5138 } 5139 5140 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5141 PackageParser.Package opkg) { 5142 if (!opkg.mTrustedOverlay) { 5143 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5144 opkg.baseCodePath + ": overlay not trusted"); 5145 return false; 5146 } 5147 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5148 if (overlaySet == null) { 5149 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5150 opkg.baseCodePath + " but target package has no known overlays"); 5151 return false; 5152 } 5153 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5154 // TODO: generate idmap for split APKs 5155 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5156 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5157 + opkg.baseCodePath); 5158 return false; 5159 } 5160 PackageParser.Package[] overlayArray = 5161 overlaySet.values().toArray(new PackageParser.Package[0]); 5162 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5163 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5164 return p1.mOverlayPriority - p2.mOverlayPriority; 5165 } 5166 }; 5167 Arrays.sort(overlayArray, cmp); 5168 5169 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5170 int i = 0; 5171 for (PackageParser.Package p : overlayArray) { 5172 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5173 } 5174 return true; 5175 } 5176 5177 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5178 final File[] files = dir.listFiles(); 5179 if (ArrayUtils.isEmpty(files)) { 5180 Log.d(TAG, "No files in app dir " + dir); 5181 return; 5182 } 5183 5184 if (DEBUG_PACKAGE_SCANNING) { 5185 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5186 + " flags=0x" + Integer.toHexString(parseFlags)); 5187 } 5188 5189 for (File file : files) { 5190 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5191 && !PackageInstallerService.isStageName(file.getName()); 5192 if (!isPackage) { 5193 // Ignore entries which are not packages 5194 continue; 5195 } 5196 try { 5197 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5198 scanFlags, currentTime, null); 5199 } catch (PackageManagerException e) { 5200 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5201 5202 // Delete invalid userdata apps 5203 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5204 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5205 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5206 if (file.isDirectory()) { 5207 mInstaller.rmPackageDir(file.getAbsolutePath()); 5208 } else { 5209 file.delete(); 5210 } 5211 } 5212 } 5213 } 5214 } 5215 5216 private static File getSettingsProblemFile() { 5217 File dataDir = Environment.getDataDirectory(); 5218 File systemDir = new File(dataDir, "system"); 5219 File fname = new File(systemDir, "uiderrors.txt"); 5220 return fname; 5221 } 5222 5223 static void reportSettingsProblem(int priority, String msg) { 5224 logCriticalInfo(priority, msg); 5225 } 5226 5227 static void logCriticalInfo(int priority, String msg) { 5228 Slog.println(priority, TAG, msg); 5229 EventLogTags.writePmCriticalInfo(msg); 5230 try { 5231 File fname = getSettingsProblemFile(); 5232 FileOutputStream out = new FileOutputStream(fname, true); 5233 PrintWriter pw = new FastPrintWriter(out); 5234 SimpleDateFormat formatter = new SimpleDateFormat(); 5235 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5236 pw.println(dateString + ": " + msg); 5237 pw.close(); 5238 FileUtils.setPermissions( 5239 fname.toString(), 5240 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5241 -1, -1); 5242 } catch (java.io.IOException e) { 5243 } 5244 } 5245 5246 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5247 PackageParser.Package pkg, File srcFile, int parseFlags) 5248 throws PackageManagerException { 5249 if (ps != null 5250 && ps.codePath.equals(srcFile) 5251 && ps.timeStamp == srcFile.lastModified() 5252 && !isCompatSignatureUpdateNeeded(pkg) 5253 && !isRecoverSignatureUpdateNeeded(pkg)) { 5254 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5255 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5256 ArraySet<PublicKey> signingKs; 5257 synchronized (mPackages) { 5258 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5259 } 5260 if (ps.signatures.mSignatures != null 5261 && ps.signatures.mSignatures.length != 0 5262 && signingKs != null) { 5263 // Optimization: reuse the existing cached certificates 5264 // if the package appears to be unchanged. 5265 pkg.mSignatures = ps.signatures.mSignatures; 5266 pkg.mSigningKeys = signingKs; 5267 return; 5268 } 5269 5270 Slog.w(TAG, "PackageSetting for " + ps.name 5271 + " is missing signatures. Collecting certs again to recover them."); 5272 } else { 5273 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5274 } 5275 5276 try { 5277 pp.collectCertificates(pkg, parseFlags); 5278 pp.collectManifestDigest(pkg); 5279 } catch (PackageParserException e) { 5280 throw PackageManagerException.from(e); 5281 } 5282 } 5283 5284 /* 5285 * Scan a package and return the newly parsed package. 5286 * Returns null in case of errors and the error code is stored in mLastScanError 5287 */ 5288 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5289 long currentTime, UserHandle user) throws PackageManagerException { 5290 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5291 parseFlags |= mDefParseFlags; 5292 PackageParser pp = new PackageParser(); 5293 pp.setSeparateProcesses(mSeparateProcesses); 5294 pp.setOnlyCoreApps(mOnlyCore); 5295 pp.setDisplayMetrics(mMetrics); 5296 5297 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5298 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5299 } 5300 5301 final PackageParser.Package pkg; 5302 try { 5303 pkg = pp.parsePackage(scanFile, parseFlags); 5304 } catch (PackageParserException e) { 5305 throw PackageManagerException.from(e); 5306 } 5307 5308 PackageSetting ps = null; 5309 PackageSetting updatedPkg; 5310 // reader 5311 synchronized (mPackages) { 5312 // Look to see if we already know about this package. 5313 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5314 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5315 // This package has been renamed to its original name. Let's 5316 // use that. 5317 ps = mSettings.peekPackageLPr(oldName); 5318 } 5319 // If there was no original package, see one for the real package name. 5320 if (ps == null) { 5321 ps = mSettings.peekPackageLPr(pkg.packageName); 5322 } 5323 // Check to see if this package could be hiding/updating a system 5324 // package. Must look for it either under the original or real 5325 // package name depending on our state. 5326 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5327 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5328 } 5329 boolean updatedPkgBetter = false; 5330 // First check if this is a system package that may involve an update 5331 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5332 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5333 // it needs to drop FLAG_PRIVILEGED. 5334 if (locationIsPrivileged(scanFile)) { 5335 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5336 } else { 5337 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5338 } 5339 5340 if (ps != null && !ps.codePath.equals(scanFile)) { 5341 // The path has changed from what was last scanned... check the 5342 // version of the new path against what we have stored to determine 5343 // what to do. 5344 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5345 if (pkg.mVersionCode <= ps.versionCode) { 5346 // The system package has been updated and the code path does not match 5347 // Ignore entry. Skip it. 5348 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5349 + " ignored: updated version " + ps.versionCode 5350 + " better than this " + pkg.mVersionCode); 5351 if (!updatedPkg.codePath.equals(scanFile)) { 5352 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5353 + ps.name + " changing from " + updatedPkg.codePathString 5354 + " to " + scanFile); 5355 updatedPkg.codePath = scanFile; 5356 updatedPkg.codePathString = scanFile.toString(); 5357 updatedPkg.resourcePath = scanFile; 5358 updatedPkg.resourcePathString = scanFile.toString(); 5359 } 5360 updatedPkg.pkg = pkg; 5361 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5362 } else { 5363 // The current app on the system partition is better than 5364 // what we have updated to on the data partition; switch 5365 // back to the system partition version. 5366 // At this point, its safely assumed that package installation for 5367 // apps in system partition will go through. If not there won't be a working 5368 // version of the app 5369 // writer 5370 synchronized (mPackages) { 5371 // Just remove the loaded entries from package lists. 5372 mPackages.remove(ps.name); 5373 } 5374 5375 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5376 + " reverting from " + ps.codePathString 5377 + ": new version " + pkg.mVersionCode 5378 + " better than installed " + ps.versionCode); 5379 5380 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5381 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5382 synchronized (mInstallLock) { 5383 args.cleanUpResourcesLI(); 5384 } 5385 synchronized (mPackages) { 5386 mSettings.enableSystemPackageLPw(ps.name); 5387 } 5388 updatedPkgBetter = true; 5389 } 5390 } 5391 } 5392 5393 if (updatedPkg != null) { 5394 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5395 // initially 5396 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5397 5398 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5399 // flag set initially 5400 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5401 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5402 } 5403 } 5404 5405 // Verify certificates against what was last scanned 5406 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5407 5408 /* 5409 * A new system app appeared, but we already had a non-system one of the 5410 * same name installed earlier. 5411 */ 5412 boolean shouldHideSystemApp = false; 5413 if (updatedPkg == null && ps != null 5414 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5415 /* 5416 * Check to make sure the signatures match first. If they don't, 5417 * wipe the installed application and its data. 5418 */ 5419 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5420 != PackageManager.SIGNATURE_MATCH) { 5421 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5422 + " signatures don't match existing userdata copy; removing"); 5423 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5424 ps = null; 5425 } else { 5426 /* 5427 * If the newly-added system app is an older version than the 5428 * already installed version, hide it. It will be scanned later 5429 * and re-added like an update. 5430 */ 5431 if (pkg.mVersionCode <= ps.versionCode) { 5432 shouldHideSystemApp = true; 5433 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5434 + " but new version " + pkg.mVersionCode + " better than installed " 5435 + ps.versionCode + "; hiding system"); 5436 } else { 5437 /* 5438 * The newly found system app is a newer version that the 5439 * one previously installed. Simply remove the 5440 * already-installed application and replace it with our own 5441 * while keeping the application data. 5442 */ 5443 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5444 + " reverting from " + ps.codePathString + ": new version " 5445 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5446 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5447 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5448 synchronized (mInstallLock) { 5449 args.cleanUpResourcesLI(); 5450 } 5451 } 5452 } 5453 } 5454 5455 // The apk is forward locked (not public) if its code and resources 5456 // are kept in different files. (except for app in either system or 5457 // vendor path). 5458 // TODO grab this value from PackageSettings 5459 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5460 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5461 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5462 } 5463 } 5464 5465 // TODO: extend to support forward-locked splits 5466 String resourcePath = null; 5467 String baseResourcePath = null; 5468 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5469 if (ps != null && ps.resourcePathString != null) { 5470 resourcePath = ps.resourcePathString; 5471 baseResourcePath = ps.resourcePathString; 5472 } else { 5473 // Should not happen at all. Just log an error. 5474 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5475 } 5476 } else { 5477 resourcePath = pkg.codePath; 5478 baseResourcePath = pkg.baseCodePath; 5479 } 5480 5481 // Set application objects path explicitly. 5482 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5483 pkg.applicationInfo.setCodePath(pkg.codePath); 5484 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5485 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5486 pkg.applicationInfo.setResourcePath(resourcePath); 5487 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5488 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5489 5490 // Note that we invoke the following method only if we are about to unpack an application 5491 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5492 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5493 5494 /* 5495 * If the system app should be overridden by a previously installed 5496 * data, hide the system app now and let the /data/app scan pick it up 5497 * again. 5498 */ 5499 if (shouldHideSystemApp) { 5500 synchronized (mPackages) { 5501 /* 5502 * We have to grant systems permissions before we hide, because 5503 * grantPermissions will assume the package update is trying to 5504 * expand its permissions. 5505 */ 5506 grantPermissionsLPw(pkg, true, pkg.packageName); 5507 mSettings.disableSystemPackageLPw(pkg.packageName); 5508 } 5509 } 5510 5511 return scannedPkg; 5512 } 5513 5514 private static String fixProcessName(String defProcessName, 5515 String processName, int uid) { 5516 if (processName == null) { 5517 return defProcessName; 5518 } 5519 return processName; 5520 } 5521 5522 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5523 throws PackageManagerException { 5524 if (pkgSetting.signatures.mSignatures != null) { 5525 // Already existing package. Make sure signatures match 5526 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5527 == PackageManager.SIGNATURE_MATCH; 5528 if (!match) { 5529 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5530 == PackageManager.SIGNATURE_MATCH; 5531 } 5532 if (!match) { 5533 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5534 == PackageManager.SIGNATURE_MATCH; 5535 } 5536 if (!match) { 5537 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5538 + pkg.packageName + " signatures do not match the " 5539 + "previously installed version; ignoring!"); 5540 } 5541 } 5542 5543 // Check for shared user signatures 5544 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5545 // Already existing package. Make sure signatures match 5546 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5547 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5548 if (!match) { 5549 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5550 == PackageManager.SIGNATURE_MATCH; 5551 } 5552 if (!match) { 5553 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5554 == PackageManager.SIGNATURE_MATCH; 5555 } 5556 if (!match) { 5557 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5558 "Package " + pkg.packageName 5559 + " has no signatures that match those in shared user " 5560 + pkgSetting.sharedUser.name + "; ignoring!"); 5561 } 5562 } 5563 } 5564 5565 /** 5566 * Enforces that only the system UID or root's UID can call a method exposed 5567 * via Binder. 5568 * 5569 * @param message used as message if SecurityException is thrown 5570 * @throws SecurityException if the caller is not system or root 5571 */ 5572 private static final void enforceSystemOrRoot(String message) { 5573 final int uid = Binder.getCallingUid(); 5574 if (uid != Process.SYSTEM_UID && uid != 0) { 5575 throw new SecurityException(message); 5576 } 5577 } 5578 5579 @Override 5580 public void performBootDexOpt() { 5581 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5582 5583 // Before everything else, see whether we need to fstrim. 5584 try { 5585 IMountService ms = PackageHelper.getMountService(); 5586 if (ms != null) { 5587 final boolean isUpgrade = isUpgrade(); 5588 boolean doTrim = isUpgrade; 5589 if (doTrim) { 5590 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5591 } else { 5592 final long interval = android.provider.Settings.Global.getLong( 5593 mContext.getContentResolver(), 5594 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5595 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5596 if (interval > 0) { 5597 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5598 if (timeSinceLast > interval) { 5599 doTrim = true; 5600 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5601 + "; running immediately"); 5602 } 5603 } 5604 } 5605 if (doTrim) { 5606 if (!isFirstBoot()) { 5607 try { 5608 ActivityManagerNative.getDefault().showBootMessage( 5609 mContext.getResources().getString( 5610 R.string.android_upgrading_fstrim), true); 5611 } catch (RemoteException e) { 5612 } 5613 } 5614 ms.runMaintenance(); 5615 } 5616 } else { 5617 Slog.e(TAG, "Mount service unavailable!"); 5618 } 5619 } catch (RemoteException e) { 5620 // Can't happen; MountService is local 5621 } 5622 5623 final ArraySet<PackageParser.Package> pkgs; 5624 synchronized (mPackages) { 5625 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5626 } 5627 5628 if (pkgs != null) { 5629 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5630 // in case the device runs out of space. 5631 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5632 // Give priority to core apps. 5633 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5634 PackageParser.Package pkg = it.next(); 5635 if (pkg.coreApp) { 5636 if (DEBUG_DEXOPT) { 5637 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5638 } 5639 sortedPkgs.add(pkg); 5640 it.remove(); 5641 } 5642 } 5643 // Give priority to system apps that listen for pre boot complete. 5644 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5645 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5646 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5647 PackageParser.Package pkg = it.next(); 5648 if (pkgNames.contains(pkg.packageName)) { 5649 if (DEBUG_DEXOPT) { 5650 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5651 } 5652 sortedPkgs.add(pkg); 5653 it.remove(); 5654 } 5655 } 5656 // Give priority to system apps. 5657 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5658 PackageParser.Package pkg = it.next(); 5659 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5660 if (DEBUG_DEXOPT) { 5661 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5662 } 5663 sortedPkgs.add(pkg); 5664 it.remove(); 5665 } 5666 } 5667 // Give priority to updated system apps. 5668 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5669 PackageParser.Package pkg = it.next(); 5670 if (pkg.isUpdatedSystemApp()) { 5671 if (DEBUG_DEXOPT) { 5672 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5673 } 5674 sortedPkgs.add(pkg); 5675 it.remove(); 5676 } 5677 } 5678 // Give priority to apps that listen for boot complete. 5679 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5680 pkgNames = getPackageNamesForIntent(intent); 5681 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5682 PackageParser.Package pkg = it.next(); 5683 if (pkgNames.contains(pkg.packageName)) { 5684 if (DEBUG_DEXOPT) { 5685 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5686 } 5687 sortedPkgs.add(pkg); 5688 it.remove(); 5689 } 5690 } 5691 // Filter out packages that aren't recently used. 5692 filterRecentlyUsedApps(pkgs); 5693 // Add all remaining apps. 5694 for (PackageParser.Package pkg : pkgs) { 5695 if (DEBUG_DEXOPT) { 5696 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5697 } 5698 sortedPkgs.add(pkg); 5699 } 5700 5701 // If we want to be lazy, filter everything that wasn't recently used. 5702 if (mLazyDexOpt) { 5703 filterRecentlyUsedApps(sortedPkgs); 5704 } 5705 5706 int i = 0; 5707 int total = sortedPkgs.size(); 5708 File dataDir = Environment.getDataDirectory(); 5709 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5710 if (lowThreshold == 0) { 5711 throw new IllegalStateException("Invalid low memory threshold"); 5712 } 5713 for (PackageParser.Package pkg : sortedPkgs) { 5714 long usableSpace = dataDir.getUsableSpace(); 5715 if (usableSpace < lowThreshold) { 5716 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5717 break; 5718 } 5719 performBootDexOpt(pkg, ++i, total); 5720 } 5721 } 5722 } 5723 5724 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5725 // Filter out packages that aren't recently used. 5726 // 5727 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5728 // should do a full dexopt. 5729 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5730 int total = pkgs.size(); 5731 int skipped = 0; 5732 long now = System.currentTimeMillis(); 5733 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5734 PackageParser.Package pkg = i.next(); 5735 long then = pkg.mLastPackageUsageTimeInMills; 5736 if (then + mDexOptLRUThresholdInMills < now) { 5737 if (DEBUG_DEXOPT) { 5738 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5739 ((then == 0) ? "never" : new Date(then))); 5740 } 5741 i.remove(); 5742 skipped++; 5743 } 5744 } 5745 if (DEBUG_DEXOPT) { 5746 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5747 } 5748 } 5749 } 5750 5751 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5752 List<ResolveInfo> ris = null; 5753 try { 5754 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5755 intent, null, 0, UserHandle.USER_OWNER); 5756 } catch (RemoteException e) { 5757 } 5758 ArraySet<String> pkgNames = new ArraySet<String>(); 5759 if (ris != null) { 5760 for (ResolveInfo ri : ris) { 5761 pkgNames.add(ri.activityInfo.packageName); 5762 } 5763 } 5764 return pkgNames; 5765 } 5766 5767 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5768 if (DEBUG_DEXOPT) { 5769 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5770 } 5771 if (!isFirstBoot()) { 5772 try { 5773 ActivityManagerNative.getDefault().showBootMessage( 5774 mContext.getResources().getString(R.string.android_upgrading_apk, 5775 curr, total), true); 5776 } catch (RemoteException e) { 5777 } 5778 } 5779 PackageParser.Package p = pkg; 5780 synchronized (mInstallLock) { 5781 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5782 false /* force dex */, false /* defer */, true /* include dependencies */); 5783 } 5784 } 5785 5786 @Override 5787 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5788 return performDexOpt(packageName, instructionSet, false); 5789 } 5790 5791 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5792 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5793 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5794 if (!dexopt && !updateUsage) { 5795 // We aren't going to dexopt or update usage, so bail early. 5796 return false; 5797 } 5798 PackageParser.Package p; 5799 final String targetInstructionSet; 5800 synchronized (mPackages) { 5801 p = mPackages.get(packageName); 5802 if (p == null) { 5803 return false; 5804 } 5805 if (updateUsage) { 5806 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5807 } 5808 mPackageUsage.write(false); 5809 if (!dexopt) { 5810 // We aren't going to dexopt, so bail early. 5811 return false; 5812 } 5813 5814 targetInstructionSet = instructionSet != null ? instructionSet : 5815 getPrimaryInstructionSet(p.applicationInfo); 5816 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5817 return false; 5818 } 5819 } 5820 5821 synchronized (mInstallLock) { 5822 final String[] instructionSets = new String[] { targetInstructionSet }; 5823 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5824 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5825 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5826 } 5827 } 5828 5829 public ArraySet<String> getPackagesThatNeedDexOpt() { 5830 ArraySet<String> pkgs = null; 5831 synchronized (mPackages) { 5832 for (PackageParser.Package p : mPackages.values()) { 5833 if (DEBUG_DEXOPT) { 5834 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5835 } 5836 if (!p.mDexOptPerformed.isEmpty()) { 5837 continue; 5838 } 5839 if (pkgs == null) { 5840 pkgs = new ArraySet<String>(); 5841 } 5842 pkgs.add(p.packageName); 5843 } 5844 } 5845 return pkgs; 5846 } 5847 5848 public void shutdown() { 5849 mPackageUsage.write(true); 5850 } 5851 5852 @Override 5853 public void forceDexOpt(String packageName) { 5854 enforceSystemOrRoot("forceDexOpt"); 5855 5856 PackageParser.Package pkg; 5857 synchronized (mPackages) { 5858 pkg = mPackages.get(packageName); 5859 if (pkg == null) { 5860 throw new IllegalArgumentException("Missing package: " + packageName); 5861 } 5862 } 5863 5864 synchronized (mInstallLock) { 5865 final String[] instructionSets = new String[] { 5866 getPrimaryInstructionSet(pkg.applicationInfo) }; 5867 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5868 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5869 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5870 throw new IllegalStateException("Failed to dexopt: " + res); 5871 } 5872 } 5873 } 5874 5875 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5876 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5877 Slog.w(TAG, "Unable to update from " + oldPkg.name 5878 + " to " + newPkg.packageName 5879 + ": old package not in system partition"); 5880 return false; 5881 } else if (mPackages.get(oldPkg.name) != null) { 5882 Slog.w(TAG, "Unable to update from " + oldPkg.name 5883 + " to " + newPkg.packageName 5884 + ": old package still exists"); 5885 return false; 5886 } 5887 return true; 5888 } 5889 5890 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5891 int[] users = sUserManager.getUserIds(); 5892 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5893 if (res < 0) { 5894 return res; 5895 } 5896 for (int user : users) { 5897 if (user != 0) { 5898 res = mInstaller.createUserData(volumeUuid, packageName, 5899 UserHandle.getUid(user, uid), user, seinfo); 5900 if (res < 0) { 5901 return res; 5902 } 5903 } 5904 } 5905 return res; 5906 } 5907 5908 private int removeDataDirsLI(String volumeUuid, String packageName) { 5909 int[] users = sUserManager.getUserIds(); 5910 int res = 0; 5911 for (int user : users) { 5912 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5913 if (resInner < 0) { 5914 res = resInner; 5915 } 5916 } 5917 5918 return res; 5919 } 5920 5921 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5922 int[] users = sUserManager.getUserIds(); 5923 int res = 0; 5924 for (int user : users) { 5925 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5926 if (resInner < 0) { 5927 res = resInner; 5928 } 5929 } 5930 return res; 5931 } 5932 5933 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5934 PackageParser.Package changingLib) { 5935 if (file.path != null) { 5936 usesLibraryFiles.add(file.path); 5937 return; 5938 } 5939 PackageParser.Package p = mPackages.get(file.apk); 5940 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5941 // If we are doing this while in the middle of updating a library apk, 5942 // then we need to make sure to use that new apk for determining the 5943 // dependencies here. (We haven't yet finished committing the new apk 5944 // to the package manager state.) 5945 if (p == null || p.packageName.equals(changingLib.packageName)) { 5946 p = changingLib; 5947 } 5948 } 5949 if (p != null) { 5950 usesLibraryFiles.addAll(p.getAllCodePaths()); 5951 } 5952 } 5953 5954 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5955 PackageParser.Package changingLib) throws PackageManagerException { 5956 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5957 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5958 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5959 for (int i=0; i<N; i++) { 5960 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5961 if (file == null) { 5962 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5963 "Package " + pkg.packageName + " requires unavailable shared library " 5964 + pkg.usesLibraries.get(i) + "; failing!"); 5965 } 5966 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5967 } 5968 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5969 for (int i=0; i<N; i++) { 5970 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5971 if (file == null) { 5972 Slog.w(TAG, "Package " + pkg.packageName 5973 + " desires unavailable shared library " 5974 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5975 } else { 5976 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5977 } 5978 } 5979 N = usesLibraryFiles.size(); 5980 if (N > 0) { 5981 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5982 } else { 5983 pkg.usesLibraryFiles = null; 5984 } 5985 } 5986 } 5987 5988 private static boolean hasString(List<String> list, List<String> which) { 5989 if (list == null) { 5990 return false; 5991 } 5992 for (int i=list.size()-1; i>=0; i--) { 5993 for (int j=which.size()-1; j>=0; j--) { 5994 if (which.get(j).equals(list.get(i))) { 5995 return true; 5996 } 5997 } 5998 } 5999 return false; 6000 } 6001 6002 private void updateAllSharedLibrariesLPw() { 6003 for (PackageParser.Package pkg : mPackages.values()) { 6004 try { 6005 updateSharedLibrariesLPw(pkg, null); 6006 } catch (PackageManagerException e) { 6007 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6008 } 6009 } 6010 } 6011 6012 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 6013 PackageParser.Package changingPkg) { 6014 ArrayList<PackageParser.Package> res = null; 6015 for (PackageParser.Package pkg : mPackages.values()) { 6016 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 6017 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 6018 if (res == null) { 6019 res = new ArrayList<PackageParser.Package>(); 6020 } 6021 res.add(pkg); 6022 try { 6023 updateSharedLibrariesLPw(pkg, changingPkg); 6024 } catch (PackageManagerException e) { 6025 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 6026 } 6027 } 6028 } 6029 return res; 6030 } 6031 6032 /** 6033 * Derive the value of the {@code cpuAbiOverride} based on the provided 6034 * value and an optional stored value from the package settings. 6035 */ 6036 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 6037 String cpuAbiOverride = null; 6038 6039 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 6040 cpuAbiOverride = null; 6041 } else if (abiOverride != null) { 6042 cpuAbiOverride = abiOverride; 6043 } else if (settings != null) { 6044 cpuAbiOverride = settings.cpuAbiOverrideString; 6045 } 6046 6047 return cpuAbiOverride; 6048 } 6049 6050 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 6051 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6052 boolean success = false; 6053 try { 6054 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 6055 currentTime, user); 6056 success = true; 6057 return res; 6058 } finally { 6059 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 6060 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 6061 } 6062 } 6063 } 6064 6065 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 6066 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6067 final File scanFile = new File(pkg.codePath); 6068 if (pkg.applicationInfo.getCodePath() == null || 6069 pkg.applicationInfo.getResourcePath() == null) { 6070 // Bail out. The resource and code paths haven't been set. 6071 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 6072 "Code and resource paths haven't been set correctly"); 6073 } 6074 6075 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 6076 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 6077 } else { 6078 // Only allow system apps to be flagged as core apps. 6079 pkg.coreApp = false; 6080 } 6081 6082 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 6083 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6084 } 6085 6086 if (mCustomResolverComponentName != null && 6087 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 6088 setUpCustomResolverActivity(pkg); 6089 } 6090 6091 if (pkg.packageName.equals("android")) { 6092 synchronized (mPackages) { 6093 if (mAndroidApplication != null) { 6094 Slog.w(TAG, "*************************************************"); 6095 Slog.w(TAG, "Core android package being redefined. Skipping."); 6096 Slog.w(TAG, " file=" + scanFile); 6097 Slog.w(TAG, "*************************************************"); 6098 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6099 "Core android package being redefined. Skipping."); 6100 } 6101 6102 // Set up information for our fall-back user intent resolution activity. 6103 mPlatformPackage = pkg; 6104 pkg.mVersionCode = mSdkVersion; 6105 mAndroidApplication = pkg.applicationInfo; 6106 6107 if (!mResolverReplaced) { 6108 mResolveActivity.applicationInfo = mAndroidApplication; 6109 mResolveActivity.name = ResolverActivity.class.getName(); 6110 mResolveActivity.packageName = mAndroidApplication.packageName; 6111 mResolveActivity.processName = "system:ui"; 6112 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6113 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 6114 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 6115 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 6116 mResolveActivity.exported = true; 6117 mResolveActivity.enabled = true; 6118 mResolveInfo.activityInfo = mResolveActivity; 6119 mResolveInfo.priority = 0; 6120 mResolveInfo.preferredOrder = 0; 6121 mResolveInfo.match = 0; 6122 mResolveComponentName = new ComponentName( 6123 mAndroidApplication.packageName, mResolveActivity.name); 6124 } 6125 } 6126 } 6127 6128 if (DEBUG_PACKAGE_SCANNING) { 6129 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6130 Log.d(TAG, "Scanning package " + pkg.packageName); 6131 } 6132 6133 if (mPackages.containsKey(pkg.packageName) 6134 || mSharedLibraries.containsKey(pkg.packageName)) { 6135 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 6136 "Application package " + pkg.packageName 6137 + " already installed. Skipping duplicate."); 6138 } 6139 6140 // If we're only installing presumed-existing packages, require that the 6141 // scanned APK is both already known and at the path previously established 6142 // for it. Previously unknown packages we pick up normally, but if we have an 6143 // a priori expectation about this package's install presence, enforce it. 6144 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6145 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6146 if (known != null) { 6147 if (DEBUG_PACKAGE_SCANNING) { 6148 Log.d(TAG, "Examining " + pkg.codePath 6149 + " and requiring known paths " + known.codePathString 6150 + " & " + known.resourcePathString); 6151 } 6152 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6153 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6154 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6155 "Application package " + pkg.packageName 6156 + " found at " + pkg.applicationInfo.getCodePath() 6157 + " but expected at " + known.codePathString + "; ignoring."); 6158 } 6159 } 6160 } 6161 6162 // Initialize package source and resource directories 6163 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6164 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6165 6166 SharedUserSetting suid = null; 6167 PackageSetting pkgSetting = null; 6168 6169 if (!isSystemApp(pkg)) { 6170 // Only system apps can use these features. 6171 pkg.mOriginalPackages = null; 6172 pkg.mRealPackage = null; 6173 pkg.mAdoptPermissions = null; 6174 } 6175 6176 // writer 6177 synchronized (mPackages) { 6178 if (pkg.mSharedUserId != null) { 6179 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6180 if (suid == null) { 6181 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6182 "Creating application package " + pkg.packageName 6183 + " for shared user failed"); 6184 } 6185 if (DEBUG_PACKAGE_SCANNING) { 6186 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6187 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6188 + "): packages=" + suid.packages); 6189 } 6190 } 6191 6192 // Check if we are renaming from an original package name. 6193 PackageSetting origPackage = null; 6194 String realName = null; 6195 if (pkg.mOriginalPackages != null) { 6196 // This package may need to be renamed to a previously 6197 // installed name. Let's check on that... 6198 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6199 if (pkg.mOriginalPackages.contains(renamed)) { 6200 // This package had originally been installed as the 6201 // original name, and we have already taken care of 6202 // transitioning to the new one. Just update the new 6203 // one to continue using the old name. 6204 realName = pkg.mRealPackage; 6205 if (!pkg.packageName.equals(renamed)) { 6206 // Callers into this function may have already taken 6207 // care of renaming the package; only do it here if 6208 // it is not already done. 6209 pkg.setPackageName(renamed); 6210 } 6211 6212 } else { 6213 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6214 if ((origPackage = mSettings.peekPackageLPr( 6215 pkg.mOriginalPackages.get(i))) != null) { 6216 // We do have the package already installed under its 6217 // original name... should we use it? 6218 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6219 // New package is not compatible with original. 6220 origPackage = null; 6221 continue; 6222 } else if (origPackage.sharedUser != null) { 6223 // Make sure uid is compatible between packages. 6224 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6225 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6226 + " to " + pkg.packageName + ": old uid " 6227 + origPackage.sharedUser.name 6228 + " differs from " + pkg.mSharedUserId); 6229 origPackage = null; 6230 continue; 6231 } 6232 } else { 6233 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6234 + pkg.packageName + " to old name " + origPackage.name); 6235 } 6236 break; 6237 } 6238 } 6239 } 6240 } 6241 6242 if (mTransferedPackages.contains(pkg.packageName)) { 6243 Slog.w(TAG, "Package " + pkg.packageName 6244 + " was transferred to another, but its .apk remains"); 6245 } 6246 6247 // Just create the setting, don't add it yet. For already existing packages 6248 // the PkgSetting exists already and doesn't have to be created. 6249 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6250 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6251 pkg.applicationInfo.primaryCpuAbi, 6252 pkg.applicationInfo.secondaryCpuAbi, 6253 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6254 user, false); 6255 if (pkgSetting == null) { 6256 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6257 "Creating application package " + pkg.packageName + " failed"); 6258 } 6259 6260 if (pkgSetting.origPackage != null) { 6261 // If we are first transitioning from an original package, 6262 // fix up the new package's name now. We need to do this after 6263 // looking up the package under its new name, so getPackageLP 6264 // can take care of fiddling things correctly. 6265 pkg.setPackageName(origPackage.name); 6266 6267 // File a report about this. 6268 String msg = "New package " + pkgSetting.realName 6269 + " renamed to replace old package " + pkgSetting.name; 6270 reportSettingsProblem(Log.WARN, msg); 6271 6272 // Make a note of it. 6273 mTransferedPackages.add(origPackage.name); 6274 6275 // No longer need to retain this. 6276 pkgSetting.origPackage = null; 6277 } 6278 6279 if (realName != null) { 6280 // Make a note of it. 6281 mTransferedPackages.add(pkg.packageName); 6282 } 6283 6284 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6285 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6286 } 6287 6288 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6289 // Check all shared libraries and map to their actual file path. 6290 // We only do this here for apps not on a system dir, because those 6291 // are the only ones that can fail an install due to this. We 6292 // will take care of the system apps by updating all of their 6293 // library paths after the scan is done. 6294 updateSharedLibrariesLPw(pkg, null); 6295 } 6296 6297 if (mFoundPolicyFile) { 6298 SELinuxMMAC.assignSeinfoValue(pkg); 6299 } 6300 6301 pkg.applicationInfo.uid = pkgSetting.appId; 6302 pkg.mExtras = pkgSetting; 6303 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6304 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6305 // We just determined the app is signed correctly, so bring 6306 // over the latest parsed certs. 6307 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6308 } else { 6309 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6310 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6311 "Package " + pkg.packageName + " upgrade keys do not match the " 6312 + "previously installed version"); 6313 } else { 6314 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6315 String msg = "System package " + pkg.packageName 6316 + " signature changed; retaining data."; 6317 reportSettingsProblem(Log.WARN, msg); 6318 } 6319 } 6320 } else { 6321 try { 6322 verifySignaturesLP(pkgSetting, pkg); 6323 // We just determined the app is signed correctly, so bring 6324 // over the latest parsed certs. 6325 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6326 } catch (PackageManagerException e) { 6327 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6328 throw e; 6329 } 6330 // The signature has changed, but this package is in the system 6331 // image... let's recover! 6332 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6333 // However... if this package is part of a shared user, but it 6334 // doesn't match the signature of the shared user, let's fail. 6335 // What this means is that you can't change the signatures 6336 // associated with an overall shared user, which doesn't seem all 6337 // that unreasonable. 6338 if (pkgSetting.sharedUser != null) { 6339 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6340 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6341 throw new PackageManagerException( 6342 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6343 "Signature mismatch for shared user : " 6344 + pkgSetting.sharedUser); 6345 } 6346 } 6347 // File a report about this. 6348 String msg = "System package " + pkg.packageName 6349 + " signature changed; retaining data."; 6350 reportSettingsProblem(Log.WARN, msg); 6351 } 6352 } 6353 // Verify that this new package doesn't have any content providers 6354 // that conflict with existing packages. Only do this if the 6355 // package isn't already installed, since we don't want to break 6356 // things that are installed. 6357 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6358 final int N = pkg.providers.size(); 6359 int i; 6360 for (i=0; i<N; i++) { 6361 PackageParser.Provider p = pkg.providers.get(i); 6362 if (p.info.authority != null) { 6363 String names[] = p.info.authority.split(";"); 6364 for (int j = 0; j < names.length; j++) { 6365 if (mProvidersByAuthority.containsKey(names[j])) { 6366 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6367 final String otherPackageName = 6368 ((other != null && other.getComponentName() != null) ? 6369 other.getComponentName().getPackageName() : "?"); 6370 throw new PackageManagerException( 6371 INSTALL_FAILED_CONFLICTING_PROVIDER, 6372 "Can't install because provider name " + names[j] 6373 + " (in package " + pkg.applicationInfo.packageName 6374 + ") is already used by " + otherPackageName); 6375 } 6376 } 6377 } 6378 } 6379 } 6380 6381 if (pkg.mAdoptPermissions != null) { 6382 // This package wants to adopt ownership of permissions from 6383 // another package. 6384 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6385 final String origName = pkg.mAdoptPermissions.get(i); 6386 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6387 if (orig != null) { 6388 if (verifyPackageUpdateLPr(orig, pkg)) { 6389 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6390 + pkg.packageName); 6391 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6392 } 6393 } 6394 } 6395 } 6396 } 6397 6398 final String pkgName = pkg.packageName; 6399 6400 final long scanFileTime = scanFile.lastModified(); 6401 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6402 pkg.applicationInfo.processName = fixProcessName( 6403 pkg.applicationInfo.packageName, 6404 pkg.applicationInfo.processName, 6405 pkg.applicationInfo.uid); 6406 6407 File dataPath; 6408 if (mPlatformPackage == pkg) { 6409 // The system package is special. 6410 dataPath = new File(Environment.getDataDirectory(), "system"); 6411 6412 pkg.applicationInfo.dataDir = dataPath.getPath(); 6413 6414 } else { 6415 // This is a normal package, need to make its data directory. 6416 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6417 UserHandle.USER_OWNER); 6418 6419 boolean uidError = false; 6420 if (dataPath.exists()) { 6421 int currentUid = 0; 6422 try { 6423 StructStat stat = Os.stat(dataPath.getPath()); 6424 currentUid = stat.st_uid; 6425 } catch (ErrnoException e) { 6426 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6427 } 6428 6429 // If we have mismatched owners for the data path, we have a problem. 6430 if (currentUid != pkg.applicationInfo.uid) { 6431 boolean recovered = false; 6432 if (currentUid == 0) { 6433 // The directory somehow became owned by root. Wow. 6434 // This is probably because the system was stopped while 6435 // installd was in the middle of messing with its libs 6436 // directory. Ask installd to fix that. 6437 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6438 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6439 if (ret >= 0) { 6440 recovered = true; 6441 String msg = "Package " + pkg.packageName 6442 + " unexpectedly changed to uid 0; recovered to " + 6443 + pkg.applicationInfo.uid; 6444 reportSettingsProblem(Log.WARN, msg); 6445 } 6446 } 6447 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6448 || (scanFlags&SCAN_BOOTING) != 0)) { 6449 // If this is a system app, we can at least delete its 6450 // current data so the application will still work. 6451 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6452 if (ret >= 0) { 6453 // TODO: Kill the processes first 6454 // Old data gone! 6455 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6456 ? "System package " : "Third party package "; 6457 String msg = prefix + pkg.packageName 6458 + " has changed from uid: " 6459 + currentUid + " to " 6460 + pkg.applicationInfo.uid + "; old data erased"; 6461 reportSettingsProblem(Log.WARN, msg); 6462 recovered = true; 6463 6464 // And now re-install the app. 6465 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6466 pkg.applicationInfo.seinfo); 6467 if (ret == -1) { 6468 // Ack should not happen! 6469 msg = prefix + pkg.packageName 6470 + " could not have data directory re-created after delete."; 6471 reportSettingsProblem(Log.WARN, msg); 6472 throw new PackageManagerException( 6473 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6474 } 6475 } 6476 if (!recovered) { 6477 mHasSystemUidErrors = true; 6478 } 6479 } else if (!recovered) { 6480 // If we allow this install to proceed, we will be broken. 6481 // Abort, abort! 6482 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6483 "scanPackageLI"); 6484 } 6485 if (!recovered) { 6486 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6487 + pkg.applicationInfo.uid + "/fs_" 6488 + currentUid; 6489 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6490 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6491 String msg = "Package " + pkg.packageName 6492 + " has mismatched uid: " 6493 + currentUid + " on disk, " 6494 + pkg.applicationInfo.uid + " in settings"; 6495 // writer 6496 synchronized (mPackages) { 6497 mSettings.mReadMessages.append(msg); 6498 mSettings.mReadMessages.append('\n'); 6499 uidError = true; 6500 if (!pkgSetting.uidError) { 6501 reportSettingsProblem(Log.ERROR, msg); 6502 } 6503 } 6504 } 6505 } 6506 pkg.applicationInfo.dataDir = dataPath.getPath(); 6507 if (mShouldRestoreconData) { 6508 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6509 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6510 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6511 } 6512 } else { 6513 if (DEBUG_PACKAGE_SCANNING) { 6514 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6515 Log.v(TAG, "Want this data dir: " + dataPath); 6516 } 6517 //invoke installer to do the actual installation 6518 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6519 pkg.applicationInfo.seinfo); 6520 if (ret < 0) { 6521 // Error from installer 6522 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6523 "Unable to create data dirs [errorCode=" + ret + "]"); 6524 } 6525 6526 if (dataPath.exists()) { 6527 pkg.applicationInfo.dataDir = dataPath.getPath(); 6528 } else { 6529 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6530 pkg.applicationInfo.dataDir = null; 6531 } 6532 } 6533 6534 pkgSetting.uidError = uidError; 6535 } 6536 6537 final String path = scanFile.getPath(); 6538 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6539 6540 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6541 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6542 6543 // Some system apps still use directory structure for native libraries 6544 // in which case we might end up not detecting abi solely based on apk 6545 // structure. Try to detect abi based on directory structure. 6546 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6547 pkg.applicationInfo.primaryCpuAbi == null) { 6548 setBundledAppAbisAndRoots(pkg, pkgSetting); 6549 setNativeLibraryPaths(pkg); 6550 } 6551 6552 } else { 6553 if ((scanFlags & SCAN_MOVE) != 0) { 6554 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6555 // but we already have this packages package info in the PackageSetting. We just 6556 // use that and derive the native library path based on the new codepath. 6557 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6558 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6559 } 6560 6561 // Set native library paths again. For moves, the path will be updated based on the 6562 // ABIs we've determined above. For non-moves, the path will be updated based on the 6563 // ABIs we determined during compilation, but the path will depend on the final 6564 // package path (after the rename away from the stage path). 6565 setNativeLibraryPaths(pkg); 6566 } 6567 6568 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6569 final int[] userIds = sUserManager.getUserIds(); 6570 synchronized (mInstallLock) { 6571 // Create a native library symlink only if we have native libraries 6572 // and if the native libraries are 32 bit libraries. We do not provide 6573 // this symlink for 64 bit libraries. 6574 if (pkg.applicationInfo.primaryCpuAbi != null && 6575 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6576 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6577 for (int userId : userIds) { 6578 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6579 nativeLibPath, userId) < 0) { 6580 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6581 "Failed linking native library dir (user=" + userId + ")"); 6582 } 6583 } 6584 } 6585 } 6586 6587 // This is a special case for the "system" package, where the ABI is 6588 // dictated by the zygote configuration (and init.rc). We should keep track 6589 // of this ABI so that we can deal with "normal" applications that run under 6590 // the same UID correctly. 6591 if (mPlatformPackage == pkg) { 6592 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6593 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6594 } 6595 6596 // If there's a mismatch between the abi-override in the package setting 6597 // and the abiOverride specified for the install. Warn about this because we 6598 // would've already compiled the app without taking the package setting into 6599 // account. 6600 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6601 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6602 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6603 " for package: " + pkg.packageName); 6604 } 6605 } 6606 6607 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6608 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6609 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6610 6611 // Copy the derived override back to the parsed package, so that we can 6612 // update the package settings accordingly. 6613 pkg.cpuAbiOverride = cpuAbiOverride; 6614 6615 if (DEBUG_ABI_SELECTION) { 6616 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6617 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6618 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6619 } 6620 6621 // Push the derived path down into PackageSettings so we know what to 6622 // clean up at uninstall time. 6623 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6624 6625 if (DEBUG_ABI_SELECTION) { 6626 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6627 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6628 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6629 } 6630 6631 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6632 // We don't do this here during boot because we can do it all 6633 // at once after scanning all existing packages. 6634 // 6635 // We also do this *before* we perform dexopt on this package, so that 6636 // we can avoid redundant dexopts, and also to make sure we've got the 6637 // code and package path correct. 6638 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6639 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6640 } 6641 6642 if ((scanFlags & SCAN_NO_DEX) == 0) { 6643 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6644 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6645 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6646 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6647 } 6648 } 6649 if (mFactoryTest && pkg.requestedPermissions.contains( 6650 android.Manifest.permission.FACTORY_TEST)) { 6651 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6652 } 6653 6654 ArrayList<PackageParser.Package> clientLibPkgs = null; 6655 6656 // writer 6657 synchronized (mPackages) { 6658 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6659 // Only system apps can add new shared libraries. 6660 if (pkg.libraryNames != null) { 6661 for (int i=0; i<pkg.libraryNames.size(); i++) { 6662 String name = pkg.libraryNames.get(i); 6663 boolean allowed = false; 6664 if (pkg.isUpdatedSystemApp()) { 6665 // New library entries can only be added through the 6666 // system image. This is important to get rid of a lot 6667 // of nasty edge cases: for example if we allowed a non- 6668 // system update of the app to add a library, then uninstalling 6669 // the update would make the library go away, and assumptions 6670 // we made such as through app install filtering would now 6671 // have allowed apps on the device which aren't compatible 6672 // with it. Better to just have the restriction here, be 6673 // conservative, and create many fewer cases that can negatively 6674 // impact the user experience. 6675 final PackageSetting sysPs = mSettings 6676 .getDisabledSystemPkgLPr(pkg.packageName); 6677 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6678 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6679 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6680 allowed = true; 6681 allowed = true; 6682 break; 6683 } 6684 } 6685 } 6686 } else { 6687 allowed = true; 6688 } 6689 if (allowed) { 6690 if (!mSharedLibraries.containsKey(name)) { 6691 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6692 } else if (!name.equals(pkg.packageName)) { 6693 Slog.w(TAG, "Package " + pkg.packageName + " library " 6694 + name + " already exists; skipping"); 6695 } 6696 } else { 6697 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6698 + name + " that is not declared on system image; skipping"); 6699 } 6700 } 6701 if ((scanFlags&SCAN_BOOTING) == 0) { 6702 // If we are not booting, we need to update any applications 6703 // that are clients of our shared library. If we are booting, 6704 // this will all be done once the scan is complete. 6705 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6706 } 6707 } 6708 } 6709 } 6710 6711 // We also need to dexopt any apps that are dependent on this library. Note that 6712 // if these fail, we should abort the install since installing the library will 6713 // result in some apps being broken. 6714 if (clientLibPkgs != null) { 6715 if ((scanFlags & SCAN_NO_DEX) == 0) { 6716 for (int i = 0; i < clientLibPkgs.size(); i++) { 6717 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6718 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6719 null /* instruction sets */, forceDex, 6720 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6721 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6722 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6723 "scanPackageLI failed to dexopt clientLibPkgs"); 6724 } 6725 } 6726 } 6727 } 6728 6729 // Also need to kill any apps that are dependent on the library. 6730 if (clientLibPkgs != null) { 6731 for (int i=0; i<clientLibPkgs.size(); i++) { 6732 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6733 killApplication(clientPkg.applicationInfo.packageName, 6734 clientPkg.applicationInfo.uid, "update lib"); 6735 } 6736 } 6737 6738 // Make sure we're not adding any bogus keyset info 6739 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6740 ksms.assertScannedPackageValid(pkg); 6741 6742 // writer 6743 synchronized (mPackages) { 6744 // We don't expect installation to fail beyond this point 6745 6746 // Add the new setting to mSettings 6747 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6748 // Add the new setting to mPackages 6749 mPackages.put(pkg.applicationInfo.packageName, pkg); 6750 // Make sure we don't accidentally delete its data. 6751 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6752 while (iter.hasNext()) { 6753 PackageCleanItem item = iter.next(); 6754 if (pkgName.equals(item.packageName)) { 6755 iter.remove(); 6756 } 6757 } 6758 6759 // Take care of first install / last update times. 6760 if (currentTime != 0) { 6761 if (pkgSetting.firstInstallTime == 0) { 6762 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6763 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6764 pkgSetting.lastUpdateTime = currentTime; 6765 } 6766 } else if (pkgSetting.firstInstallTime == 0) { 6767 // We need *something*. Take time time stamp of the file. 6768 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6769 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6770 if (scanFileTime != pkgSetting.timeStamp) { 6771 // A package on the system image has changed; consider this 6772 // to be an update. 6773 pkgSetting.lastUpdateTime = scanFileTime; 6774 } 6775 } 6776 6777 // Add the package's KeySets to the global KeySetManagerService 6778 ksms.addScannedPackageLPw(pkg); 6779 6780 int N = pkg.providers.size(); 6781 StringBuilder r = null; 6782 int i; 6783 for (i=0; i<N; i++) { 6784 PackageParser.Provider p = pkg.providers.get(i); 6785 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6786 p.info.processName, pkg.applicationInfo.uid); 6787 mProviders.addProvider(p); 6788 p.syncable = p.info.isSyncable; 6789 if (p.info.authority != null) { 6790 String names[] = p.info.authority.split(";"); 6791 p.info.authority = null; 6792 for (int j = 0; j < names.length; j++) { 6793 if (j == 1 && p.syncable) { 6794 // We only want the first authority for a provider to possibly be 6795 // syncable, so if we already added this provider using a different 6796 // authority clear the syncable flag. We copy the provider before 6797 // changing it because the mProviders object contains a reference 6798 // to a provider that we don't want to change. 6799 // Only do this for the second authority since the resulting provider 6800 // object can be the same for all future authorities for this provider. 6801 p = new PackageParser.Provider(p); 6802 p.syncable = false; 6803 } 6804 if (!mProvidersByAuthority.containsKey(names[j])) { 6805 mProvidersByAuthority.put(names[j], p); 6806 if (p.info.authority == null) { 6807 p.info.authority = names[j]; 6808 } else { 6809 p.info.authority = p.info.authority + ";" + names[j]; 6810 } 6811 if (DEBUG_PACKAGE_SCANNING) { 6812 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6813 Log.d(TAG, "Registered content provider: " + names[j] 6814 + ", className = " + p.info.name + ", isSyncable = " 6815 + p.info.isSyncable); 6816 } 6817 } else { 6818 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6819 Slog.w(TAG, "Skipping provider name " + names[j] + 6820 " (in package " + pkg.applicationInfo.packageName + 6821 "): name already used by " 6822 + ((other != null && other.getComponentName() != null) 6823 ? other.getComponentName().getPackageName() : "?")); 6824 } 6825 } 6826 } 6827 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6828 if (r == null) { 6829 r = new StringBuilder(256); 6830 } else { 6831 r.append(' '); 6832 } 6833 r.append(p.info.name); 6834 } 6835 } 6836 if (r != null) { 6837 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6838 } 6839 6840 N = pkg.services.size(); 6841 r = null; 6842 for (i=0; i<N; i++) { 6843 PackageParser.Service s = pkg.services.get(i); 6844 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6845 s.info.processName, pkg.applicationInfo.uid); 6846 mServices.addService(s); 6847 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6848 if (r == null) { 6849 r = new StringBuilder(256); 6850 } else { 6851 r.append(' '); 6852 } 6853 r.append(s.info.name); 6854 } 6855 } 6856 if (r != null) { 6857 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6858 } 6859 6860 N = pkg.receivers.size(); 6861 r = null; 6862 for (i=0; i<N; i++) { 6863 PackageParser.Activity a = pkg.receivers.get(i); 6864 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6865 a.info.processName, pkg.applicationInfo.uid); 6866 mReceivers.addActivity(a, "receiver"); 6867 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6868 if (r == null) { 6869 r = new StringBuilder(256); 6870 } else { 6871 r.append(' '); 6872 } 6873 r.append(a.info.name); 6874 } 6875 } 6876 if (r != null) { 6877 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6878 } 6879 6880 N = pkg.activities.size(); 6881 r = null; 6882 for (i=0; i<N; i++) { 6883 PackageParser.Activity a = pkg.activities.get(i); 6884 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6885 a.info.processName, pkg.applicationInfo.uid); 6886 mActivities.addActivity(a, "activity"); 6887 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6888 if (r == null) { 6889 r = new StringBuilder(256); 6890 } else { 6891 r.append(' '); 6892 } 6893 r.append(a.info.name); 6894 } 6895 } 6896 if (r != null) { 6897 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6898 } 6899 6900 N = pkg.permissionGroups.size(); 6901 r = null; 6902 for (i=0; i<N; i++) { 6903 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6904 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6905 if (cur == null) { 6906 mPermissionGroups.put(pg.info.name, pg); 6907 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6908 if (r == null) { 6909 r = new StringBuilder(256); 6910 } else { 6911 r.append(' '); 6912 } 6913 r.append(pg.info.name); 6914 } 6915 } else { 6916 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6917 + pg.info.packageName + " ignored: original from " 6918 + cur.info.packageName); 6919 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6920 if (r == null) { 6921 r = new StringBuilder(256); 6922 } else { 6923 r.append(' '); 6924 } 6925 r.append("DUP:"); 6926 r.append(pg.info.name); 6927 } 6928 } 6929 } 6930 if (r != null) { 6931 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6932 } 6933 6934 N = pkg.permissions.size(); 6935 r = null; 6936 for (i=0; i<N; i++) { 6937 PackageParser.Permission p = pkg.permissions.get(i); 6938 6939 // Now that permission groups have a special meaning, we ignore permission 6940 // groups for legacy apps to prevent unexpected behavior. In particular, 6941 // permissions for one app being granted to someone just becuase they happen 6942 // to be in a group defined by another app (before this had no implications). 6943 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6944 p.group = mPermissionGroups.get(p.info.group); 6945 // Warn for a permission in an unknown group. 6946 if (p.info.group != null && p.group == null) { 6947 Slog.w(TAG, "Permission " + p.info.name + " from package " 6948 + p.info.packageName + " in an unknown group " + p.info.group); 6949 } 6950 } 6951 6952 ArrayMap<String, BasePermission> permissionMap = 6953 p.tree ? mSettings.mPermissionTrees 6954 : mSettings.mPermissions; 6955 BasePermission bp = permissionMap.get(p.info.name); 6956 6957 // Allow system apps to redefine non-system permissions 6958 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6959 final boolean currentOwnerIsSystem = (bp.perm != null 6960 && isSystemApp(bp.perm.owner)); 6961 if (isSystemApp(p.owner)) { 6962 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6963 // It's a built-in permission and no owner, take ownership now 6964 bp.packageSetting = pkgSetting; 6965 bp.perm = p; 6966 bp.uid = pkg.applicationInfo.uid; 6967 bp.sourcePackage = p.info.packageName; 6968 } else if (!currentOwnerIsSystem) { 6969 String msg = "New decl " + p.owner + " of permission " 6970 + p.info.name + " is system; overriding " + bp.sourcePackage; 6971 reportSettingsProblem(Log.WARN, msg); 6972 bp = null; 6973 } 6974 } 6975 } 6976 6977 if (bp == null) { 6978 bp = new BasePermission(p.info.name, p.info.packageName, 6979 BasePermission.TYPE_NORMAL); 6980 permissionMap.put(p.info.name, bp); 6981 } 6982 6983 if (bp.perm == null) { 6984 if (bp.sourcePackage == null 6985 || bp.sourcePackage.equals(p.info.packageName)) { 6986 BasePermission tree = findPermissionTreeLP(p.info.name); 6987 if (tree == null 6988 || tree.sourcePackage.equals(p.info.packageName)) { 6989 bp.packageSetting = pkgSetting; 6990 bp.perm = p; 6991 bp.uid = pkg.applicationInfo.uid; 6992 bp.sourcePackage = p.info.packageName; 6993 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6994 if (r == null) { 6995 r = new StringBuilder(256); 6996 } else { 6997 r.append(' '); 6998 } 6999 r.append(p.info.name); 7000 } 7001 } else { 7002 Slog.w(TAG, "Permission " + p.info.name + " from package " 7003 + p.info.packageName + " ignored: base tree " 7004 + tree.name + " is from package " 7005 + tree.sourcePackage); 7006 } 7007 } else { 7008 Slog.w(TAG, "Permission " + p.info.name + " from package " 7009 + p.info.packageName + " ignored: original from " 7010 + bp.sourcePackage); 7011 } 7012 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7013 if (r == null) { 7014 r = new StringBuilder(256); 7015 } else { 7016 r.append(' '); 7017 } 7018 r.append("DUP:"); 7019 r.append(p.info.name); 7020 } 7021 if (bp.perm == p) { 7022 bp.protectionLevel = p.info.protectionLevel; 7023 } 7024 } 7025 7026 if (r != null) { 7027 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 7028 } 7029 7030 N = pkg.instrumentation.size(); 7031 r = null; 7032 for (i=0; i<N; i++) { 7033 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7034 a.info.packageName = pkg.applicationInfo.packageName; 7035 a.info.sourceDir = pkg.applicationInfo.sourceDir; 7036 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 7037 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 7038 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 7039 a.info.dataDir = pkg.applicationInfo.dataDir; 7040 7041 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 7042 // need other information about the application, like the ABI and what not ? 7043 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 7044 mInstrumentation.put(a.getComponentName(), a); 7045 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 7046 if (r == null) { 7047 r = new StringBuilder(256); 7048 } else { 7049 r.append(' '); 7050 } 7051 r.append(a.info.name); 7052 } 7053 } 7054 if (r != null) { 7055 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 7056 } 7057 7058 if (pkg.protectedBroadcasts != null) { 7059 N = pkg.protectedBroadcasts.size(); 7060 for (i=0; i<N; i++) { 7061 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 7062 } 7063 } 7064 7065 pkgSetting.setTimeStamp(scanFileTime); 7066 7067 // Create idmap files for pairs of (packages, overlay packages). 7068 // Note: "android", ie framework-res.apk, is handled by native layers. 7069 if (pkg.mOverlayTarget != null) { 7070 // This is an overlay package. 7071 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 7072 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 7073 mOverlays.put(pkg.mOverlayTarget, 7074 new ArrayMap<String, PackageParser.Package>()); 7075 } 7076 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 7077 map.put(pkg.packageName, pkg); 7078 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 7079 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 7080 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7081 "scanPackageLI failed to createIdmap"); 7082 } 7083 } 7084 } else if (mOverlays.containsKey(pkg.packageName) && 7085 !pkg.packageName.equals("android")) { 7086 // This is a regular package, with one or more known overlay packages. 7087 createIdmapsForPackageLI(pkg); 7088 } 7089 } 7090 7091 return pkg; 7092 } 7093 7094 /** 7095 * Derive the ABI of a non-system package located at {@code scanFile}. This information 7096 * is derived purely on the basis of the contents of {@code scanFile} and 7097 * {@code cpuAbiOverride}. 7098 * 7099 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 7100 */ 7101 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 7102 String cpuAbiOverride, boolean extractLibs) 7103 throws PackageManagerException { 7104 // TODO: We can probably be smarter about this stuff. For installed apps, 7105 // we can calculate this information at install time once and for all. For 7106 // system apps, we can probably assume that this information doesn't change 7107 // after the first boot scan. As things stand, we do lots of unnecessary work. 7108 7109 // Give ourselves some initial paths; we'll come back for another 7110 // pass once we've determined ABI below. 7111 setNativeLibraryPaths(pkg); 7112 7113 // We would never need to extract libs for forward-locked and external packages, 7114 // since the container service will do it for us. We shouldn't attempt to 7115 // extract libs from system app when it was not updated. 7116 if (pkg.isForwardLocked() || isExternal(pkg) || 7117 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 7118 extractLibs = false; 7119 } 7120 7121 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 7122 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 7123 7124 NativeLibraryHelper.Handle handle = null; 7125 try { 7126 handle = NativeLibraryHelper.Handle.create(scanFile); 7127 // TODO(multiArch): This can be null for apps that didn't go through the 7128 // usual installation process. We can calculate it again, like we 7129 // do during install time. 7130 // 7131 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 7132 // unnecessary. 7133 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7134 7135 // Null out the abis so that they can be recalculated. 7136 pkg.applicationInfo.primaryCpuAbi = null; 7137 pkg.applicationInfo.secondaryCpuAbi = null; 7138 if (isMultiArch(pkg.applicationInfo)) { 7139 // Warn if we've set an abiOverride for multi-lib packages.. 7140 // By definition, we need to copy both 32 and 64 bit libraries for 7141 // such packages. 7142 if (pkg.cpuAbiOverride != null 7143 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7144 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7145 } 7146 7147 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7148 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7149 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7150 if (extractLibs) { 7151 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7152 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7153 useIsaSpecificSubdirs); 7154 } else { 7155 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7156 } 7157 } 7158 7159 maybeThrowExceptionForMultiArchCopy( 7160 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7161 7162 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7163 if (extractLibs) { 7164 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7165 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7166 useIsaSpecificSubdirs); 7167 } else { 7168 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7169 } 7170 } 7171 7172 maybeThrowExceptionForMultiArchCopy( 7173 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7174 7175 if (abi64 >= 0) { 7176 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7177 } 7178 7179 if (abi32 >= 0) { 7180 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7181 if (abi64 >= 0) { 7182 pkg.applicationInfo.secondaryCpuAbi = abi; 7183 } else { 7184 pkg.applicationInfo.primaryCpuAbi = abi; 7185 } 7186 } 7187 } else { 7188 String[] abiList = (cpuAbiOverride != null) ? 7189 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7190 7191 // Enable gross and lame hacks for apps that are built with old 7192 // SDK tools. We must scan their APKs for renderscript bitcode and 7193 // not launch them if it's present. Don't bother checking on devices 7194 // that don't have 64 bit support. 7195 boolean needsRenderScriptOverride = false; 7196 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7197 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7198 abiList = Build.SUPPORTED_32_BIT_ABIS; 7199 needsRenderScriptOverride = true; 7200 } 7201 7202 final int copyRet; 7203 if (extractLibs) { 7204 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7205 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7206 } else { 7207 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7208 } 7209 7210 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7211 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7212 "Error unpackaging native libs for app, errorCode=" + copyRet); 7213 } 7214 7215 if (copyRet >= 0) { 7216 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7217 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7218 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7219 } else if (needsRenderScriptOverride) { 7220 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7221 } 7222 } 7223 } catch (IOException ioe) { 7224 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7225 } finally { 7226 IoUtils.closeQuietly(handle); 7227 } 7228 7229 // Now that we've calculated the ABIs and determined if it's an internal app, 7230 // we will go ahead and populate the nativeLibraryPath. 7231 setNativeLibraryPaths(pkg); 7232 } 7233 7234 /** 7235 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7236 * i.e, so that all packages can be run inside a single process if required. 7237 * 7238 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7239 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7240 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7241 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7242 * updating a package that belongs to a shared user. 7243 * 7244 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7245 * adds unnecessary complexity. 7246 */ 7247 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7248 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7249 String requiredInstructionSet = null; 7250 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7251 requiredInstructionSet = VMRuntime.getInstructionSet( 7252 scannedPackage.applicationInfo.primaryCpuAbi); 7253 } 7254 7255 PackageSetting requirer = null; 7256 for (PackageSetting ps : packagesForUser) { 7257 // If packagesForUser contains scannedPackage, we skip it. This will happen 7258 // when scannedPackage is an update of an existing package. Without this check, 7259 // we will never be able to change the ABI of any package belonging to a shared 7260 // user, even if it's compatible with other packages. 7261 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7262 if (ps.primaryCpuAbiString == null) { 7263 continue; 7264 } 7265 7266 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7267 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7268 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7269 // this but there's not much we can do. 7270 String errorMessage = "Instruction set mismatch, " 7271 + ((requirer == null) ? "[caller]" : requirer) 7272 + " requires " + requiredInstructionSet + " whereas " + ps 7273 + " requires " + instructionSet; 7274 Slog.w(TAG, errorMessage); 7275 } 7276 7277 if (requiredInstructionSet == null) { 7278 requiredInstructionSet = instructionSet; 7279 requirer = ps; 7280 } 7281 } 7282 } 7283 7284 if (requiredInstructionSet != null) { 7285 String adjustedAbi; 7286 if (requirer != null) { 7287 // requirer != null implies that either scannedPackage was null or that scannedPackage 7288 // did not require an ABI, in which case we have to adjust scannedPackage to match 7289 // the ABI of the set (which is the same as requirer's ABI) 7290 adjustedAbi = requirer.primaryCpuAbiString; 7291 if (scannedPackage != null) { 7292 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7293 } 7294 } else { 7295 // requirer == null implies that we're updating all ABIs in the set to 7296 // match scannedPackage. 7297 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7298 } 7299 7300 for (PackageSetting ps : packagesForUser) { 7301 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7302 if (ps.primaryCpuAbiString != null) { 7303 continue; 7304 } 7305 7306 ps.primaryCpuAbiString = adjustedAbi; 7307 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7308 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7309 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7310 7311 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7312 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7313 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7314 ps.primaryCpuAbiString = null; 7315 ps.pkg.applicationInfo.primaryCpuAbi = null; 7316 return; 7317 } else { 7318 mInstaller.rmdex(ps.codePathString, 7319 getDexCodeInstructionSet(getPreferredInstructionSet())); 7320 } 7321 } 7322 } 7323 } 7324 } 7325 } 7326 7327 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7328 synchronized (mPackages) { 7329 mResolverReplaced = true; 7330 // Set up information for custom user intent resolution activity. 7331 mResolveActivity.applicationInfo = pkg.applicationInfo; 7332 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7333 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7334 mResolveActivity.processName = pkg.applicationInfo.packageName; 7335 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7336 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7337 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7338 mResolveActivity.theme = 0; 7339 mResolveActivity.exported = true; 7340 mResolveActivity.enabled = true; 7341 mResolveInfo.activityInfo = mResolveActivity; 7342 mResolveInfo.priority = 0; 7343 mResolveInfo.preferredOrder = 0; 7344 mResolveInfo.match = 0; 7345 mResolveComponentName = mCustomResolverComponentName; 7346 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7347 mResolveComponentName); 7348 } 7349 } 7350 7351 private static String calculateBundledApkRoot(final String codePathString) { 7352 final File codePath = new File(codePathString); 7353 final File codeRoot; 7354 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7355 codeRoot = Environment.getRootDirectory(); 7356 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7357 codeRoot = Environment.getOemDirectory(); 7358 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7359 codeRoot = Environment.getVendorDirectory(); 7360 } else { 7361 // Unrecognized code path; take its top real segment as the apk root: 7362 // e.g. /something/app/blah.apk => /something 7363 try { 7364 File f = codePath.getCanonicalFile(); 7365 File parent = f.getParentFile(); // non-null because codePath is a file 7366 File tmp; 7367 while ((tmp = parent.getParentFile()) != null) { 7368 f = parent; 7369 parent = tmp; 7370 } 7371 codeRoot = f; 7372 Slog.w(TAG, "Unrecognized code path " 7373 + codePath + " - using " + codeRoot); 7374 } catch (IOException e) { 7375 // Can't canonicalize the code path -- shenanigans? 7376 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7377 return Environment.getRootDirectory().getPath(); 7378 } 7379 } 7380 return codeRoot.getPath(); 7381 } 7382 7383 /** 7384 * Derive and set the location of native libraries for the given package, 7385 * which varies depending on where and how the package was installed. 7386 */ 7387 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7388 final ApplicationInfo info = pkg.applicationInfo; 7389 final String codePath = pkg.codePath; 7390 final File codeFile = new File(codePath); 7391 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7392 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7393 7394 info.nativeLibraryRootDir = null; 7395 info.nativeLibraryRootRequiresIsa = false; 7396 info.nativeLibraryDir = null; 7397 info.secondaryNativeLibraryDir = null; 7398 7399 if (isApkFile(codeFile)) { 7400 // Monolithic install 7401 if (bundledApp) { 7402 // If "/system/lib64/apkname" exists, assume that is the per-package 7403 // native library directory to use; otherwise use "/system/lib/apkname". 7404 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7405 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7406 getPrimaryInstructionSet(info)); 7407 7408 // This is a bundled system app so choose the path based on the ABI. 7409 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7410 // is just the default path. 7411 final String apkName = deriveCodePathName(codePath); 7412 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7413 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7414 apkName).getAbsolutePath(); 7415 7416 if (info.secondaryCpuAbi != null) { 7417 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7418 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7419 secondaryLibDir, apkName).getAbsolutePath(); 7420 } 7421 } else if (asecApp) { 7422 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7423 .getAbsolutePath(); 7424 } else { 7425 final String apkName = deriveCodePathName(codePath); 7426 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7427 .getAbsolutePath(); 7428 } 7429 7430 info.nativeLibraryRootRequiresIsa = false; 7431 info.nativeLibraryDir = info.nativeLibraryRootDir; 7432 } else { 7433 // Cluster install 7434 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7435 info.nativeLibraryRootRequiresIsa = true; 7436 7437 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7438 getPrimaryInstructionSet(info)).getAbsolutePath(); 7439 7440 if (info.secondaryCpuAbi != null) { 7441 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7442 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7443 } 7444 } 7445 } 7446 7447 /** 7448 * Calculate the abis and roots for a bundled app. These can uniquely 7449 * be determined from the contents of the system partition, i.e whether 7450 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7451 * of this information, and instead assume that the system was built 7452 * sensibly. 7453 */ 7454 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7455 PackageSetting pkgSetting) { 7456 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7457 7458 // If "/system/lib64/apkname" exists, assume that is the per-package 7459 // native library directory to use; otherwise use "/system/lib/apkname". 7460 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7461 setBundledAppAbi(pkg, apkRoot, apkName); 7462 // pkgSetting might be null during rescan following uninstall of updates 7463 // to a bundled app, so accommodate that possibility. The settings in 7464 // that case will be established later from the parsed package. 7465 // 7466 // If the settings aren't null, sync them up with what we've just derived. 7467 // note that apkRoot isn't stored in the package settings. 7468 if (pkgSetting != null) { 7469 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7470 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7471 } 7472 } 7473 7474 /** 7475 * Deduces the ABI of a bundled app and sets the relevant fields on the 7476 * parsed pkg object. 7477 * 7478 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7479 * under which system libraries are installed. 7480 * @param apkName the name of the installed package. 7481 */ 7482 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7483 final File codeFile = new File(pkg.codePath); 7484 7485 final boolean has64BitLibs; 7486 final boolean has32BitLibs; 7487 if (isApkFile(codeFile)) { 7488 // Monolithic install 7489 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7490 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7491 } else { 7492 // Cluster install 7493 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7494 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7495 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7496 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7497 has64BitLibs = (new File(rootDir, isa)).exists(); 7498 } else { 7499 has64BitLibs = false; 7500 } 7501 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7502 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7503 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7504 has32BitLibs = (new File(rootDir, isa)).exists(); 7505 } else { 7506 has32BitLibs = false; 7507 } 7508 } 7509 7510 if (has64BitLibs && !has32BitLibs) { 7511 // The package has 64 bit libs, but not 32 bit libs. Its primary 7512 // ABI should be 64 bit. We can safely assume here that the bundled 7513 // native libraries correspond to the most preferred ABI in the list. 7514 7515 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7516 pkg.applicationInfo.secondaryCpuAbi = null; 7517 } else if (has32BitLibs && !has64BitLibs) { 7518 // The package has 32 bit libs but not 64 bit libs. Its primary 7519 // ABI should be 32 bit. 7520 7521 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7522 pkg.applicationInfo.secondaryCpuAbi = null; 7523 } else if (has32BitLibs && has64BitLibs) { 7524 // The application has both 64 and 32 bit bundled libraries. We check 7525 // here that the app declares multiArch support, and warn if it doesn't. 7526 // 7527 // We will be lenient here and record both ABIs. The primary will be the 7528 // ABI that's higher on the list, i.e, a device that's configured to prefer 7529 // 64 bit apps will see a 64 bit primary ABI, 7530 7531 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7532 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7533 } 7534 7535 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7536 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7537 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7538 } else { 7539 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7540 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7541 } 7542 } else { 7543 pkg.applicationInfo.primaryCpuAbi = null; 7544 pkg.applicationInfo.secondaryCpuAbi = null; 7545 } 7546 } 7547 7548 private void killApplication(String pkgName, int appId, String reason) { 7549 // Request the ActivityManager to kill the process(only for existing packages) 7550 // so that we do not end up in a confused state while the user is still using the older 7551 // version of the application while the new one gets installed. 7552 IActivityManager am = ActivityManagerNative.getDefault(); 7553 if (am != null) { 7554 try { 7555 am.killApplicationWithAppId(pkgName, appId, reason); 7556 } catch (RemoteException e) { 7557 } 7558 } 7559 } 7560 7561 void removePackageLI(PackageSetting ps, boolean chatty) { 7562 if (DEBUG_INSTALL) { 7563 if (chatty) 7564 Log.d(TAG, "Removing package " + ps.name); 7565 } 7566 7567 // writer 7568 synchronized (mPackages) { 7569 mPackages.remove(ps.name); 7570 final PackageParser.Package pkg = ps.pkg; 7571 if (pkg != null) { 7572 cleanPackageDataStructuresLILPw(pkg, chatty); 7573 } 7574 } 7575 } 7576 7577 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7578 if (DEBUG_INSTALL) { 7579 if (chatty) 7580 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7581 } 7582 7583 // writer 7584 synchronized (mPackages) { 7585 mPackages.remove(pkg.applicationInfo.packageName); 7586 cleanPackageDataStructuresLILPw(pkg, chatty); 7587 } 7588 } 7589 7590 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7591 int N = pkg.providers.size(); 7592 StringBuilder r = null; 7593 int i; 7594 for (i=0; i<N; i++) { 7595 PackageParser.Provider p = pkg.providers.get(i); 7596 mProviders.removeProvider(p); 7597 if (p.info.authority == null) { 7598 7599 /* There was another ContentProvider with this authority when 7600 * this app was installed so this authority is null, 7601 * Ignore it as we don't have to unregister the provider. 7602 */ 7603 continue; 7604 } 7605 String names[] = p.info.authority.split(";"); 7606 for (int j = 0; j < names.length; j++) { 7607 if (mProvidersByAuthority.get(names[j]) == p) { 7608 mProvidersByAuthority.remove(names[j]); 7609 if (DEBUG_REMOVE) { 7610 if (chatty) 7611 Log.d(TAG, "Unregistered content provider: " + names[j] 7612 + ", className = " + p.info.name + ", isSyncable = " 7613 + p.info.isSyncable); 7614 } 7615 } 7616 } 7617 if (DEBUG_REMOVE && chatty) { 7618 if (r == null) { 7619 r = new StringBuilder(256); 7620 } else { 7621 r.append(' '); 7622 } 7623 r.append(p.info.name); 7624 } 7625 } 7626 if (r != null) { 7627 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7628 } 7629 7630 N = pkg.services.size(); 7631 r = null; 7632 for (i=0; i<N; i++) { 7633 PackageParser.Service s = pkg.services.get(i); 7634 mServices.removeService(s); 7635 if (chatty) { 7636 if (r == null) { 7637 r = new StringBuilder(256); 7638 } else { 7639 r.append(' '); 7640 } 7641 r.append(s.info.name); 7642 } 7643 } 7644 if (r != null) { 7645 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7646 } 7647 7648 N = pkg.receivers.size(); 7649 r = null; 7650 for (i=0; i<N; i++) { 7651 PackageParser.Activity a = pkg.receivers.get(i); 7652 mReceivers.removeActivity(a, "receiver"); 7653 if (DEBUG_REMOVE && chatty) { 7654 if (r == null) { 7655 r = new StringBuilder(256); 7656 } else { 7657 r.append(' '); 7658 } 7659 r.append(a.info.name); 7660 } 7661 } 7662 if (r != null) { 7663 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7664 } 7665 7666 N = pkg.activities.size(); 7667 r = null; 7668 for (i=0; i<N; i++) { 7669 PackageParser.Activity a = pkg.activities.get(i); 7670 mActivities.removeActivity(a, "activity"); 7671 if (DEBUG_REMOVE && chatty) { 7672 if (r == null) { 7673 r = new StringBuilder(256); 7674 } else { 7675 r.append(' '); 7676 } 7677 r.append(a.info.name); 7678 } 7679 } 7680 if (r != null) { 7681 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7682 } 7683 7684 N = pkg.permissions.size(); 7685 r = null; 7686 for (i=0; i<N; i++) { 7687 PackageParser.Permission p = pkg.permissions.get(i); 7688 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7689 if (bp == null) { 7690 bp = mSettings.mPermissionTrees.get(p.info.name); 7691 } 7692 if (bp != null && bp.perm == p) { 7693 bp.perm = null; 7694 if (DEBUG_REMOVE && chatty) { 7695 if (r == null) { 7696 r = new StringBuilder(256); 7697 } else { 7698 r.append(' '); 7699 } 7700 r.append(p.info.name); 7701 } 7702 } 7703 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7704 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7705 if (appOpPerms != null) { 7706 appOpPerms.remove(pkg.packageName); 7707 } 7708 } 7709 } 7710 if (r != null) { 7711 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7712 } 7713 7714 N = pkg.requestedPermissions.size(); 7715 r = null; 7716 for (i=0; i<N; i++) { 7717 String perm = pkg.requestedPermissions.get(i); 7718 BasePermission bp = mSettings.mPermissions.get(perm); 7719 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7720 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7721 if (appOpPerms != null) { 7722 appOpPerms.remove(pkg.packageName); 7723 if (appOpPerms.isEmpty()) { 7724 mAppOpPermissionPackages.remove(perm); 7725 } 7726 } 7727 } 7728 } 7729 if (r != null) { 7730 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7731 } 7732 7733 N = pkg.instrumentation.size(); 7734 r = null; 7735 for (i=0; i<N; i++) { 7736 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7737 mInstrumentation.remove(a.getComponentName()); 7738 if (DEBUG_REMOVE && chatty) { 7739 if (r == null) { 7740 r = new StringBuilder(256); 7741 } else { 7742 r.append(' '); 7743 } 7744 r.append(a.info.name); 7745 } 7746 } 7747 if (r != null) { 7748 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7749 } 7750 7751 r = null; 7752 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7753 // Only system apps can hold shared libraries. 7754 if (pkg.libraryNames != null) { 7755 for (i=0; i<pkg.libraryNames.size(); i++) { 7756 String name = pkg.libraryNames.get(i); 7757 SharedLibraryEntry cur = mSharedLibraries.get(name); 7758 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7759 mSharedLibraries.remove(name); 7760 if (DEBUG_REMOVE && chatty) { 7761 if (r == null) { 7762 r = new StringBuilder(256); 7763 } else { 7764 r.append(' '); 7765 } 7766 r.append(name); 7767 } 7768 } 7769 } 7770 } 7771 } 7772 if (r != null) { 7773 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7774 } 7775 } 7776 7777 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7778 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7779 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7780 return true; 7781 } 7782 } 7783 return false; 7784 } 7785 7786 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7787 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7788 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7789 7790 private void updatePermissionsLPw(String changingPkg, 7791 PackageParser.Package pkgInfo, int flags) { 7792 // Make sure there are no dangling permission trees. 7793 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7794 while (it.hasNext()) { 7795 final BasePermission bp = it.next(); 7796 if (bp.packageSetting == null) { 7797 // We may not yet have parsed the package, so just see if 7798 // we still know about its settings. 7799 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7800 } 7801 if (bp.packageSetting == null) { 7802 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7803 + " from package " + bp.sourcePackage); 7804 it.remove(); 7805 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7806 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7807 Slog.i(TAG, "Removing old permission tree: " + bp.name 7808 + " from package " + bp.sourcePackage); 7809 flags |= UPDATE_PERMISSIONS_ALL; 7810 it.remove(); 7811 } 7812 } 7813 } 7814 7815 // Make sure all dynamic permissions have been assigned to a package, 7816 // and make sure there are no dangling permissions. 7817 it = mSettings.mPermissions.values().iterator(); 7818 while (it.hasNext()) { 7819 final BasePermission bp = it.next(); 7820 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7821 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7822 + bp.name + " pkg=" + bp.sourcePackage 7823 + " info=" + bp.pendingInfo); 7824 if (bp.packageSetting == null && bp.pendingInfo != null) { 7825 final BasePermission tree = findPermissionTreeLP(bp.name); 7826 if (tree != null && tree.perm != null) { 7827 bp.packageSetting = tree.packageSetting; 7828 bp.perm = new PackageParser.Permission(tree.perm.owner, 7829 new PermissionInfo(bp.pendingInfo)); 7830 bp.perm.info.packageName = tree.perm.info.packageName; 7831 bp.perm.info.name = bp.name; 7832 bp.uid = tree.uid; 7833 } 7834 } 7835 } 7836 if (bp.packageSetting == null) { 7837 // We may not yet have parsed the package, so just see if 7838 // we still know about its settings. 7839 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7840 } 7841 if (bp.packageSetting == null) { 7842 Slog.w(TAG, "Removing dangling permission: " + bp.name 7843 + " from package " + bp.sourcePackage); 7844 it.remove(); 7845 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7846 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7847 Slog.i(TAG, "Removing old permission: " + bp.name 7848 + " from package " + bp.sourcePackage); 7849 flags |= UPDATE_PERMISSIONS_ALL; 7850 it.remove(); 7851 } 7852 } 7853 } 7854 7855 // Now update the permissions for all packages, in particular 7856 // replace the granted permissions of the system packages. 7857 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7858 for (PackageParser.Package pkg : mPackages.values()) { 7859 if (pkg != pkgInfo) { 7860 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7861 changingPkg); 7862 } 7863 } 7864 } 7865 7866 if (pkgInfo != null) { 7867 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7868 } 7869 } 7870 7871 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7872 String packageOfInterest) { 7873 // IMPORTANT: There are two types of permissions: install and runtime. 7874 // Install time permissions are granted when the app is installed to 7875 // all device users and users added in the future. Runtime permissions 7876 // are granted at runtime explicitly to specific users. Normal and signature 7877 // protected permissions are install time permissions. Dangerous permissions 7878 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7879 // otherwise they are runtime permissions. This function does not manage 7880 // runtime permissions except for the case an app targeting Lollipop MR1 7881 // being upgraded to target a newer SDK, in which case dangerous permissions 7882 // are transformed from install time to runtime ones. 7883 7884 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7885 if (ps == null) { 7886 return; 7887 } 7888 7889 PermissionsState permissionsState = ps.getPermissionsState(); 7890 PermissionsState origPermissions = permissionsState; 7891 7892 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7893 7894 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7895 7896 boolean changedInstallPermission = false; 7897 7898 if (replace) { 7899 ps.installPermissionsFixed = false; 7900 if (!ps.isSharedUser()) { 7901 origPermissions = new PermissionsState(permissionsState); 7902 permissionsState.reset(); 7903 } 7904 } 7905 7906 permissionsState.setGlobalGids(mGlobalGids); 7907 7908 final int N = pkg.requestedPermissions.size(); 7909 for (int i=0; i<N; i++) { 7910 final String name = pkg.requestedPermissions.get(i); 7911 final BasePermission bp = mSettings.mPermissions.get(name); 7912 7913 if (DEBUG_INSTALL) { 7914 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7915 } 7916 7917 if (bp == null || bp.packageSetting == null) { 7918 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7919 Slog.w(TAG, "Unknown permission " + name 7920 + " in package " + pkg.packageName); 7921 } 7922 continue; 7923 } 7924 7925 final String perm = bp.name; 7926 boolean allowedSig = false; 7927 int grant = GRANT_DENIED; 7928 7929 // Keep track of app op permissions. 7930 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7931 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7932 if (pkgs == null) { 7933 pkgs = new ArraySet<>(); 7934 mAppOpPermissionPackages.put(bp.name, pkgs); 7935 } 7936 pkgs.add(pkg.packageName); 7937 } 7938 7939 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7940 switch (level) { 7941 case PermissionInfo.PROTECTION_NORMAL: { 7942 // For all apps normal permissions are install time ones. 7943 grant = GRANT_INSTALL; 7944 } break; 7945 7946 case PermissionInfo.PROTECTION_DANGEROUS: { 7947 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7948 // For legacy apps dangerous permissions are install time ones. 7949 grant = GRANT_INSTALL_LEGACY; 7950 } else if (origPermissions.hasInstallPermission(bp.name)) { 7951 // For legacy apps that became modern, install becomes runtime. 7952 grant = GRANT_UPGRADE; 7953 } else { 7954 // For modern apps keep runtime permissions unchanged. 7955 grant = GRANT_RUNTIME; 7956 } 7957 } break; 7958 7959 case PermissionInfo.PROTECTION_SIGNATURE: { 7960 // For all apps signature permissions are install time ones. 7961 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7962 if (allowedSig) { 7963 grant = GRANT_INSTALL; 7964 } 7965 } break; 7966 } 7967 7968 if (DEBUG_INSTALL) { 7969 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7970 } 7971 7972 if (grant != GRANT_DENIED) { 7973 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7974 // If this is an existing, non-system package, then 7975 // we can't add any new permissions to it. 7976 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7977 // Except... if this is a permission that was added 7978 // to the platform (note: need to only do this when 7979 // updating the platform). 7980 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7981 grant = GRANT_DENIED; 7982 } 7983 } 7984 } 7985 7986 switch (grant) { 7987 case GRANT_INSTALL: { 7988 // Revoke this as runtime permission to handle the case of 7989 // a runtime permission being downgraded to an install one. 7990 for (int userId : UserManagerService.getInstance().getUserIds()) { 7991 if (origPermissions.getRuntimePermissionState( 7992 bp.name, userId) != null) { 7993 // Revoke the runtime permission and clear the flags. 7994 origPermissions.revokeRuntimePermission(bp, userId); 7995 origPermissions.updatePermissionFlags(bp, userId, 7996 PackageManager.MASK_PERMISSION_FLAGS, 0); 7997 // If we revoked a permission permission, we have to write. 7998 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7999 changedRuntimePermissionUserIds, userId); 8000 } 8001 } 8002 // Grant an install permission. 8003 if (permissionsState.grantInstallPermission(bp) != 8004 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8005 changedInstallPermission = true; 8006 } 8007 } break; 8008 8009 case GRANT_INSTALL_LEGACY: { 8010 // Grant an install permission. 8011 if (permissionsState.grantInstallPermission(bp) != 8012 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8013 changedInstallPermission = true; 8014 } 8015 } break; 8016 8017 case GRANT_RUNTIME: { 8018 // Grant previously granted runtime permissions. 8019 for (int userId : UserManagerService.getInstance().getUserIds()) { 8020 PermissionState permissionState = origPermissions 8021 .getRuntimePermissionState(bp.name, userId); 8022 final int flags = permissionState != null 8023 ? permissionState.getFlags() : 0; 8024 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 8025 if (permissionsState.grantRuntimePermission(bp, userId) == 8026 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8027 // If we cannot put the permission as it was, we have to write. 8028 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8029 changedRuntimePermissionUserIds, userId); 8030 } 8031 } 8032 // Propagate the permission flags. 8033 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 8034 } 8035 } break; 8036 8037 case GRANT_UPGRADE: { 8038 // Grant runtime permissions for a previously held install permission. 8039 PermissionState permissionState = origPermissions 8040 .getInstallPermissionState(bp.name); 8041 final int flags = permissionState != null ? permissionState.getFlags() : 0; 8042 8043 if (origPermissions.revokeInstallPermission(bp) 8044 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 8045 // We will be transferring the permission flags, so clear them. 8046 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 8047 PackageManager.MASK_PERMISSION_FLAGS, 0); 8048 changedInstallPermission = true; 8049 } 8050 8051 // If the permission is not to be promoted to runtime we ignore it and 8052 // also its other flags as they are not applicable to install permissions. 8053 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 8054 for (int userId : currentUserIds) { 8055 if (permissionsState.grantRuntimePermission(bp, userId) != 8056 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8057 // Transfer the permission flags. 8058 permissionsState.updatePermissionFlags(bp, userId, 8059 flags, flags); 8060 // If we granted the permission, we have to write. 8061 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 8062 changedRuntimePermissionUserIds, userId); 8063 } 8064 } 8065 } 8066 } break; 8067 8068 default: { 8069 if (packageOfInterest == null 8070 || packageOfInterest.equals(pkg.packageName)) { 8071 Slog.w(TAG, "Not granting permission " + perm 8072 + " to package " + pkg.packageName 8073 + " because it was previously installed without"); 8074 } 8075 } break; 8076 } 8077 } else { 8078 if (permissionsState.revokeInstallPermission(bp) != 8079 PermissionsState.PERMISSION_OPERATION_FAILURE) { 8080 // Also drop the permission flags. 8081 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 8082 PackageManager.MASK_PERMISSION_FLAGS, 0); 8083 changedInstallPermission = true; 8084 Slog.i(TAG, "Un-granting permission " + perm 8085 + " from package " + pkg.packageName 8086 + " (protectionLevel=" + bp.protectionLevel 8087 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8088 + ")"); 8089 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 8090 // Don't print warning for app op permissions, since it is fine for them 8091 // not to be granted, there is a UI for the user to decide. 8092 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 8093 Slog.w(TAG, "Not granting permission " + perm 8094 + " to package " + pkg.packageName 8095 + " (protectionLevel=" + bp.protectionLevel 8096 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 8097 + ")"); 8098 } 8099 } 8100 } 8101 } 8102 8103 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8104 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8105 // This is the first that we have heard about this package, so the 8106 // permissions we have now selected are fixed until explicitly 8107 // changed. 8108 ps.installPermissionsFixed = true; 8109 } 8110 8111 // Persist the runtime permissions state for users with changes. 8112 for (int userId : changedRuntimePermissionUserIds) { 8113 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 8114 } 8115 } 8116 8117 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8118 boolean allowed = false; 8119 final int NP = PackageParser.NEW_PERMISSIONS.length; 8120 for (int ip=0; ip<NP; ip++) { 8121 final PackageParser.NewPermissionInfo npi 8122 = PackageParser.NEW_PERMISSIONS[ip]; 8123 if (npi.name.equals(perm) 8124 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8125 allowed = true; 8126 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8127 + pkg.packageName); 8128 break; 8129 } 8130 } 8131 return allowed; 8132 } 8133 8134 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8135 BasePermission bp, PermissionsState origPermissions) { 8136 boolean allowed; 8137 allowed = (compareSignatures( 8138 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8139 == PackageManager.SIGNATURE_MATCH) 8140 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8141 == PackageManager.SIGNATURE_MATCH); 8142 if (!allowed && (bp.protectionLevel 8143 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8144 if (isSystemApp(pkg)) { 8145 // For updated system applications, a system permission 8146 // is granted only if it had been defined by the original application. 8147 if (pkg.isUpdatedSystemApp()) { 8148 final PackageSetting sysPs = mSettings 8149 .getDisabledSystemPkgLPr(pkg.packageName); 8150 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8151 // If the original was granted this permission, we take 8152 // that grant decision as read and propagate it to the 8153 // update. 8154 if (sysPs.isPrivileged()) { 8155 allowed = true; 8156 } 8157 } else { 8158 // The system apk may have been updated with an older 8159 // version of the one on the data partition, but which 8160 // granted a new system permission that it didn't have 8161 // before. In this case we do want to allow the app to 8162 // now get the new permission if the ancestral apk is 8163 // privileged to get it. 8164 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8165 for (int j=0; 8166 j<sysPs.pkg.requestedPermissions.size(); j++) { 8167 if (perm.equals( 8168 sysPs.pkg.requestedPermissions.get(j))) { 8169 allowed = true; 8170 break; 8171 } 8172 } 8173 } 8174 } 8175 } else { 8176 allowed = isPrivilegedApp(pkg); 8177 } 8178 } 8179 } 8180 if (!allowed && (bp.protectionLevel 8181 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8182 // For development permissions, a development permission 8183 // is granted only if it was already granted. 8184 allowed = origPermissions.hasInstallPermission(perm); 8185 } 8186 return allowed; 8187 } 8188 8189 final class ActivityIntentResolver 8190 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8191 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8192 boolean defaultOnly, int userId) { 8193 if (!sUserManager.exists(userId)) return null; 8194 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8195 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8196 } 8197 8198 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8199 int userId) { 8200 if (!sUserManager.exists(userId)) return null; 8201 mFlags = flags; 8202 return super.queryIntent(intent, resolvedType, 8203 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8204 } 8205 8206 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8207 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8208 if (!sUserManager.exists(userId)) return null; 8209 if (packageActivities == null) { 8210 return null; 8211 } 8212 mFlags = flags; 8213 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8214 final int N = packageActivities.size(); 8215 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8216 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8217 8218 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8219 for (int i = 0; i < N; ++i) { 8220 intentFilters = packageActivities.get(i).intents; 8221 if (intentFilters != null && intentFilters.size() > 0) { 8222 PackageParser.ActivityIntentInfo[] array = 8223 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8224 intentFilters.toArray(array); 8225 listCut.add(array); 8226 } 8227 } 8228 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8229 } 8230 8231 public final void addActivity(PackageParser.Activity a, String type) { 8232 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8233 mActivities.put(a.getComponentName(), a); 8234 if (DEBUG_SHOW_INFO) 8235 Log.v( 8236 TAG, " " + type + " " + 8237 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8238 if (DEBUG_SHOW_INFO) 8239 Log.v(TAG, " Class=" + a.info.name); 8240 final int NI = a.intents.size(); 8241 for (int j=0; j<NI; j++) { 8242 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8243 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8244 intent.setPriority(0); 8245 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8246 + a.className + " with priority > 0, forcing to 0"); 8247 } 8248 if (DEBUG_SHOW_INFO) { 8249 Log.v(TAG, " IntentFilter:"); 8250 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8251 } 8252 if (!intent.debugCheck()) { 8253 Log.w(TAG, "==> For Activity " + a.info.name); 8254 } 8255 addFilter(intent); 8256 } 8257 } 8258 8259 public final void removeActivity(PackageParser.Activity a, String type) { 8260 mActivities.remove(a.getComponentName()); 8261 if (DEBUG_SHOW_INFO) { 8262 Log.v(TAG, " " + type + " " 8263 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8264 : a.info.name) + ":"); 8265 Log.v(TAG, " Class=" + a.info.name); 8266 } 8267 final int NI = a.intents.size(); 8268 for (int j=0; j<NI; j++) { 8269 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8270 if (DEBUG_SHOW_INFO) { 8271 Log.v(TAG, " IntentFilter:"); 8272 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8273 } 8274 removeFilter(intent); 8275 } 8276 } 8277 8278 @Override 8279 protected boolean allowFilterResult( 8280 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8281 ActivityInfo filterAi = filter.activity.info; 8282 for (int i=dest.size()-1; i>=0; i--) { 8283 ActivityInfo destAi = dest.get(i).activityInfo; 8284 if (destAi.name == filterAi.name 8285 && destAi.packageName == filterAi.packageName) { 8286 return false; 8287 } 8288 } 8289 return true; 8290 } 8291 8292 @Override 8293 protected ActivityIntentInfo[] newArray(int size) { 8294 return new ActivityIntentInfo[size]; 8295 } 8296 8297 @Override 8298 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8299 if (!sUserManager.exists(userId)) return true; 8300 PackageParser.Package p = filter.activity.owner; 8301 if (p != null) { 8302 PackageSetting ps = (PackageSetting)p.mExtras; 8303 if (ps != null) { 8304 // System apps are never considered stopped for purposes of 8305 // filtering, because there may be no way for the user to 8306 // actually re-launch them. 8307 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8308 && ps.getStopped(userId); 8309 } 8310 } 8311 return false; 8312 } 8313 8314 @Override 8315 protected boolean isPackageForFilter(String packageName, 8316 PackageParser.ActivityIntentInfo info) { 8317 return packageName.equals(info.activity.owner.packageName); 8318 } 8319 8320 @Override 8321 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8322 int match, int userId) { 8323 if (!sUserManager.exists(userId)) return null; 8324 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8325 return null; 8326 } 8327 final PackageParser.Activity activity = info.activity; 8328 if (mSafeMode && (activity.info.applicationInfo.flags 8329 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8330 return null; 8331 } 8332 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8333 if (ps == null) { 8334 return null; 8335 } 8336 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8337 ps.readUserState(userId), userId); 8338 if (ai == null) { 8339 return null; 8340 } 8341 final ResolveInfo res = new ResolveInfo(); 8342 res.activityInfo = ai; 8343 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8344 res.filter = info; 8345 } 8346 if (info != null) { 8347 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8348 } 8349 res.priority = info.getPriority(); 8350 res.preferredOrder = activity.owner.mPreferredOrder; 8351 //System.out.println("Result: " + res.activityInfo.className + 8352 // " = " + res.priority); 8353 res.match = match; 8354 res.isDefault = info.hasDefault; 8355 res.labelRes = info.labelRes; 8356 res.nonLocalizedLabel = info.nonLocalizedLabel; 8357 if (userNeedsBadging(userId)) { 8358 res.noResourceId = true; 8359 } else { 8360 res.icon = info.icon; 8361 } 8362 res.iconResourceId = info.icon; 8363 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8364 return res; 8365 } 8366 8367 @Override 8368 protected void sortResults(List<ResolveInfo> results) { 8369 Collections.sort(results, mResolvePrioritySorter); 8370 } 8371 8372 @Override 8373 protected void dumpFilter(PrintWriter out, String prefix, 8374 PackageParser.ActivityIntentInfo filter) { 8375 out.print(prefix); out.print( 8376 Integer.toHexString(System.identityHashCode(filter.activity))); 8377 out.print(' '); 8378 filter.activity.printComponentShortName(out); 8379 out.print(" filter "); 8380 out.println(Integer.toHexString(System.identityHashCode(filter))); 8381 } 8382 8383 @Override 8384 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8385 return filter.activity; 8386 } 8387 8388 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8389 PackageParser.Activity activity = (PackageParser.Activity)label; 8390 out.print(prefix); out.print( 8391 Integer.toHexString(System.identityHashCode(activity))); 8392 out.print(' '); 8393 activity.printComponentShortName(out); 8394 if (count > 1) { 8395 out.print(" ("); out.print(count); out.print(" filters)"); 8396 } 8397 out.println(); 8398 } 8399 8400// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8401// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8402// final List<ResolveInfo> retList = Lists.newArrayList(); 8403// while (i.hasNext()) { 8404// final ResolveInfo resolveInfo = i.next(); 8405// if (isEnabledLP(resolveInfo.activityInfo)) { 8406// retList.add(resolveInfo); 8407// } 8408// } 8409// return retList; 8410// } 8411 8412 // Keys are String (activity class name), values are Activity. 8413 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8414 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8415 private int mFlags; 8416 } 8417 8418 private final class ServiceIntentResolver 8419 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8420 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8421 boolean defaultOnly, int userId) { 8422 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8423 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8424 } 8425 8426 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8427 int userId) { 8428 if (!sUserManager.exists(userId)) return null; 8429 mFlags = flags; 8430 return super.queryIntent(intent, resolvedType, 8431 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8432 } 8433 8434 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8435 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8436 if (!sUserManager.exists(userId)) return null; 8437 if (packageServices == null) { 8438 return null; 8439 } 8440 mFlags = flags; 8441 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8442 final int N = packageServices.size(); 8443 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8444 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8445 8446 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8447 for (int i = 0; i < N; ++i) { 8448 intentFilters = packageServices.get(i).intents; 8449 if (intentFilters != null && intentFilters.size() > 0) { 8450 PackageParser.ServiceIntentInfo[] array = 8451 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8452 intentFilters.toArray(array); 8453 listCut.add(array); 8454 } 8455 } 8456 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8457 } 8458 8459 public final void addService(PackageParser.Service s) { 8460 mServices.put(s.getComponentName(), s); 8461 if (DEBUG_SHOW_INFO) { 8462 Log.v(TAG, " " 8463 + (s.info.nonLocalizedLabel != null 8464 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8465 Log.v(TAG, " Class=" + s.info.name); 8466 } 8467 final int NI = s.intents.size(); 8468 int j; 8469 for (j=0; j<NI; j++) { 8470 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8471 if (DEBUG_SHOW_INFO) { 8472 Log.v(TAG, " IntentFilter:"); 8473 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8474 } 8475 if (!intent.debugCheck()) { 8476 Log.w(TAG, "==> For Service " + s.info.name); 8477 } 8478 addFilter(intent); 8479 } 8480 } 8481 8482 public final void removeService(PackageParser.Service s) { 8483 mServices.remove(s.getComponentName()); 8484 if (DEBUG_SHOW_INFO) { 8485 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8486 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8487 Log.v(TAG, " Class=" + s.info.name); 8488 } 8489 final int NI = s.intents.size(); 8490 int j; 8491 for (j=0; j<NI; j++) { 8492 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8493 if (DEBUG_SHOW_INFO) { 8494 Log.v(TAG, " IntentFilter:"); 8495 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8496 } 8497 removeFilter(intent); 8498 } 8499 } 8500 8501 @Override 8502 protected boolean allowFilterResult( 8503 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8504 ServiceInfo filterSi = filter.service.info; 8505 for (int i=dest.size()-1; i>=0; i--) { 8506 ServiceInfo destAi = dest.get(i).serviceInfo; 8507 if (destAi.name == filterSi.name 8508 && destAi.packageName == filterSi.packageName) { 8509 return false; 8510 } 8511 } 8512 return true; 8513 } 8514 8515 @Override 8516 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8517 return new PackageParser.ServiceIntentInfo[size]; 8518 } 8519 8520 @Override 8521 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8522 if (!sUserManager.exists(userId)) return true; 8523 PackageParser.Package p = filter.service.owner; 8524 if (p != null) { 8525 PackageSetting ps = (PackageSetting)p.mExtras; 8526 if (ps != null) { 8527 // System apps are never considered stopped for purposes of 8528 // filtering, because there may be no way for the user to 8529 // actually re-launch them. 8530 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8531 && ps.getStopped(userId); 8532 } 8533 } 8534 return false; 8535 } 8536 8537 @Override 8538 protected boolean isPackageForFilter(String packageName, 8539 PackageParser.ServiceIntentInfo info) { 8540 return packageName.equals(info.service.owner.packageName); 8541 } 8542 8543 @Override 8544 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8545 int match, int userId) { 8546 if (!sUserManager.exists(userId)) return null; 8547 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8548 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8549 return null; 8550 } 8551 final PackageParser.Service service = info.service; 8552 if (mSafeMode && (service.info.applicationInfo.flags 8553 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8554 return null; 8555 } 8556 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8557 if (ps == null) { 8558 return null; 8559 } 8560 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8561 ps.readUserState(userId), userId); 8562 if (si == null) { 8563 return null; 8564 } 8565 final ResolveInfo res = new ResolveInfo(); 8566 res.serviceInfo = si; 8567 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8568 res.filter = filter; 8569 } 8570 res.priority = info.getPriority(); 8571 res.preferredOrder = service.owner.mPreferredOrder; 8572 res.match = match; 8573 res.isDefault = info.hasDefault; 8574 res.labelRes = info.labelRes; 8575 res.nonLocalizedLabel = info.nonLocalizedLabel; 8576 res.icon = info.icon; 8577 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8578 return res; 8579 } 8580 8581 @Override 8582 protected void sortResults(List<ResolveInfo> results) { 8583 Collections.sort(results, mResolvePrioritySorter); 8584 } 8585 8586 @Override 8587 protected void dumpFilter(PrintWriter out, String prefix, 8588 PackageParser.ServiceIntentInfo filter) { 8589 out.print(prefix); out.print( 8590 Integer.toHexString(System.identityHashCode(filter.service))); 8591 out.print(' '); 8592 filter.service.printComponentShortName(out); 8593 out.print(" filter "); 8594 out.println(Integer.toHexString(System.identityHashCode(filter))); 8595 } 8596 8597 @Override 8598 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8599 return filter.service; 8600 } 8601 8602 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8603 PackageParser.Service service = (PackageParser.Service)label; 8604 out.print(prefix); out.print( 8605 Integer.toHexString(System.identityHashCode(service))); 8606 out.print(' '); 8607 service.printComponentShortName(out); 8608 if (count > 1) { 8609 out.print(" ("); out.print(count); out.print(" filters)"); 8610 } 8611 out.println(); 8612 } 8613 8614// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8615// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8616// final List<ResolveInfo> retList = Lists.newArrayList(); 8617// while (i.hasNext()) { 8618// final ResolveInfo resolveInfo = (ResolveInfo) i; 8619// if (isEnabledLP(resolveInfo.serviceInfo)) { 8620// retList.add(resolveInfo); 8621// } 8622// } 8623// return retList; 8624// } 8625 8626 // Keys are String (activity class name), values are Activity. 8627 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8628 = new ArrayMap<ComponentName, PackageParser.Service>(); 8629 private int mFlags; 8630 }; 8631 8632 private final class ProviderIntentResolver 8633 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8634 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8635 boolean defaultOnly, int userId) { 8636 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8637 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8638 } 8639 8640 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8641 int userId) { 8642 if (!sUserManager.exists(userId)) 8643 return null; 8644 mFlags = flags; 8645 return super.queryIntent(intent, resolvedType, 8646 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8647 } 8648 8649 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8650 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8651 if (!sUserManager.exists(userId)) 8652 return null; 8653 if (packageProviders == null) { 8654 return null; 8655 } 8656 mFlags = flags; 8657 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8658 final int N = packageProviders.size(); 8659 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8660 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8661 8662 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8663 for (int i = 0; i < N; ++i) { 8664 intentFilters = packageProviders.get(i).intents; 8665 if (intentFilters != null && intentFilters.size() > 0) { 8666 PackageParser.ProviderIntentInfo[] array = 8667 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8668 intentFilters.toArray(array); 8669 listCut.add(array); 8670 } 8671 } 8672 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8673 } 8674 8675 public final void addProvider(PackageParser.Provider p) { 8676 if (mProviders.containsKey(p.getComponentName())) { 8677 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8678 return; 8679 } 8680 8681 mProviders.put(p.getComponentName(), p); 8682 if (DEBUG_SHOW_INFO) { 8683 Log.v(TAG, " " 8684 + (p.info.nonLocalizedLabel != null 8685 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8686 Log.v(TAG, " Class=" + p.info.name); 8687 } 8688 final int NI = p.intents.size(); 8689 int j; 8690 for (j = 0; j < NI; j++) { 8691 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8692 if (DEBUG_SHOW_INFO) { 8693 Log.v(TAG, " IntentFilter:"); 8694 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8695 } 8696 if (!intent.debugCheck()) { 8697 Log.w(TAG, "==> For Provider " + p.info.name); 8698 } 8699 addFilter(intent); 8700 } 8701 } 8702 8703 public final void removeProvider(PackageParser.Provider p) { 8704 mProviders.remove(p.getComponentName()); 8705 if (DEBUG_SHOW_INFO) { 8706 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8707 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8708 Log.v(TAG, " Class=" + p.info.name); 8709 } 8710 final int NI = p.intents.size(); 8711 int j; 8712 for (j = 0; j < NI; j++) { 8713 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8714 if (DEBUG_SHOW_INFO) { 8715 Log.v(TAG, " IntentFilter:"); 8716 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8717 } 8718 removeFilter(intent); 8719 } 8720 } 8721 8722 @Override 8723 protected boolean allowFilterResult( 8724 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8725 ProviderInfo filterPi = filter.provider.info; 8726 for (int i = dest.size() - 1; i >= 0; i--) { 8727 ProviderInfo destPi = dest.get(i).providerInfo; 8728 if (destPi.name == filterPi.name 8729 && destPi.packageName == filterPi.packageName) { 8730 return false; 8731 } 8732 } 8733 return true; 8734 } 8735 8736 @Override 8737 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8738 return new PackageParser.ProviderIntentInfo[size]; 8739 } 8740 8741 @Override 8742 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8743 if (!sUserManager.exists(userId)) 8744 return true; 8745 PackageParser.Package p = filter.provider.owner; 8746 if (p != null) { 8747 PackageSetting ps = (PackageSetting) p.mExtras; 8748 if (ps != null) { 8749 // System apps are never considered stopped for purposes of 8750 // filtering, because there may be no way for the user to 8751 // actually re-launch them. 8752 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8753 && ps.getStopped(userId); 8754 } 8755 } 8756 return false; 8757 } 8758 8759 @Override 8760 protected boolean isPackageForFilter(String packageName, 8761 PackageParser.ProviderIntentInfo info) { 8762 return packageName.equals(info.provider.owner.packageName); 8763 } 8764 8765 @Override 8766 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8767 int match, int userId) { 8768 if (!sUserManager.exists(userId)) 8769 return null; 8770 final PackageParser.ProviderIntentInfo info = filter; 8771 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8772 return null; 8773 } 8774 final PackageParser.Provider provider = info.provider; 8775 if (mSafeMode && (provider.info.applicationInfo.flags 8776 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8777 return null; 8778 } 8779 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8780 if (ps == null) { 8781 return null; 8782 } 8783 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8784 ps.readUserState(userId), userId); 8785 if (pi == null) { 8786 return null; 8787 } 8788 final ResolveInfo res = new ResolveInfo(); 8789 res.providerInfo = pi; 8790 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8791 res.filter = filter; 8792 } 8793 res.priority = info.getPriority(); 8794 res.preferredOrder = provider.owner.mPreferredOrder; 8795 res.match = match; 8796 res.isDefault = info.hasDefault; 8797 res.labelRes = info.labelRes; 8798 res.nonLocalizedLabel = info.nonLocalizedLabel; 8799 res.icon = info.icon; 8800 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8801 return res; 8802 } 8803 8804 @Override 8805 protected void sortResults(List<ResolveInfo> results) { 8806 Collections.sort(results, mResolvePrioritySorter); 8807 } 8808 8809 @Override 8810 protected void dumpFilter(PrintWriter out, String prefix, 8811 PackageParser.ProviderIntentInfo filter) { 8812 out.print(prefix); 8813 out.print( 8814 Integer.toHexString(System.identityHashCode(filter.provider))); 8815 out.print(' '); 8816 filter.provider.printComponentShortName(out); 8817 out.print(" filter "); 8818 out.println(Integer.toHexString(System.identityHashCode(filter))); 8819 } 8820 8821 @Override 8822 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8823 return filter.provider; 8824 } 8825 8826 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8827 PackageParser.Provider provider = (PackageParser.Provider)label; 8828 out.print(prefix); out.print( 8829 Integer.toHexString(System.identityHashCode(provider))); 8830 out.print(' '); 8831 provider.printComponentShortName(out); 8832 if (count > 1) { 8833 out.print(" ("); out.print(count); out.print(" filters)"); 8834 } 8835 out.println(); 8836 } 8837 8838 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8839 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8840 private int mFlags; 8841 }; 8842 8843 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8844 new Comparator<ResolveInfo>() { 8845 public int compare(ResolveInfo r1, ResolveInfo r2) { 8846 int v1 = r1.priority; 8847 int v2 = r2.priority; 8848 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8849 if (v1 != v2) { 8850 return (v1 > v2) ? -1 : 1; 8851 } 8852 v1 = r1.preferredOrder; 8853 v2 = r2.preferredOrder; 8854 if (v1 != v2) { 8855 return (v1 > v2) ? -1 : 1; 8856 } 8857 if (r1.isDefault != r2.isDefault) { 8858 return r1.isDefault ? -1 : 1; 8859 } 8860 v1 = r1.match; 8861 v2 = r2.match; 8862 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8863 if (v1 != v2) { 8864 return (v1 > v2) ? -1 : 1; 8865 } 8866 if (r1.system != r2.system) { 8867 return r1.system ? -1 : 1; 8868 } 8869 return 0; 8870 } 8871 }; 8872 8873 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8874 new Comparator<ProviderInfo>() { 8875 public int compare(ProviderInfo p1, ProviderInfo p2) { 8876 final int v1 = p1.initOrder; 8877 final int v2 = p2.initOrder; 8878 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8879 } 8880 }; 8881 8882 final void sendPackageBroadcast(final String action, final String pkg, 8883 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8884 final int[] userIds) { 8885 mHandler.post(new Runnable() { 8886 @Override 8887 public void run() { 8888 try { 8889 final IActivityManager am = ActivityManagerNative.getDefault(); 8890 if (am == null) return; 8891 final int[] resolvedUserIds; 8892 if (userIds == null) { 8893 resolvedUserIds = am.getRunningUserIds(); 8894 } else { 8895 resolvedUserIds = userIds; 8896 } 8897 for (int id : resolvedUserIds) { 8898 final Intent intent = new Intent(action, 8899 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8900 if (extras != null) { 8901 intent.putExtras(extras); 8902 } 8903 if (targetPkg != null) { 8904 intent.setPackage(targetPkg); 8905 } 8906 // Modify the UID when posting to other users 8907 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8908 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8909 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8910 intent.putExtra(Intent.EXTRA_UID, uid); 8911 } 8912 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8913 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8914 if (DEBUG_BROADCASTS) { 8915 RuntimeException here = new RuntimeException("here"); 8916 here.fillInStackTrace(); 8917 Slog.d(TAG, "Sending to user " + id + ": " 8918 + intent.toShortString(false, true, false, false) 8919 + " " + intent.getExtras(), here); 8920 } 8921 am.broadcastIntent(null, intent, null, finishedReceiver, 8922 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8923 null, finishedReceiver != null, false, id); 8924 } 8925 } catch (RemoteException ex) { 8926 } 8927 } 8928 }); 8929 } 8930 8931 /** 8932 * Check if the external storage media is available. This is true if there 8933 * is a mounted external storage medium or if the external storage is 8934 * emulated. 8935 */ 8936 private boolean isExternalMediaAvailable() { 8937 return mMediaMounted || Environment.isExternalStorageEmulated(); 8938 } 8939 8940 @Override 8941 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8942 // writer 8943 synchronized (mPackages) { 8944 if (!isExternalMediaAvailable()) { 8945 // If the external storage is no longer mounted at this point, 8946 // the caller may not have been able to delete all of this 8947 // packages files and can not delete any more. Bail. 8948 return null; 8949 } 8950 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8951 if (lastPackage != null) { 8952 pkgs.remove(lastPackage); 8953 } 8954 if (pkgs.size() > 0) { 8955 return pkgs.get(0); 8956 } 8957 } 8958 return null; 8959 } 8960 8961 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8962 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8963 userId, andCode ? 1 : 0, packageName); 8964 if (mSystemReady) { 8965 msg.sendToTarget(); 8966 } else { 8967 if (mPostSystemReadyMessages == null) { 8968 mPostSystemReadyMessages = new ArrayList<>(); 8969 } 8970 mPostSystemReadyMessages.add(msg); 8971 } 8972 } 8973 8974 void startCleaningPackages() { 8975 // reader 8976 synchronized (mPackages) { 8977 if (!isExternalMediaAvailable()) { 8978 return; 8979 } 8980 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8981 return; 8982 } 8983 } 8984 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8985 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8986 IActivityManager am = ActivityManagerNative.getDefault(); 8987 if (am != null) { 8988 try { 8989 am.startService(null, intent, null, UserHandle.USER_OWNER); 8990 } catch (RemoteException e) { 8991 } 8992 } 8993 } 8994 8995 @Override 8996 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8997 int installFlags, String installerPackageName, VerificationParams verificationParams, 8998 String packageAbiOverride) { 8999 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 9000 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 9001 } 9002 9003 @Override 9004 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 9005 int installFlags, String installerPackageName, VerificationParams verificationParams, 9006 String packageAbiOverride, int userId) { 9007 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 9008 9009 final int callingUid = Binder.getCallingUid(); 9010 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 9011 9012 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9013 try { 9014 if (observer != null) { 9015 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 9016 } 9017 } catch (RemoteException re) { 9018 } 9019 return; 9020 } 9021 9022 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 9023 installFlags |= PackageManager.INSTALL_FROM_ADB; 9024 9025 } else { 9026 // Caller holds INSTALL_PACKAGES permission, so we're less strict 9027 // about installerPackageName. 9028 9029 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 9030 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 9031 } 9032 9033 UserHandle user; 9034 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 9035 user = UserHandle.ALL; 9036 } else { 9037 user = new UserHandle(userId); 9038 } 9039 9040 // Only system components can circumvent runtime permissions when installing. 9041 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 9042 && mContext.checkCallingOrSelfPermission(Manifest.permission 9043 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 9044 throw new SecurityException("You need the " 9045 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 9046 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 9047 } 9048 9049 verificationParams.setInstallerUid(callingUid); 9050 9051 final File originFile = new File(originPath); 9052 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 9053 9054 final Message msg = mHandler.obtainMessage(INIT_COPY); 9055 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 9056 null, verificationParams, user, packageAbiOverride); 9057 mHandler.sendMessage(msg); 9058 } 9059 9060 void installStage(String packageName, File stagedDir, String stagedCid, 9061 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 9062 String installerPackageName, int installerUid, UserHandle user) { 9063 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 9064 params.referrerUri, installerUid, null); 9065 9066 final OriginInfo origin; 9067 if (stagedDir != null) { 9068 origin = OriginInfo.fromStagedFile(stagedDir); 9069 } else { 9070 origin = OriginInfo.fromStagedContainer(stagedCid); 9071 } 9072 9073 final Message msg = mHandler.obtainMessage(INIT_COPY); 9074 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 9075 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 9076 mHandler.sendMessage(msg); 9077 } 9078 9079 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 9080 Bundle extras = new Bundle(1); 9081 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 9082 9083 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 9084 packageName, extras, null, null, new int[] {userId}); 9085 try { 9086 IActivityManager am = ActivityManagerNative.getDefault(); 9087 final boolean isSystem = 9088 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 9089 if (isSystem && am.isUserRunning(userId, false)) { 9090 // The just-installed/enabled app is bundled on the system, so presumed 9091 // to be able to run automatically without needing an explicit launch. 9092 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 9093 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 9094 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 9095 .setPackage(packageName); 9096 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 9097 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 9098 } 9099 } catch (RemoteException e) { 9100 // shouldn't happen 9101 Slog.w(TAG, "Unable to bootstrap installed package", e); 9102 } 9103 } 9104 9105 @Override 9106 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9107 int userId) { 9108 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9109 PackageSetting pkgSetting; 9110 final int uid = Binder.getCallingUid(); 9111 enforceCrossUserPermission(uid, userId, true, true, 9112 "setApplicationHiddenSetting for user " + userId); 9113 9114 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9115 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9116 return false; 9117 } 9118 9119 long callingId = Binder.clearCallingIdentity(); 9120 try { 9121 boolean sendAdded = false; 9122 boolean sendRemoved = false; 9123 // writer 9124 synchronized (mPackages) { 9125 pkgSetting = mSettings.mPackages.get(packageName); 9126 if (pkgSetting == null) { 9127 return false; 9128 } 9129 if (pkgSetting.getHidden(userId) != hidden) { 9130 pkgSetting.setHidden(hidden, userId); 9131 mSettings.writePackageRestrictionsLPr(userId); 9132 if (hidden) { 9133 sendRemoved = true; 9134 } else { 9135 sendAdded = true; 9136 } 9137 } 9138 } 9139 if (sendAdded) { 9140 sendPackageAddedForUser(packageName, pkgSetting, userId); 9141 return true; 9142 } 9143 if (sendRemoved) { 9144 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9145 "hiding pkg"); 9146 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9147 } 9148 } finally { 9149 Binder.restoreCallingIdentity(callingId); 9150 } 9151 return false; 9152 } 9153 9154 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9155 int userId) { 9156 final PackageRemovedInfo info = new PackageRemovedInfo(); 9157 info.removedPackage = packageName; 9158 info.removedUsers = new int[] {userId}; 9159 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9160 info.sendBroadcast(false, false, false); 9161 } 9162 9163 /** 9164 * Returns true if application is not found or there was an error. Otherwise it returns 9165 * the hidden state of the package for the given user. 9166 */ 9167 @Override 9168 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9169 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9170 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9171 false, "getApplicationHidden for user " + userId); 9172 PackageSetting pkgSetting; 9173 long callingId = Binder.clearCallingIdentity(); 9174 try { 9175 // writer 9176 synchronized (mPackages) { 9177 pkgSetting = mSettings.mPackages.get(packageName); 9178 if (pkgSetting == null) { 9179 return true; 9180 } 9181 return pkgSetting.getHidden(userId); 9182 } 9183 } finally { 9184 Binder.restoreCallingIdentity(callingId); 9185 } 9186 } 9187 9188 /** 9189 * @hide 9190 */ 9191 @Override 9192 public int installExistingPackageAsUser(String packageName, int userId) { 9193 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9194 null); 9195 PackageSetting pkgSetting; 9196 final int uid = Binder.getCallingUid(); 9197 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9198 + userId); 9199 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9200 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9201 } 9202 9203 long callingId = Binder.clearCallingIdentity(); 9204 try { 9205 boolean sendAdded = false; 9206 9207 // writer 9208 synchronized (mPackages) { 9209 pkgSetting = mSettings.mPackages.get(packageName); 9210 if (pkgSetting == null) { 9211 return PackageManager.INSTALL_FAILED_INVALID_URI; 9212 } 9213 if (!pkgSetting.getInstalled(userId)) { 9214 pkgSetting.setInstalled(true, userId); 9215 pkgSetting.setHidden(false, userId); 9216 mSettings.writePackageRestrictionsLPr(userId); 9217 sendAdded = true; 9218 } 9219 } 9220 9221 if (sendAdded) { 9222 sendPackageAddedForUser(packageName, pkgSetting, userId); 9223 } 9224 } finally { 9225 Binder.restoreCallingIdentity(callingId); 9226 } 9227 9228 return PackageManager.INSTALL_SUCCEEDED; 9229 } 9230 9231 boolean isUserRestricted(int userId, String restrictionKey) { 9232 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9233 if (restrictions.getBoolean(restrictionKey, false)) { 9234 Log.w(TAG, "User is restricted: " + restrictionKey); 9235 return true; 9236 } 9237 return false; 9238 } 9239 9240 @Override 9241 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9242 mContext.enforceCallingOrSelfPermission( 9243 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9244 "Only package verification agents can verify applications"); 9245 9246 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9247 final PackageVerificationResponse response = new PackageVerificationResponse( 9248 verificationCode, Binder.getCallingUid()); 9249 msg.arg1 = id; 9250 msg.obj = response; 9251 mHandler.sendMessage(msg); 9252 } 9253 9254 @Override 9255 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9256 long millisecondsToDelay) { 9257 mContext.enforceCallingOrSelfPermission( 9258 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9259 "Only package verification agents can extend verification timeouts"); 9260 9261 final PackageVerificationState state = mPendingVerification.get(id); 9262 final PackageVerificationResponse response = new PackageVerificationResponse( 9263 verificationCodeAtTimeout, Binder.getCallingUid()); 9264 9265 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9266 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9267 } 9268 if (millisecondsToDelay < 0) { 9269 millisecondsToDelay = 0; 9270 } 9271 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9272 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9273 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9274 } 9275 9276 if ((state != null) && !state.timeoutExtended()) { 9277 state.extendTimeout(); 9278 9279 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9280 msg.arg1 = id; 9281 msg.obj = response; 9282 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9283 } 9284 } 9285 9286 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9287 int verificationCode, UserHandle user) { 9288 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9289 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9290 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9291 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9292 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9293 9294 mContext.sendBroadcastAsUser(intent, user, 9295 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9296 } 9297 9298 private ComponentName matchComponentForVerifier(String packageName, 9299 List<ResolveInfo> receivers) { 9300 ActivityInfo targetReceiver = null; 9301 9302 final int NR = receivers.size(); 9303 for (int i = 0; i < NR; i++) { 9304 final ResolveInfo info = receivers.get(i); 9305 if (info.activityInfo == null) { 9306 continue; 9307 } 9308 9309 if (packageName.equals(info.activityInfo.packageName)) { 9310 targetReceiver = info.activityInfo; 9311 break; 9312 } 9313 } 9314 9315 if (targetReceiver == null) { 9316 return null; 9317 } 9318 9319 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9320 } 9321 9322 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9323 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9324 if (pkgInfo.verifiers.length == 0) { 9325 return null; 9326 } 9327 9328 final int N = pkgInfo.verifiers.length; 9329 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9330 for (int i = 0; i < N; i++) { 9331 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9332 9333 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9334 receivers); 9335 if (comp == null) { 9336 continue; 9337 } 9338 9339 final int verifierUid = getUidForVerifier(verifierInfo); 9340 if (verifierUid == -1) { 9341 continue; 9342 } 9343 9344 if (DEBUG_VERIFY) { 9345 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9346 + " with the correct signature"); 9347 } 9348 sufficientVerifiers.add(comp); 9349 verificationState.addSufficientVerifier(verifierUid); 9350 } 9351 9352 return sufficientVerifiers; 9353 } 9354 9355 private int getUidForVerifier(VerifierInfo verifierInfo) { 9356 synchronized (mPackages) { 9357 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9358 if (pkg == null) { 9359 return -1; 9360 } else if (pkg.mSignatures.length != 1) { 9361 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9362 + " has more than one signature; ignoring"); 9363 return -1; 9364 } 9365 9366 /* 9367 * If the public key of the package's signature does not match 9368 * our expected public key, then this is a different package and 9369 * we should skip. 9370 */ 9371 9372 final byte[] expectedPublicKey; 9373 try { 9374 final Signature verifierSig = pkg.mSignatures[0]; 9375 final PublicKey publicKey = verifierSig.getPublicKey(); 9376 expectedPublicKey = publicKey.getEncoded(); 9377 } catch (CertificateException e) { 9378 return -1; 9379 } 9380 9381 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9382 9383 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9384 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9385 + " does not have the expected public key; ignoring"); 9386 return -1; 9387 } 9388 9389 return pkg.applicationInfo.uid; 9390 } 9391 } 9392 9393 @Override 9394 public void finishPackageInstall(int token) { 9395 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9396 9397 if (DEBUG_INSTALL) { 9398 Slog.v(TAG, "BM finishing package install for " + token); 9399 } 9400 9401 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9402 mHandler.sendMessage(msg); 9403 } 9404 9405 /** 9406 * Get the verification agent timeout. 9407 * 9408 * @return verification timeout in milliseconds 9409 */ 9410 private long getVerificationTimeout() { 9411 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9412 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9413 DEFAULT_VERIFICATION_TIMEOUT); 9414 } 9415 9416 /** 9417 * Get the default verification agent response code. 9418 * 9419 * @return default verification response code 9420 */ 9421 private int getDefaultVerificationResponse() { 9422 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9423 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9424 DEFAULT_VERIFICATION_RESPONSE); 9425 } 9426 9427 /** 9428 * Check whether or not package verification has been enabled. 9429 * 9430 * @return true if verification should be performed 9431 */ 9432 private boolean isVerificationEnabled(int userId, int installFlags) { 9433 if (!DEFAULT_VERIFY_ENABLE) { 9434 return false; 9435 } 9436 9437 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9438 9439 // Check if installing from ADB 9440 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9441 // Do not run verification in a test harness environment 9442 if (ActivityManager.isRunningInTestHarness()) { 9443 return false; 9444 } 9445 if (ensureVerifyAppsEnabled) { 9446 return true; 9447 } 9448 // Check if the developer does not want package verification for ADB installs 9449 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9450 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9451 return false; 9452 } 9453 } 9454 9455 if (ensureVerifyAppsEnabled) { 9456 return true; 9457 } 9458 9459 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9460 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9461 } 9462 9463 @Override 9464 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9465 throws RemoteException { 9466 mContext.enforceCallingOrSelfPermission( 9467 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9468 "Only intentfilter verification agents can verify applications"); 9469 9470 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9471 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9472 Binder.getCallingUid(), verificationCode, failedDomains); 9473 msg.arg1 = id; 9474 msg.obj = response; 9475 mHandler.sendMessage(msg); 9476 } 9477 9478 @Override 9479 public int getIntentVerificationStatus(String packageName, int userId) { 9480 synchronized (mPackages) { 9481 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9482 } 9483 } 9484 9485 @Override 9486 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9487 boolean result = false; 9488 synchronized (mPackages) { 9489 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9490 } 9491 if (result) { 9492 scheduleWritePackageRestrictionsLocked(userId); 9493 } 9494 return result; 9495 } 9496 9497 @Override 9498 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9499 synchronized (mPackages) { 9500 return mSettings.getIntentFilterVerificationsLPr(packageName); 9501 } 9502 } 9503 9504 @Override 9505 public List<IntentFilter> getAllIntentFilters(String packageName) { 9506 if (TextUtils.isEmpty(packageName)) { 9507 return Collections.<IntentFilter>emptyList(); 9508 } 9509 synchronized (mPackages) { 9510 PackageParser.Package pkg = mPackages.get(packageName); 9511 if (pkg == null || pkg.activities == null) { 9512 return Collections.<IntentFilter>emptyList(); 9513 } 9514 final int count = pkg.activities.size(); 9515 ArrayList<IntentFilter> result = new ArrayList<>(); 9516 for (int n=0; n<count; n++) { 9517 PackageParser.Activity activity = pkg.activities.get(n); 9518 if (activity.intents != null || activity.intents.size() > 0) { 9519 result.addAll(activity.intents); 9520 } 9521 } 9522 return result; 9523 } 9524 } 9525 9526 @Override 9527 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9528 synchronized (mPackages) { 9529 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9530 if (packageName != null) { 9531 result |= updateIntentVerificationStatus(packageName, 9532 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9533 UserHandle.myUserId()); 9534 } 9535 return result; 9536 } 9537 } 9538 9539 @Override 9540 public String getDefaultBrowserPackageName(int userId) { 9541 synchronized (mPackages) { 9542 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9543 } 9544 } 9545 9546 /** 9547 * Get the "allow unknown sources" setting. 9548 * 9549 * @return the current "allow unknown sources" setting 9550 */ 9551 private int getUnknownSourcesSettings() { 9552 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9553 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9554 -1); 9555 } 9556 9557 @Override 9558 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9559 final int uid = Binder.getCallingUid(); 9560 // writer 9561 synchronized (mPackages) { 9562 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9563 if (targetPackageSetting == null) { 9564 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9565 } 9566 9567 PackageSetting installerPackageSetting; 9568 if (installerPackageName != null) { 9569 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9570 if (installerPackageSetting == null) { 9571 throw new IllegalArgumentException("Unknown installer package: " 9572 + installerPackageName); 9573 } 9574 } else { 9575 installerPackageSetting = null; 9576 } 9577 9578 Signature[] callerSignature; 9579 Object obj = mSettings.getUserIdLPr(uid); 9580 if (obj != null) { 9581 if (obj instanceof SharedUserSetting) { 9582 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9583 } else if (obj instanceof PackageSetting) { 9584 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9585 } else { 9586 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9587 } 9588 } else { 9589 throw new SecurityException("Unknown calling uid " + uid); 9590 } 9591 9592 // Verify: can't set installerPackageName to a package that is 9593 // not signed with the same cert as the caller. 9594 if (installerPackageSetting != null) { 9595 if (compareSignatures(callerSignature, 9596 installerPackageSetting.signatures.mSignatures) 9597 != PackageManager.SIGNATURE_MATCH) { 9598 throw new SecurityException( 9599 "Caller does not have same cert as new installer package " 9600 + installerPackageName); 9601 } 9602 } 9603 9604 // Verify: if target already has an installer package, it must 9605 // be signed with the same cert as the caller. 9606 if (targetPackageSetting.installerPackageName != null) { 9607 PackageSetting setting = mSettings.mPackages.get( 9608 targetPackageSetting.installerPackageName); 9609 // If the currently set package isn't valid, then it's always 9610 // okay to change it. 9611 if (setting != null) { 9612 if (compareSignatures(callerSignature, 9613 setting.signatures.mSignatures) 9614 != PackageManager.SIGNATURE_MATCH) { 9615 throw new SecurityException( 9616 "Caller does not have same cert as old installer package " 9617 + targetPackageSetting.installerPackageName); 9618 } 9619 } 9620 } 9621 9622 // Okay! 9623 targetPackageSetting.installerPackageName = installerPackageName; 9624 scheduleWriteSettingsLocked(); 9625 } 9626 } 9627 9628 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9629 // Queue up an async operation since the package installation may take a little while. 9630 mHandler.post(new Runnable() { 9631 public void run() { 9632 mHandler.removeCallbacks(this); 9633 // Result object to be returned 9634 PackageInstalledInfo res = new PackageInstalledInfo(); 9635 res.returnCode = currentStatus; 9636 res.uid = -1; 9637 res.pkg = null; 9638 res.removedInfo = new PackageRemovedInfo(); 9639 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9640 args.doPreInstall(res.returnCode); 9641 synchronized (mInstallLock) { 9642 installPackageLI(args, res); 9643 } 9644 args.doPostInstall(res.returnCode, res.uid); 9645 } 9646 9647 // A restore should be performed at this point if (a) the install 9648 // succeeded, (b) the operation is not an update, and (c) the new 9649 // package has not opted out of backup participation. 9650 final boolean update = res.removedInfo.removedPackage != null; 9651 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9652 boolean doRestore = !update 9653 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9654 9655 // Set up the post-install work request bookkeeping. This will be used 9656 // and cleaned up by the post-install event handling regardless of whether 9657 // there's a restore pass performed. Token values are >= 1. 9658 int token; 9659 if (mNextInstallToken < 0) mNextInstallToken = 1; 9660 token = mNextInstallToken++; 9661 9662 PostInstallData data = new PostInstallData(args, res); 9663 mRunningInstalls.put(token, data); 9664 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9665 9666 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9667 // Pass responsibility to the Backup Manager. It will perform a 9668 // restore if appropriate, then pass responsibility back to the 9669 // Package Manager to run the post-install observer callbacks 9670 // and broadcasts. 9671 IBackupManager bm = IBackupManager.Stub.asInterface( 9672 ServiceManager.getService(Context.BACKUP_SERVICE)); 9673 if (bm != null) { 9674 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9675 + " to BM for possible restore"); 9676 try { 9677 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9678 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9679 } else { 9680 doRestore = false; 9681 } 9682 } catch (RemoteException e) { 9683 // can't happen; the backup manager is local 9684 } catch (Exception e) { 9685 Slog.e(TAG, "Exception trying to enqueue restore", e); 9686 doRestore = false; 9687 } 9688 } else { 9689 Slog.e(TAG, "Backup Manager not found!"); 9690 doRestore = false; 9691 } 9692 } 9693 9694 if (!doRestore) { 9695 // No restore possible, or the Backup Manager was mysteriously not 9696 // available -- just fire the post-install work request directly. 9697 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9698 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9699 mHandler.sendMessage(msg); 9700 } 9701 } 9702 }); 9703 } 9704 9705 private abstract class HandlerParams { 9706 private static final int MAX_RETRIES = 4; 9707 9708 /** 9709 * Number of times startCopy() has been attempted and had a non-fatal 9710 * error. 9711 */ 9712 private int mRetries = 0; 9713 9714 /** User handle for the user requesting the information or installation. */ 9715 private final UserHandle mUser; 9716 9717 HandlerParams(UserHandle user) { 9718 mUser = user; 9719 } 9720 9721 UserHandle getUser() { 9722 return mUser; 9723 } 9724 9725 final boolean startCopy() { 9726 boolean res; 9727 try { 9728 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9729 9730 if (++mRetries > MAX_RETRIES) { 9731 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9732 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9733 handleServiceError(); 9734 return false; 9735 } else { 9736 handleStartCopy(); 9737 res = true; 9738 } 9739 } catch (RemoteException e) { 9740 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9741 mHandler.sendEmptyMessage(MCS_RECONNECT); 9742 res = false; 9743 } 9744 handleReturnCode(); 9745 return res; 9746 } 9747 9748 final void serviceError() { 9749 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9750 handleServiceError(); 9751 handleReturnCode(); 9752 } 9753 9754 abstract void handleStartCopy() throws RemoteException; 9755 abstract void handleServiceError(); 9756 abstract void handleReturnCode(); 9757 } 9758 9759 class MeasureParams extends HandlerParams { 9760 private final PackageStats mStats; 9761 private boolean mSuccess; 9762 9763 private final IPackageStatsObserver mObserver; 9764 9765 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9766 super(new UserHandle(stats.userHandle)); 9767 mObserver = observer; 9768 mStats = stats; 9769 } 9770 9771 @Override 9772 public String toString() { 9773 return "MeasureParams{" 9774 + Integer.toHexString(System.identityHashCode(this)) 9775 + " " + mStats.packageName + "}"; 9776 } 9777 9778 @Override 9779 void handleStartCopy() throws RemoteException { 9780 synchronized (mInstallLock) { 9781 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9782 } 9783 9784 if (mSuccess) { 9785 final boolean mounted; 9786 if (Environment.isExternalStorageEmulated()) { 9787 mounted = true; 9788 } else { 9789 final String status = Environment.getExternalStorageState(); 9790 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9791 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9792 } 9793 9794 if (mounted) { 9795 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9796 9797 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9798 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9799 9800 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9801 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9802 9803 // Always subtract cache size, since it's a subdirectory 9804 mStats.externalDataSize -= mStats.externalCacheSize; 9805 9806 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9807 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9808 9809 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9810 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9811 } 9812 } 9813 } 9814 9815 @Override 9816 void handleReturnCode() { 9817 if (mObserver != null) { 9818 try { 9819 mObserver.onGetStatsCompleted(mStats, mSuccess); 9820 } catch (RemoteException e) { 9821 Slog.i(TAG, "Observer no longer exists."); 9822 } 9823 } 9824 } 9825 9826 @Override 9827 void handleServiceError() { 9828 Slog.e(TAG, "Could not measure application " + mStats.packageName 9829 + " external storage"); 9830 } 9831 } 9832 9833 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9834 throws RemoteException { 9835 long result = 0; 9836 for (File path : paths) { 9837 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9838 } 9839 return result; 9840 } 9841 9842 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9843 for (File path : paths) { 9844 try { 9845 mcs.clearDirectory(path.getAbsolutePath()); 9846 } catch (RemoteException e) { 9847 } 9848 } 9849 } 9850 9851 static class OriginInfo { 9852 /** 9853 * Location where install is coming from, before it has been 9854 * copied/renamed into place. This could be a single monolithic APK 9855 * file, or a cluster directory. This location may be untrusted. 9856 */ 9857 final File file; 9858 final String cid; 9859 9860 /** 9861 * Flag indicating that {@link #file} or {@link #cid} has already been 9862 * staged, meaning downstream users don't need to defensively copy the 9863 * contents. 9864 */ 9865 final boolean staged; 9866 9867 /** 9868 * Flag indicating that {@link #file} or {@link #cid} is an already 9869 * installed app that is being moved. 9870 */ 9871 final boolean existing; 9872 9873 final String resolvedPath; 9874 final File resolvedFile; 9875 9876 static OriginInfo fromNothing() { 9877 return new OriginInfo(null, null, false, false); 9878 } 9879 9880 static OriginInfo fromUntrustedFile(File file) { 9881 return new OriginInfo(file, null, false, false); 9882 } 9883 9884 static OriginInfo fromExistingFile(File file) { 9885 return new OriginInfo(file, null, false, true); 9886 } 9887 9888 static OriginInfo fromStagedFile(File file) { 9889 return new OriginInfo(file, null, true, false); 9890 } 9891 9892 static OriginInfo fromStagedContainer(String cid) { 9893 return new OriginInfo(null, cid, true, false); 9894 } 9895 9896 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9897 this.file = file; 9898 this.cid = cid; 9899 this.staged = staged; 9900 this.existing = existing; 9901 9902 if (cid != null) { 9903 resolvedPath = PackageHelper.getSdDir(cid); 9904 resolvedFile = new File(resolvedPath); 9905 } else if (file != null) { 9906 resolvedPath = file.getAbsolutePath(); 9907 resolvedFile = file; 9908 } else { 9909 resolvedPath = null; 9910 resolvedFile = null; 9911 } 9912 } 9913 } 9914 9915 class MoveInfo { 9916 final int moveId; 9917 final String fromUuid; 9918 final String toUuid; 9919 final String packageName; 9920 final String dataAppName; 9921 final int appId; 9922 final String seinfo; 9923 9924 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9925 String dataAppName, int appId, String seinfo) { 9926 this.moveId = moveId; 9927 this.fromUuid = fromUuid; 9928 this.toUuid = toUuid; 9929 this.packageName = packageName; 9930 this.dataAppName = dataAppName; 9931 this.appId = appId; 9932 this.seinfo = seinfo; 9933 } 9934 } 9935 9936 class InstallParams extends HandlerParams { 9937 final OriginInfo origin; 9938 final MoveInfo move; 9939 final IPackageInstallObserver2 observer; 9940 int installFlags; 9941 final String installerPackageName; 9942 final String volumeUuid; 9943 final VerificationParams verificationParams; 9944 private InstallArgs mArgs; 9945 private int mRet; 9946 final String packageAbiOverride; 9947 9948 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9949 int installFlags, String installerPackageName, String volumeUuid, 9950 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9951 super(user); 9952 this.origin = origin; 9953 this.move = move; 9954 this.observer = observer; 9955 this.installFlags = installFlags; 9956 this.installerPackageName = installerPackageName; 9957 this.volumeUuid = volumeUuid; 9958 this.verificationParams = verificationParams; 9959 this.packageAbiOverride = packageAbiOverride; 9960 } 9961 9962 @Override 9963 public String toString() { 9964 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9965 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9966 } 9967 9968 public ManifestDigest getManifestDigest() { 9969 if (verificationParams == null) { 9970 return null; 9971 } 9972 return verificationParams.getManifestDigest(); 9973 } 9974 9975 private int installLocationPolicy(PackageInfoLite pkgLite) { 9976 String packageName = pkgLite.packageName; 9977 int installLocation = pkgLite.installLocation; 9978 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9979 // reader 9980 synchronized (mPackages) { 9981 PackageParser.Package pkg = mPackages.get(packageName); 9982 if (pkg != null) { 9983 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9984 // Check for downgrading. 9985 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9986 try { 9987 checkDowngrade(pkg, pkgLite); 9988 } catch (PackageManagerException e) { 9989 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9990 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9991 } 9992 } 9993 // Check for updated system application. 9994 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9995 if (onSd) { 9996 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9997 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9998 } 9999 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10000 } else { 10001 if (onSd) { 10002 // Install flag overrides everything. 10003 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10004 } 10005 // If current upgrade specifies particular preference 10006 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 10007 // Application explicitly specified internal. 10008 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10009 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 10010 // App explictly prefers external. Let policy decide 10011 } else { 10012 // Prefer previous location 10013 if (isExternal(pkg)) { 10014 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10015 } 10016 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 10017 } 10018 } 10019 } else { 10020 // Invalid install. Return error code 10021 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 10022 } 10023 } 10024 } 10025 // All the special cases have been taken care of. 10026 // Return result based on recommended install location. 10027 if (onSd) { 10028 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 10029 } 10030 return pkgLite.recommendedInstallLocation; 10031 } 10032 10033 /* 10034 * Invoke remote method to get package information and install 10035 * location values. Override install location based on default 10036 * policy if needed and then create install arguments based 10037 * on the install location. 10038 */ 10039 public void handleStartCopy() throws RemoteException { 10040 int ret = PackageManager.INSTALL_SUCCEEDED; 10041 10042 // If we're already staged, we've firmly committed to an install location 10043 if (origin.staged) { 10044 if (origin.file != null) { 10045 installFlags |= PackageManager.INSTALL_INTERNAL; 10046 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10047 } else if (origin.cid != null) { 10048 installFlags |= PackageManager.INSTALL_EXTERNAL; 10049 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10050 } else { 10051 throw new IllegalStateException("Invalid stage location"); 10052 } 10053 } 10054 10055 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10056 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 10057 10058 PackageInfoLite pkgLite = null; 10059 10060 if (onInt && onSd) { 10061 // Check if both bits are set. 10062 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 10063 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10064 } else { 10065 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 10066 packageAbiOverride); 10067 10068 /* 10069 * If we have too little free space, try to free cache 10070 * before giving up. 10071 */ 10072 if (!origin.staged && pkgLite.recommendedInstallLocation 10073 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10074 // TODO: focus freeing disk space on the target device 10075 final StorageManager storage = StorageManager.from(mContext); 10076 final long lowThreshold = storage.getStorageLowBytes( 10077 Environment.getDataDirectory()); 10078 10079 final long sizeBytes = mContainerService.calculateInstalledSize( 10080 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 10081 10082 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 10083 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 10084 installFlags, packageAbiOverride); 10085 } 10086 10087 /* 10088 * The cache free must have deleted the file we 10089 * downloaded to install. 10090 * 10091 * TODO: fix the "freeCache" call to not delete 10092 * the file we care about. 10093 */ 10094 if (pkgLite.recommendedInstallLocation 10095 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10096 pkgLite.recommendedInstallLocation 10097 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 10098 } 10099 } 10100 } 10101 10102 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10103 int loc = pkgLite.recommendedInstallLocation; 10104 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10105 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10106 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10107 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10108 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10109 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10110 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10111 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10112 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10113 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10114 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10115 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10116 } else { 10117 // Override with defaults if needed. 10118 loc = installLocationPolicy(pkgLite); 10119 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10120 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10121 } else if (!onSd && !onInt) { 10122 // Override install location with flags 10123 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10124 // Set the flag to install on external media. 10125 installFlags |= PackageManager.INSTALL_EXTERNAL; 10126 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10127 } else { 10128 // Make sure the flag for installing on external 10129 // media is unset 10130 installFlags |= PackageManager.INSTALL_INTERNAL; 10131 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10132 } 10133 } 10134 } 10135 } 10136 10137 final InstallArgs args = createInstallArgs(this); 10138 mArgs = args; 10139 10140 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10141 /* 10142 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10143 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10144 */ 10145 int userIdentifier = getUser().getIdentifier(); 10146 if (userIdentifier == UserHandle.USER_ALL 10147 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10148 userIdentifier = UserHandle.USER_OWNER; 10149 } 10150 10151 /* 10152 * Determine if we have any installed package verifiers. If we 10153 * do, then we'll defer to them to verify the packages. 10154 */ 10155 final int requiredUid = mRequiredVerifierPackage == null ? -1 10156 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10157 if (!origin.existing && requiredUid != -1 10158 && isVerificationEnabled(userIdentifier, installFlags)) { 10159 final Intent verification = new Intent( 10160 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10161 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10162 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10163 PACKAGE_MIME_TYPE); 10164 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10165 10166 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10167 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10168 0 /* TODO: Which userId? */); 10169 10170 if (DEBUG_VERIFY) { 10171 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10172 + verification.toString() + " with " + pkgLite.verifiers.length 10173 + " optional verifiers"); 10174 } 10175 10176 final int verificationId = mPendingVerificationToken++; 10177 10178 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10179 10180 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10181 installerPackageName); 10182 10183 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10184 installFlags); 10185 10186 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10187 pkgLite.packageName); 10188 10189 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10190 pkgLite.versionCode); 10191 10192 if (verificationParams != null) { 10193 if (verificationParams.getVerificationURI() != null) { 10194 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10195 verificationParams.getVerificationURI()); 10196 } 10197 if (verificationParams.getOriginatingURI() != null) { 10198 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10199 verificationParams.getOriginatingURI()); 10200 } 10201 if (verificationParams.getReferrer() != null) { 10202 verification.putExtra(Intent.EXTRA_REFERRER, 10203 verificationParams.getReferrer()); 10204 } 10205 if (verificationParams.getOriginatingUid() >= 0) { 10206 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10207 verificationParams.getOriginatingUid()); 10208 } 10209 if (verificationParams.getInstallerUid() >= 0) { 10210 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10211 verificationParams.getInstallerUid()); 10212 } 10213 } 10214 10215 final PackageVerificationState verificationState = new PackageVerificationState( 10216 requiredUid, args); 10217 10218 mPendingVerification.append(verificationId, verificationState); 10219 10220 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10221 receivers, verificationState); 10222 10223 /* 10224 * If any sufficient verifiers were listed in the package 10225 * manifest, attempt to ask them. 10226 */ 10227 if (sufficientVerifiers != null) { 10228 final int N = sufficientVerifiers.size(); 10229 if (N == 0) { 10230 Slog.i(TAG, "Additional verifiers required, but none installed."); 10231 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10232 } else { 10233 for (int i = 0; i < N; i++) { 10234 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10235 10236 final Intent sufficientIntent = new Intent(verification); 10237 sufficientIntent.setComponent(verifierComponent); 10238 10239 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10240 } 10241 } 10242 } 10243 10244 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10245 mRequiredVerifierPackage, receivers); 10246 if (ret == PackageManager.INSTALL_SUCCEEDED 10247 && mRequiredVerifierPackage != null) { 10248 /* 10249 * Send the intent to the required verification agent, 10250 * but only start the verification timeout after the 10251 * target BroadcastReceivers have run. 10252 */ 10253 verification.setComponent(requiredVerifierComponent); 10254 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10255 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10256 new BroadcastReceiver() { 10257 @Override 10258 public void onReceive(Context context, Intent intent) { 10259 final Message msg = mHandler 10260 .obtainMessage(CHECK_PENDING_VERIFICATION); 10261 msg.arg1 = verificationId; 10262 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10263 } 10264 }, null, 0, null, null); 10265 10266 /* 10267 * We don't want the copy to proceed until verification 10268 * succeeds, so null out this field. 10269 */ 10270 mArgs = null; 10271 } 10272 } else { 10273 /* 10274 * No package verification is enabled, so immediately start 10275 * the remote call to initiate copy using temporary file. 10276 */ 10277 ret = args.copyApk(mContainerService, true); 10278 } 10279 } 10280 10281 mRet = ret; 10282 } 10283 10284 @Override 10285 void handleReturnCode() { 10286 // If mArgs is null, then MCS couldn't be reached. When it 10287 // reconnects, it will try again to install. At that point, this 10288 // will succeed. 10289 if (mArgs != null) { 10290 processPendingInstall(mArgs, mRet); 10291 } 10292 } 10293 10294 @Override 10295 void handleServiceError() { 10296 mArgs = createInstallArgs(this); 10297 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10298 } 10299 10300 public boolean isForwardLocked() { 10301 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10302 } 10303 } 10304 10305 /** 10306 * Used during creation of InstallArgs 10307 * 10308 * @param installFlags package installation flags 10309 * @return true if should be installed on external storage 10310 */ 10311 private static boolean installOnExternalAsec(int installFlags) { 10312 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10313 return false; 10314 } 10315 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10316 return true; 10317 } 10318 return false; 10319 } 10320 10321 /** 10322 * Used during creation of InstallArgs 10323 * 10324 * @param installFlags package installation flags 10325 * @return true if should be installed as forward locked 10326 */ 10327 private static boolean installForwardLocked(int installFlags) { 10328 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10329 } 10330 10331 private InstallArgs createInstallArgs(InstallParams params) { 10332 if (params.move != null) { 10333 return new MoveInstallArgs(params); 10334 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10335 return new AsecInstallArgs(params); 10336 } else { 10337 return new FileInstallArgs(params); 10338 } 10339 } 10340 10341 /** 10342 * Create args that describe an existing installed package. Typically used 10343 * when cleaning up old installs, or used as a move source. 10344 */ 10345 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10346 String resourcePath, String[] instructionSets) { 10347 final boolean isInAsec; 10348 if (installOnExternalAsec(installFlags)) { 10349 /* Apps on SD card are always in ASEC containers. */ 10350 isInAsec = true; 10351 } else if (installForwardLocked(installFlags) 10352 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10353 /* 10354 * Forward-locked apps are only in ASEC containers if they're the 10355 * new style 10356 */ 10357 isInAsec = true; 10358 } else { 10359 isInAsec = false; 10360 } 10361 10362 if (isInAsec) { 10363 return new AsecInstallArgs(codePath, instructionSets, 10364 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10365 } else { 10366 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10367 } 10368 } 10369 10370 static abstract class InstallArgs { 10371 /** @see InstallParams#origin */ 10372 final OriginInfo origin; 10373 /** @see InstallParams#move */ 10374 final MoveInfo move; 10375 10376 final IPackageInstallObserver2 observer; 10377 // Always refers to PackageManager flags only 10378 final int installFlags; 10379 final String installerPackageName; 10380 final String volumeUuid; 10381 final ManifestDigest manifestDigest; 10382 final UserHandle user; 10383 final String abiOverride; 10384 10385 // The list of instruction sets supported by this app. This is currently 10386 // only used during the rmdex() phase to clean up resources. We can get rid of this 10387 // if we move dex files under the common app path. 10388 /* nullable */ String[] instructionSets; 10389 10390 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10391 int installFlags, String installerPackageName, String volumeUuid, 10392 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10393 String abiOverride) { 10394 this.origin = origin; 10395 this.move = move; 10396 this.installFlags = installFlags; 10397 this.observer = observer; 10398 this.installerPackageName = installerPackageName; 10399 this.volumeUuid = volumeUuid; 10400 this.manifestDigest = manifestDigest; 10401 this.user = user; 10402 this.instructionSets = instructionSets; 10403 this.abiOverride = abiOverride; 10404 } 10405 10406 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10407 abstract int doPreInstall(int status); 10408 10409 /** 10410 * Rename package into final resting place. All paths on the given 10411 * scanned package should be updated to reflect the rename. 10412 */ 10413 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10414 abstract int doPostInstall(int status, int uid); 10415 10416 /** @see PackageSettingBase#codePathString */ 10417 abstract String getCodePath(); 10418 /** @see PackageSettingBase#resourcePathString */ 10419 abstract String getResourcePath(); 10420 10421 // Need installer lock especially for dex file removal. 10422 abstract void cleanUpResourcesLI(); 10423 abstract boolean doPostDeleteLI(boolean delete); 10424 10425 /** 10426 * Called before the source arguments are copied. This is used mostly 10427 * for MoveParams when it needs to read the source file to put it in the 10428 * destination. 10429 */ 10430 int doPreCopy() { 10431 return PackageManager.INSTALL_SUCCEEDED; 10432 } 10433 10434 /** 10435 * Called after the source arguments are copied. This is used mostly for 10436 * MoveParams when it needs to read the source file to put it in the 10437 * destination. 10438 * 10439 * @return 10440 */ 10441 int doPostCopy(int uid) { 10442 return PackageManager.INSTALL_SUCCEEDED; 10443 } 10444 10445 protected boolean isFwdLocked() { 10446 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10447 } 10448 10449 protected boolean isExternalAsec() { 10450 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10451 } 10452 10453 UserHandle getUser() { 10454 return user; 10455 } 10456 } 10457 10458 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10459 if (!allCodePaths.isEmpty()) { 10460 if (instructionSets == null) { 10461 throw new IllegalStateException("instructionSet == null"); 10462 } 10463 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10464 for (String codePath : allCodePaths) { 10465 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10466 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10467 if (retCode < 0) { 10468 Slog.w(TAG, "Couldn't remove dex file for package: " 10469 + " at location " + codePath + ", retcode=" + retCode); 10470 // we don't consider this to be a failure of the core package deletion 10471 } 10472 } 10473 } 10474 } 10475 } 10476 10477 /** 10478 * Logic to handle installation of non-ASEC applications, including copying 10479 * and renaming logic. 10480 */ 10481 class FileInstallArgs extends InstallArgs { 10482 private File codeFile; 10483 private File resourceFile; 10484 10485 // Example topology: 10486 // /data/app/com.example/base.apk 10487 // /data/app/com.example/split_foo.apk 10488 // /data/app/com.example/lib/arm/libfoo.so 10489 // /data/app/com.example/lib/arm64/libfoo.so 10490 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10491 10492 /** New install */ 10493 FileInstallArgs(InstallParams params) { 10494 super(params.origin, params.move, params.observer, params.installFlags, 10495 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10496 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10497 if (isFwdLocked()) { 10498 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10499 } 10500 } 10501 10502 /** Existing install */ 10503 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10504 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10505 null); 10506 this.codeFile = (codePath != null) ? new File(codePath) : null; 10507 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10508 } 10509 10510 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10511 if (origin.staged) { 10512 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10513 codeFile = origin.file; 10514 resourceFile = origin.file; 10515 return PackageManager.INSTALL_SUCCEEDED; 10516 } 10517 10518 try { 10519 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10520 codeFile = tempDir; 10521 resourceFile = tempDir; 10522 } catch (IOException e) { 10523 Slog.w(TAG, "Failed to create copy file: " + e); 10524 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10525 } 10526 10527 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10528 @Override 10529 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10530 if (!FileUtils.isValidExtFilename(name)) { 10531 throw new IllegalArgumentException("Invalid filename: " + name); 10532 } 10533 try { 10534 final File file = new File(codeFile, name); 10535 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10536 O_RDWR | O_CREAT, 0644); 10537 Os.chmod(file.getAbsolutePath(), 0644); 10538 return new ParcelFileDescriptor(fd); 10539 } catch (ErrnoException e) { 10540 throw new RemoteException("Failed to open: " + e.getMessage()); 10541 } 10542 } 10543 }; 10544 10545 int ret = PackageManager.INSTALL_SUCCEEDED; 10546 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10547 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10548 Slog.e(TAG, "Failed to copy package"); 10549 return ret; 10550 } 10551 10552 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10553 NativeLibraryHelper.Handle handle = null; 10554 try { 10555 handle = NativeLibraryHelper.Handle.create(codeFile); 10556 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10557 abiOverride); 10558 } catch (IOException e) { 10559 Slog.e(TAG, "Copying native libraries failed", e); 10560 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10561 } finally { 10562 IoUtils.closeQuietly(handle); 10563 } 10564 10565 return ret; 10566 } 10567 10568 int doPreInstall(int status) { 10569 if (status != PackageManager.INSTALL_SUCCEEDED) { 10570 cleanUp(); 10571 } 10572 return status; 10573 } 10574 10575 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10576 if (status != PackageManager.INSTALL_SUCCEEDED) { 10577 cleanUp(); 10578 return false; 10579 } 10580 10581 final File targetDir = codeFile.getParentFile(); 10582 final File beforeCodeFile = codeFile; 10583 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10584 10585 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10586 try { 10587 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10588 } catch (ErrnoException e) { 10589 Slog.w(TAG, "Failed to rename", e); 10590 return false; 10591 } 10592 10593 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10594 Slog.w(TAG, "Failed to restorecon"); 10595 return false; 10596 } 10597 10598 // Reflect the rename internally 10599 codeFile = afterCodeFile; 10600 resourceFile = afterCodeFile; 10601 10602 // Reflect the rename in scanned details 10603 pkg.codePath = afterCodeFile.getAbsolutePath(); 10604 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10605 pkg.baseCodePath); 10606 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10607 pkg.splitCodePaths); 10608 10609 // Reflect the rename in app info 10610 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10611 pkg.applicationInfo.setCodePath(pkg.codePath); 10612 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10613 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10614 pkg.applicationInfo.setResourcePath(pkg.codePath); 10615 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10616 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10617 10618 return true; 10619 } 10620 10621 int doPostInstall(int status, int uid) { 10622 if (status != PackageManager.INSTALL_SUCCEEDED) { 10623 cleanUp(); 10624 } 10625 return status; 10626 } 10627 10628 @Override 10629 String getCodePath() { 10630 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10631 } 10632 10633 @Override 10634 String getResourcePath() { 10635 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10636 } 10637 10638 private boolean cleanUp() { 10639 if (codeFile == null || !codeFile.exists()) { 10640 return false; 10641 } 10642 10643 if (codeFile.isDirectory()) { 10644 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10645 } else { 10646 codeFile.delete(); 10647 } 10648 10649 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10650 resourceFile.delete(); 10651 } 10652 10653 return true; 10654 } 10655 10656 void cleanUpResourcesLI() { 10657 // Try enumerating all code paths before deleting 10658 List<String> allCodePaths = Collections.EMPTY_LIST; 10659 if (codeFile != null && codeFile.exists()) { 10660 try { 10661 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10662 allCodePaths = pkg.getAllCodePaths(); 10663 } catch (PackageParserException e) { 10664 // Ignored; we tried our best 10665 } 10666 } 10667 10668 cleanUp(); 10669 removeDexFiles(allCodePaths, instructionSets); 10670 } 10671 10672 boolean doPostDeleteLI(boolean delete) { 10673 // XXX err, shouldn't we respect the delete flag? 10674 cleanUpResourcesLI(); 10675 return true; 10676 } 10677 } 10678 10679 private boolean isAsecExternal(String cid) { 10680 final String asecPath = PackageHelper.getSdFilesystem(cid); 10681 return !asecPath.startsWith(mAsecInternalPath); 10682 } 10683 10684 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10685 PackageManagerException { 10686 if (copyRet < 0) { 10687 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10688 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10689 throw new PackageManagerException(copyRet, message); 10690 } 10691 } 10692 } 10693 10694 /** 10695 * Extract the MountService "container ID" from the full code path of an 10696 * .apk. 10697 */ 10698 static String cidFromCodePath(String fullCodePath) { 10699 int eidx = fullCodePath.lastIndexOf("/"); 10700 String subStr1 = fullCodePath.substring(0, eidx); 10701 int sidx = subStr1.lastIndexOf("/"); 10702 return subStr1.substring(sidx+1, eidx); 10703 } 10704 10705 /** 10706 * Logic to handle installation of ASEC applications, including copying and 10707 * renaming logic. 10708 */ 10709 class AsecInstallArgs extends InstallArgs { 10710 static final String RES_FILE_NAME = "pkg.apk"; 10711 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10712 10713 String cid; 10714 String packagePath; 10715 String resourcePath; 10716 10717 /** New install */ 10718 AsecInstallArgs(InstallParams params) { 10719 super(params.origin, params.move, params.observer, params.installFlags, 10720 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10721 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10722 } 10723 10724 /** Existing install */ 10725 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10726 boolean isExternal, boolean isForwardLocked) { 10727 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10728 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10729 instructionSets, null); 10730 // Hackily pretend we're still looking at a full code path 10731 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10732 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10733 } 10734 10735 // Extract cid from fullCodePath 10736 int eidx = fullCodePath.lastIndexOf("/"); 10737 String subStr1 = fullCodePath.substring(0, eidx); 10738 int sidx = subStr1.lastIndexOf("/"); 10739 cid = subStr1.substring(sidx+1, eidx); 10740 setMountPath(subStr1); 10741 } 10742 10743 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10744 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10745 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10746 instructionSets, null); 10747 this.cid = cid; 10748 setMountPath(PackageHelper.getSdDir(cid)); 10749 } 10750 10751 void createCopyFile() { 10752 cid = mInstallerService.allocateExternalStageCidLegacy(); 10753 } 10754 10755 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10756 if (origin.staged) { 10757 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10758 cid = origin.cid; 10759 setMountPath(PackageHelper.getSdDir(cid)); 10760 return PackageManager.INSTALL_SUCCEEDED; 10761 } 10762 10763 if (temp) { 10764 createCopyFile(); 10765 } else { 10766 /* 10767 * Pre-emptively destroy the container since it's destroyed if 10768 * copying fails due to it existing anyway. 10769 */ 10770 PackageHelper.destroySdDir(cid); 10771 } 10772 10773 final String newMountPath = imcs.copyPackageToContainer( 10774 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10775 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10776 10777 if (newMountPath != null) { 10778 setMountPath(newMountPath); 10779 return PackageManager.INSTALL_SUCCEEDED; 10780 } else { 10781 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10782 } 10783 } 10784 10785 @Override 10786 String getCodePath() { 10787 return packagePath; 10788 } 10789 10790 @Override 10791 String getResourcePath() { 10792 return resourcePath; 10793 } 10794 10795 int doPreInstall(int status) { 10796 if (status != PackageManager.INSTALL_SUCCEEDED) { 10797 // Destroy container 10798 PackageHelper.destroySdDir(cid); 10799 } else { 10800 boolean mounted = PackageHelper.isContainerMounted(cid); 10801 if (!mounted) { 10802 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10803 Process.SYSTEM_UID); 10804 if (newMountPath != null) { 10805 setMountPath(newMountPath); 10806 } else { 10807 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10808 } 10809 } 10810 } 10811 return status; 10812 } 10813 10814 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10815 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10816 String newMountPath = null; 10817 if (PackageHelper.isContainerMounted(cid)) { 10818 // Unmount the container 10819 if (!PackageHelper.unMountSdDir(cid)) { 10820 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10821 return false; 10822 } 10823 } 10824 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10825 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10826 " which might be stale. Will try to clean up."); 10827 // Clean up the stale container and proceed to recreate. 10828 if (!PackageHelper.destroySdDir(newCacheId)) { 10829 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10830 return false; 10831 } 10832 // Successfully cleaned up stale container. Try to rename again. 10833 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10834 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10835 + " inspite of cleaning it up."); 10836 return false; 10837 } 10838 } 10839 if (!PackageHelper.isContainerMounted(newCacheId)) { 10840 Slog.w(TAG, "Mounting container " + newCacheId); 10841 newMountPath = PackageHelper.mountSdDir(newCacheId, 10842 getEncryptKey(), Process.SYSTEM_UID); 10843 } else { 10844 newMountPath = PackageHelper.getSdDir(newCacheId); 10845 } 10846 if (newMountPath == null) { 10847 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10848 return false; 10849 } 10850 Log.i(TAG, "Succesfully renamed " + cid + 10851 " to " + newCacheId + 10852 " at new path: " + newMountPath); 10853 cid = newCacheId; 10854 10855 final File beforeCodeFile = new File(packagePath); 10856 setMountPath(newMountPath); 10857 final File afterCodeFile = new File(packagePath); 10858 10859 // Reflect the rename in scanned details 10860 pkg.codePath = afterCodeFile.getAbsolutePath(); 10861 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10862 pkg.baseCodePath); 10863 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10864 pkg.splitCodePaths); 10865 10866 // Reflect the rename in app info 10867 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10868 pkg.applicationInfo.setCodePath(pkg.codePath); 10869 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10870 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10871 pkg.applicationInfo.setResourcePath(pkg.codePath); 10872 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10873 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10874 10875 return true; 10876 } 10877 10878 private void setMountPath(String mountPath) { 10879 final File mountFile = new File(mountPath); 10880 10881 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10882 if (monolithicFile.exists()) { 10883 packagePath = monolithicFile.getAbsolutePath(); 10884 if (isFwdLocked()) { 10885 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10886 } else { 10887 resourcePath = packagePath; 10888 } 10889 } else { 10890 packagePath = mountFile.getAbsolutePath(); 10891 resourcePath = packagePath; 10892 } 10893 } 10894 10895 int doPostInstall(int status, int uid) { 10896 if (status != PackageManager.INSTALL_SUCCEEDED) { 10897 cleanUp(); 10898 } else { 10899 final int groupOwner; 10900 final String protectedFile; 10901 if (isFwdLocked()) { 10902 groupOwner = UserHandle.getSharedAppGid(uid); 10903 protectedFile = RES_FILE_NAME; 10904 } else { 10905 groupOwner = -1; 10906 protectedFile = null; 10907 } 10908 10909 if (uid < Process.FIRST_APPLICATION_UID 10910 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10911 Slog.e(TAG, "Failed to finalize " + cid); 10912 PackageHelper.destroySdDir(cid); 10913 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10914 } 10915 10916 boolean mounted = PackageHelper.isContainerMounted(cid); 10917 if (!mounted) { 10918 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10919 } 10920 } 10921 return status; 10922 } 10923 10924 private void cleanUp() { 10925 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10926 10927 // Destroy secure container 10928 PackageHelper.destroySdDir(cid); 10929 } 10930 10931 private List<String> getAllCodePaths() { 10932 final File codeFile = new File(getCodePath()); 10933 if (codeFile != null && codeFile.exists()) { 10934 try { 10935 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10936 return pkg.getAllCodePaths(); 10937 } catch (PackageParserException e) { 10938 // Ignored; we tried our best 10939 } 10940 } 10941 return Collections.EMPTY_LIST; 10942 } 10943 10944 void cleanUpResourcesLI() { 10945 // Enumerate all code paths before deleting 10946 cleanUpResourcesLI(getAllCodePaths()); 10947 } 10948 10949 private void cleanUpResourcesLI(List<String> allCodePaths) { 10950 cleanUp(); 10951 removeDexFiles(allCodePaths, instructionSets); 10952 } 10953 10954 String getPackageName() { 10955 return getAsecPackageName(cid); 10956 } 10957 10958 boolean doPostDeleteLI(boolean delete) { 10959 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10960 final List<String> allCodePaths = getAllCodePaths(); 10961 boolean mounted = PackageHelper.isContainerMounted(cid); 10962 if (mounted) { 10963 // Unmount first 10964 if (PackageHelper.unMountSdDir(cid)) { 10965 mounted = false; 10966 } 10967 } 10968 if (!mounted && delete) { 10969 cleanUpResourcesLI(allCodePaths); 10970 } 10971 return !mounted; 10972 } 10973 10974 @Override 10975 int doPreCopy() { 10976 if (isFwdLocked()) { 10977 if (!PackageHelper.fixSdPermissions(cid, 10978 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10979 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10980 } 10981 } 10982 10983 return PackageManager.INSTALL_SUCCEEDED; 10984 } 10985 10986 @Override 10987 int doPostCopy(int uid) { 10988 if (isFwdLocked()) { 10989 if (uid < Process.FIRST_APPLICATION_UID 10990 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10991 RES_FILE_NAME)) { 10992 Slog.e(TAG, "Failed to finalize " + cid); 10993 PackageHelper.destroySdDir(cid); 10994 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10995 } 10996 } 10997 10998 return PackageManager.INSTALL_SUCCEEDED; 10999 } 11000 } 11001 11002 /** 11003 * Logic to handle movement of existing installed applications. 11004 */ 11005 class MoveInstallArgs extends InstallArgs { 11006 private File codeFile; 11007 private File resourceFile; 11008 11009 /** New install */ 11010 MoveInstallArgs(InstallParams params) { 11011 super(params.origin, params.move, params.observer, params.installFlags, 11012 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 11013 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 11014 } 11015 11016 int copyApk(IMediaContainerService imcs, boolean temp) { 11017 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 11018 + move.fromUuid + " to " + move.toUuid); 11019 synchronized (mInstaller) { 11020 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 11021 move.dataAppName, move.appId, move.seinfo) != 0) { 11022 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 11023 } 11024 } 11025 11026 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 11027 resourceFile = codeFile; 11028 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 11029 11030 return PackageManager.INSTALL_SUCCEEDED; 11031 } 11032 11033 int doPreInstall(int status) { 11034 if (status != PackageManager.INSTALL_SUCCEEDED) { 11035 cleanUp(); 11036 } 11037 return status; 11038 } 11039 11040 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 11041 if (status != PackageManager.INSTALL_SUCCEEDED) { 11042 cleanUp(); 11043 return false; 11044 } 11045 11046 // Reflect the move in app info 11047 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 11048 pkg.applicationInfo.setCodePath(pkg.codePath); 11049 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 11050 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 11051 pkg.applicationInfo.setResourcePath(pkg.codePath); 11052 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 11053 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 11054 11055 return true; 11056 } 11057 11058 int doPostInstall(int status, int uid) { 11059 if (status != PackageManager.INSTALL_SUCCEEDED) { 11060 cleanUp(); 11061 } 11062 return status; 11063 } 11064 11065 @Override 11066 String getCodePath() { 11067 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 11068 } 11069 11070 @Override 11071 String getResourcePath() { 11072 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 11073 } 11074 11075 private boolean cleanUp() { 11076 if (codeFile == null || !codeFile.exists()) { 11077 return false; 11078 } 11079 11080 if (codeFile.isDirectory()) { 11081 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 11082 } else { 11083 codeFile.delete(); 11084 } 11085 11086 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 11087 resourceFile.delete(); 11088 } 11089 11090 return true; 11091 } 11092 11093 void cleanUpResourcesLI() { 11094 cleanUp(); 11095 } 11096 11097 boolean doPostDeleteLI(boolean delete) { 11098 // XXX err, shouldn't we respect the delete flag? 11099 cleanUpResourcesLI(); 11100 return true; 11101 } 11102 } 11103 11104 static String getAsecPackageName(String packageCid) { 11105 int idx = packageCid.lastIndexOf("-"); 11106 if (idx == -1) { 11107 return packageCid; 11108 } 11109 return packageCid.substring(0, idx); 11110 } 11111 11112 // Utility method used to create code paths based on package name and available index. 11113 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11114 String idxStr = ""; 11115 int idx = 1; 11116 // Fall back to default value of idx=1 if prefix is not 11117 // part of oldCodePath 11118 if (oldCodePath != null) { 11119 String subStr = oldCodePath; 11120 // Drop the suffix right away 11121 if (suffix != null && subStr.endsWith(suffix)) { 11122 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11123 } 11124 // If oldCodePath already contains prefix find out the 11125 // ending index to either increment or decrement. 11126 int sidx = subStr.lastIndexOf(prefix); 11127 if (sidx != -1) { 11128 subStr = subStr.substring(sidx + prefix.length()); 11129 if (subStr != null) { 11130 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11131 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11132 } 11133 try { 11134 idx = Integer.parseInt(subStr); 11135 if (idx <= 1) { 11136 idx++; 11137 } else { 11138 idx--; 11139 } 11140 } catch(NumberFormatException e) { 11141 } 11142 } 11143 } 11144 } 11145 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11146 return prefix + idxStr; 11147 } 11148 11149 private File getNextCodePath(File targetDir, String packageName) { 11150 int suffix = 1; 11151 File result; 11152 do { 11153 result = new File(targetDir, packageName + "-" + suffix); 11154 suffix++; 11155 } while (result.exists()); 11156 return result; 11157 } 11158 11159 // Utility method that returns the relative package path with respect 11160 // to the installation directory. Like say for /data/data/com.test-1.apk 11161 // string com.test-1 is returned. 11162 static String deriveCodePathName(String codePath) { 11163 if (codePath == null) { 11164 return null; 11165 } 11166 final File codeFile = new File(codePath); 11167 final String name = codeFile.getName(); 11168 if (codeFile.isDirectory()) { 11169 return name; 11170 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11171 final int lastDot = name.lastIndexOf('.'); 11172 return name.substring(0, lastDot); 11173 } else { 11174 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11175 return null; 11176 } 11177 } 11178 11179 class PackageInstalledInfo { 11180 String name; 11181 int uid; 11182 // The set of users that originally had this package installed. 11183 int[] origUsers; 11184 // The set of users that now have this package installed. 11185 int[] newUsers; 11186 PackageParser.Package pkg; 11187 int returnCode; 11188 String returnMsg; 11189 PackageRemovedInfo removedInfo; 11190 11191 public void setError(int code, String msg) { 11192 returnCode = code; 11193 returnMsg = msg; 11194 Slog.w(TAG, msg); 11195 } 11196 11197 public void setError(String msg, PackageParserException e) { 11198 returnCode = e.error; 11199 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11200 Slog.w(TAG, msg, e); 11201 } 11202 11203 public void setError(String msg, PackageManagerException e) { 11204 returnCode = e.error; 11205 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11206 Slog.w(TAG, msg, e); 11207 } 11208 11209 // In some error cases we want to convey more info back to the observer 11210 String origPackage; 11211 String origPermission; 11212 } 11213 11214 /* 11215 * Install a non-existing package. 11216 */ 11217 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11218 UserHandle user, String installerPackageName, String volumeUuid, 11219 PackageInstalledInfo res) { 11220 // Remember this for later, in case we need to rollback this install 11221 String pkgName = pkg.packageName; 11222 11223 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11224 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11225 UserHandle.USER_OWNER).exists(); 11226 synchronized(mPackages) { 11227 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11228 // A package with the same name is already installed, though 11229 // it has been renamed to an older name. The package we 11230 // are trying to install should be installed as an update to 11231 // the existing one, but that has not been requested, so bail. 11232 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11233 + " without first uninstalling package running as " 11234 + mSettings.mRenamedPackages.get(pkgName)); 11235 return; 11236 } 11237 if (mPackages.containsKey(pkgName)) { 11238 // Don't allow installation over an existing package with the same name. 11239 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11240 + " without first uninstalling."); 11241 return; 11242 } 11243 } 11244 11245 try { 11246 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11247 System.currentTimeMillis(), user); 11248 11249 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11250 // delete the partially installed application. the data directory will have to be 11251 // restored if it was already existing 11252 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11253 // remove package from internal structures. Note that we want deletePackageX to 11254 // delete the package data and cache directories that it created in 11255 // scanPackageLocked, unless those directories existed before we even tried to 11256 // install. 11257 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11258 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11259 res.removedInfo, true); 11260 } 11261 11262 } catch (PackageManagerException e) { 11263 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11264 } 11265 } 11266 11267 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11268 // Can't rotate keys during boot or if sharedUser. 11269 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11270 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11271 return false; 11272 } 11273 // app is using upgradeKeySets; make sure all are valid 11274 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11275 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11276 for (int i = 0; i < upgradeKeySets.length; i++) { 11277 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11278 Slog.wtf(TAG, "Package " 11279 + (oldPs.name != null ? oldPs.name : "<null>") 11280 + " contains upgrade-key-set reference to unknown key-set: " 11281 + upgradeKeySets[i] 11282 + " reverting to signatures check."); 11283 return false; 11284 } 11285 } 11286 return true; 11287 } 11288 11289 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11290 // Upgrade keysets are being used. Determine if new package has a superset of the 11291 // required keys. 11292 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11293 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11294 for (int i = 0; i < upgradeKeySets.length; i++) { 11295 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11296 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 11297 return true; 11298 } 11299 } 11300 return false; 11301 } 11302 11303 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11304 UserHandle user, String installerPackageName, String volumeUuid, 11305 PackageInstalledInfo res) { 11306 final PackageParser.Package oldPackage; 11307 final String pkgName = pkg.packageName; 11308 final int[] allUsers; 11309 final boolean[] perUserInstalled; 11310 final boolean weFroze; 11311 11312 // First find the old package info and check signatures 11313 synchronized(mPackages) { 11314 oldPackage = mPackages.get(pkgName); 11315 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11316 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11317 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11318 if(!checkUpgradeKeySetLP(ps, pkg)) { 11319 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11320 "New package not signed by keys specified by upgrade-keysets: " 11321 + pkgName); 11322 return; 11323 } 11324 } else { 11325 // default to original signature matching 11326 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11327 != PackageManager.SIGNATURE_MATCH) { 11328 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11329 "New package has a different signature: " + pkgName); 11330 return; 11331 } 11332 } 11333 11334 // In case of rollback, remember per-user/profile install state 11335 allUsers = sUserManager.getUserIds(); 11336 perUserInstalled = new boolean[allUsers.length]; 11337 for (int i = 0; i < allUsers.length; i++) { 11338 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11339 } 11340 11341 // Mark the app as frozen to prevent launching during the upgrade 11342 // process, and then kill all running instances 11343 if (!ps.frozen) { 11344 ps.frozen = true; 11345 weFroze = true; 11346 } else { 11347 weFroze = false; 11348 } 11349 } 11350 11351 // Now that we're guarded by frozen state, kill app during upgrade 11352 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11353 11354 try { 11355 boolean sysPkg = (isSystemApp(oldPackage)); 11356 if (sysPkg) { 11357 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11358 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11359 } else { 11360 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11361 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11362 } 11363 } finally { 11364 // Regardless of success or failure of upgrade steps above, always 11365 // unfreeze the package if we froze it 11366 if (weFroze) { 11367 unfreezePackage(pkgName); 11368 } 11369 } 11370 } 11371 11372 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11373 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11374 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11375 String volumeUuid, PackageInstalledInfo res) { 11376 String pkgName = deletedPackage.packageName; 11377 boolean deletedPkg = true; 11378 boolean updatedSettings = false; 11379 11380 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11381 + deletedPackage); 11382 long origUpdateTime; 11383 if (pkg.mExtras != null) { 11384 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11385 } else { 11386 origUpdateTime = 0; 11387 } 11388 11389 // First delete the existing package while retaining the data directory 11390 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11391 res.removedInfo, true)) { 11392 // If the existing package wasn't successfully deleted 11393 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11394 deletedPkg = false; 11395 } else { 11396 // Successfully deleted the old package; proceed with replace. 11397 11398 // If deleted package lived in a container, give users a chance to 11399 // relinquish resources before killing. 11400 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11401 if (DEBUG_INSTALL) { 11402 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11403 } 11404 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11405 final ArrayList<String> pkgList = new ArrayList<String>(1); 11406 pkgList.add(deletedPackage.applicationInfo.packageName); 11407 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11408 } 11409 11410 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11411 try { 11412 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11413 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11414 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11415 perUserInstalled, res, user); 11416 updatedSettings = true; 11417 } catch (PackageManagerException e) { 11418 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11419 } 11420 } 11421 11422 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11423 // remove package from internal structures. Note that we want deletePackageX to 11424 // delete the package data and cache directories that it created in 11425 // scanPackageLocked, unless those directories existed before we even tried to 11426 // install. 11427 if(updatedSettings) { 11428 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11429 deletePackageLI( 11430 pkgName, null, true, allUsers, perUserInstalled, 11431 PackageManager.DELETE_KEEP_DATA, 11432 res.removedInfo, true); 11433 } 11434 // Since we failed to install the new package we need to restore the old 11435 // package that we deleted. 11436 if (deletedPkg) { 11437 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11438 File restoreFile = new File(deletedPackage.codePath); 11439 // Parse old package 11440 boolean oldExternal = isExternal(deletedPackage); 11441 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11442 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11443 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11444 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11445 try { 11446 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11447 } catch (PackageManagerException e) { 11448 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11449 + e.getMessage()); 11450 return; 11451 } 11452 // Restore of old package succeeded. Update permissions. 11453 // writer 11454 synchronized (mPackages) { 11455 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11456 UPDATE_PERMISSIONS_ALL); 11457 // can downgrade to reader 11458 mSettings.writeLPr(); 11459 } 11460 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11461 } 11462 } 11463 } 11464 11465 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11466 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11467 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11468 String volumeUuid, PackageInstalledInfo res) { 11469 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11470 + ", old=" + deletedPackage); 11471 boolean disabledSystem = false; 11472 boolean updatedSettings = false; 11473 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11474 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11475 != 0) { 11476 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11477 } 11478 String packageName = deletedPackage.packageName; 11479 if (packageName == null) { 11480 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11481 "Attempt to delete null packageName."); 11482 return; 11483 } 11484 PackageParser.Package oldPkg; 11485 PackageSetting oldPkgSetting; 11486 // reader 11487 synchronized (mPackages) { 11488 oldPkg = mPackages.get(packageName); 11489 oldPkgSetting = mSettings.mPackages.get(packageName); 11490 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11491 (oldPkgSetting == null)) { 11492 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11493 "Couldn't find package:" + packageName + " information"); 11494 return; 11495 } 11496 } 11497 11498 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11499 res.removedInfo.removedPackage = packageName; 11500 // Remove existing system package 11501 removePackageLI(oldPkgSetting, true); 11502 // writer 11503 synchronized (mPackages) { 11504 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11505 if (!disabledSystem && deletedPackage != null) { 11506 // We didn't need to disable the .apk as a current system package, 11507 // which means we are replacing another update that is already 11508 // installed. We need to make sure to delete the older one's .apk. 11509 res.removedInfo.args = createInstallArgsForExisting(0, 11510 deletedPackage.applicationInfo.getCodePath(), 11511 deletedPackage.applicationInfo.getResourcePath(), 11512 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11513 } else { 11514 res.removedInfo.args = null; 11515 } 11516 } 11517 11518 // Successfully disabled the old package. Now proceed with re-installation 11519 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11520 11521 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11522 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11523 11524 PackageParser.Package newPackage = null; 11525 try { 11526 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11527 if (newPackage.mExtras != null) { 11528 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11529 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11530 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11531 11532 // is the update attempting to change shared user? that isn't going to work... 11533 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11534 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11535 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11536 + " to " + newPkgSetting.sharedUser); 11537 updatedSettings = true; 11538 } 11539 } 11540 11541 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11542 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11543 perUserInstalled, res, user); 11544 updatedSettings = true; 11545 } 11546 11547 } catch (PackageManagerException e) { 11548 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11549 } 11550 11551 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11552 // Re installation failed. Restore old information 11553 // Remove new pkg information 11554 if (newPackage != null) { 11555 removeInstalledPackageLI(newPackage, true); 11556 } 11557 // Add back the old system package 11558 try { 11559 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11560 } catch (PackageManagerException e) { 11561 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11562 } 11563 // Restore the old system information in Settings 11564 synchronized (mPackages) { 11565 if (disabledSystem) { 11566 mSettings.enableSystemPackageLPw(packageName); 11567 } 11568 if (updatedSettings) { 11569 mSettings.setInstallerPackageName(packageName, 11570 oldPkgSetting.installerPackageName); 11571 } 11572 mSettings.writeLPr(); 11573 } 11574 } 11575 } 11576 11577 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11578 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11579 UserHandle user) { 11580 String pkgName = newPackage.packageName; 11581 synchronized (mPackages) { 11582 //write settings. the installStatus will be incomplete at this stage. 11583 //note that the new package setting would have already been 11584 //added to mPackages. It hasn't been persisted yet. 11585 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11586 mSettings.writeLPr(); 11587 } 11588 11589 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11590 11591 synchronized (mPackages) { 11592 updatePermissionsLPw(newPackage.packageName, newPackage, 11593 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11594 ? UPDATE_PERMISSIONS_ALL : 0)); 11595 // For system-bundled packages, we assume that installing an upgraded version 11596 // of the package implies that the user actually wants to run that new code, 11597 // so we enable the package. 11598 PackageSetting ps = mSettings.mPackages.get(pkgName); 11599 if (ps != null) { 11600 if (isSystemApp(newPackage)) { 11601 // NB: implicit assumption that system package upgrades apply to all users 11602 if (DEBUG_INSTALL) { 11603 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11604 } 11605 if (res.origUsers != null) { 11606 for (int userHandle : res.origUsers) { 11607 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11608 userHandle, installerPackageName); 11609 } 11610 } 11611 // Also convey the prior install/uninstall state 11612 if (allUsers != null && perUserInstalled != null) { 11613 for (int i = 0; i < allUsers.length; i++) { 11614 if (DEBUG_INSTALL) { 11615 Slog.d(TAG, " user " + allUsers[i] 11616 + " => " + perUserInstalled[i]); 11617 } 11618 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11619 } 11620 // these install state changes will be persisted in the 11621 // upcoming call to mSettings.writeLPr(). 11622 } 11623 } 11624 // It's implied that when a user requests installation, they want the app to be 11625 // installed and enabled. 11626 int userId = user.getIdentifier(); 11627 if (userId != UserHandle.USER_ALL) { 11628 ps.setInstalled(true, userId); 11629 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11630 } 11631 } 11632 res.name = pkgName; 11633 res.uid = newPackage.applicationInfo.uid; 11634 res.pkg = newPackage; 11635 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11636 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11637 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11638 //to update install status 11639 mSettings.writeLPr(); 11640 } 11641 } 11642 11643 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11644 final int installFlags = args.installFlags; 11645 final String installerPackageName = args.installerPackageName; 11646 final String volumeUuid = args.volumeUuid; 11647 final File tmpPackageFile = new File(args.getCodePath()); 11648 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11649 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11650 || (args.volumeUuid != null)); 11651 boolean replace = false; 11652 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11653 // Result object to be returned 11654 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11655 11656 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11657 // Retrieve PackageSettings and parse package 11658 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11659 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11660 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11661 PackageParser pp = new PackageParser(); 11662 pp.setSeparateProcesses(mSeparateProcesses); 11663 pp.setDisplayMetrics(mMetrics); 11664 11665 final PackageParser.Package pkg; 11666 try { 11667 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11668 } catch (PackageParserException e) { 11669 res.setError("Failed parse during installPackageLI", e); 11670 return; 11671 } 11672 11673 // Mark that we have an install time CPU ABI override. 11674 pkg.cpuAbiOverride = args.abiOverride; 11675 11676 String pkgName = res.name = pkg.packageName; 11677 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11678 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11679 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11680 return; 11681 } 11682 } 11683 11684 try { 11685 pp.collectCertificates(pkg, parseFlags); 11686 pp.collectManifestDigest(pkg); 11687 } catch (PackageParserException e) { 11688 res.setError("Failed collect during installPackageLI", e); 11689 return; 11690 } 11691 11692 /* If the installer passed in a manifest digest, compare it now. */ 11693 if (args.manifestDigest != null) { 11694 if (DEBUG_INSTALL) { 11695 final String parsedManifest = pkg.manifestDigest == null ? "null" 11696 : pkg.manifestDigest.toString(); 11697 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11698 + parsedManifest); 11699 } 11700 11701 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11702 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11703 return; 11704 } 11705 } else if (DEBUG_INSTALL) { 11706 final String parsedManifest = pkg.manifestDigest == null 11707 ? "null" : pkg.manifestDigest.toString(); 11708 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11709 } 11710 11711 // Get rid of all references to package scan path via parser. 11712 pp = null; 11713 String oldCodePath = null; 11714 boolean systemApp = false; 11715 synchronized (mPackages) { 11716 // Check if installing already existing package 11717 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11718 String oldName = mSettings.mRenamedPackages.get(pkgName); 11719 if (pkg.mOriginalPackages != null 11720 && pkg.mOriginalPackages.contains(oldName) 11721 && mPackages.containsKey(oldName)) { 11722 // This package is derived from an original package, 11723 // and this device has been updating from that original 11724 // name. We must continue using the original name, so 11725 // rename the new package here. 11726 pkg.setPackageName(oldName); 11727 pkgName = pkg.packageName; 11728 replace = true; 11729 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11730 + oldName + " pkgName=" + pkgName); 11731 } else if (mPackages.containsKey(pkgName)) { 11732 // This package, under its official name, already exists 11733 // on the device; we should replace it. 11734 replace = true; 11735 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11736 } 11737 11738 // Prevent apps opting out from runtime permissions 11739 if (replace) { 11740 PackageParser.Package oldPackage = mPackages.get(pkgName); 11741 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11742 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11743 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11744 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11745 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11746 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11747 + " doesn't support runtime permissions but the old" 11748 + " target SDK " + oldTargetSdk + " does."); 11749 return; 11750 } 11751 } 11752 } 11753 11754 PackageSetting ps = mSettings.mPackages.get(pkgName); 11755 if (ps != null) { 11756 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11757 11758 // Quick sanity check that we're signed correctly if updating; 11759 // we'll check this again later when scanning, but we want to 11760 // bail early here before tripping over redefined permissions. 11761 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11762 if (!checkUpgradeKeySetLP(ps, pkg)) { 11763 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11764 + pkg.packageName + " upgrade keys do not match the " 11765 + "previously installed version"); 11766 return; 11767 } 11768 } else { 11769 try { 11770 verifySignaturesLP(ps, pkg); 11771 } catch (PackageManagerException e) { 11772 res.setError(e.error, e.getMessage()); 11773 return; 11774 } 11775 } 11776 11777 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11778 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11779 systemApp = (ps.pkg.applicationInfo.flags & 11780 ApplicationInfo.FLAG_SYSTEM) != 0; 11781 } 11782 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11783 } 11784 11785 // Check whether the newly-scanned package wants to define an already-defined perm 11786 int N = pkg.permissions.size(); 11787 for (int i = N-1; i >= 0; i--) { 11788 PackageParser.Permission perm = pkg.permissions.get(i); 11789 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11790 if (bp != null) { 11791 // If the defining package is signed with our cert, it's okay. This 11792 // also includes the "updating the same package" case, of course. 11793 // "updating same package" could also involve key-rotation. 11794 final boolean sigsOk; 11795 if (bp.sourcePackage.equals(pkg.packageName) 11796 && (bp.packageSetting instanceof PackageSetting) 11797 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11798 scanFlags))) { 11799 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11800 } else { 11801 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11802 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11803 } 11804 if (!sigsOk) { 11805 // If the owning package is the system itself, we log but allow 11806 // install to proceed; we fail the install on all other permission 11807 // redefinitions. 11808 if (!bp.sourcePackage.equals("android")) { 11809 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11810 + pkg.packageName + " attempting to redeclare permission " 11811 + perm.info.name + " already owned by " + bp.sourcePackage); 11812 res.origPermission = perm.info.name; 11813 res.origPackage = bp.sourcePackage; 11814 return; 11815 } else { 11816 Slog.w(TAG, "Package " + pkg.packageName 11817 + " attempting to redeclare system permission " 11818 + perm.info.name + "; ignoring new declaration"); 11819 pkg.permissions.remove(i); 11820 } 11821 } 11822 } 11823 } 11824 11825 } 11826 11827 if (systemApp && onExternal) { 11828 // Disable updates to system apps on sdcard 11829 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11830 "Cannot install updates to system apps on sdcard"); 11831 return; 11832 } 11833 11834 if (args.move != null) { 11835 // We did an in-place move, so dex is ready to roll 11836 scanFlags |= SCAN_NO_DEX; 11837 scanFlags |= SCAN_MOVE; 11838 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11839 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11840 scanFlags |= SCAN_NO_DEX; 11841 11842 try { 11843 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11844 true /* extract libs */); 11845 } catch (PackageManagerException pme) { 11846 Slog.e(TAG, "Error deriving application ABI", pme); 11847 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11848 return; 11849 } 11850 11851 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11852 int result = mPackageDexOptimizer 11853 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11854 false /* defer */, false /* inclDependencies */); 11855 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11856 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11857 return; 11858 } 11859 } 11860 11861 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11862 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11863 return; 11864 } 11865 11866 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11867 11868 if (replace) { 11869 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11870 installerPackageName, volumeUuid, res); 11871 } else { 11872 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11873 args.user, installerPackageName, volumeUuid, res); 11874 } 11875 synchronized (mPackages) { 11876 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11877 if (ps != null) { 11878 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11879 } 11880 } 11881 } 11882 11883 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11884 if (mIntentFilterVerifierComponent == null) { 11885 Slog.w(TAG, "No IntentFilter verification will not be done as " 11886 + "there is no IntentFilterVerifier available!"); 11887 return; 11888 } 11889 11890 final int verifierUid = getPackageUid( 11891 mIntentFilterVerifierComponent.getPackageName(), 11892 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11893 11894 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11895 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11896 msg.obj = pkg; 11897 msg.arg1 = userId; 11898 msg.arg2 = verifierUid; 11899 11900 mHandler.sendMessage(msg); 11901 } 11902 11903 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11904 PackageParser.Package pkg) { 11905 int size = pkg.activities.size(); 11906 if (size == 0) { 11907 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11908 "No activity, so no need to verify any IntentFilter!"); 11909 return; 11910 } 11911 11912 final boolean hasDomainURLs = hasDomainURLs(pkg); 11913 if (!hasDomainURLs) { 11914 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11915 "No domain URLs, so no need to verify any IntentFilter!"); 11916 return; 11917 } 11918 11919 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11920 + " if any IntentFilter from the " + size 11921 + " Activities needs verification ..."); 11922 11923 final int verificationId = mIntentFilterVerificationToken++; 11924 int count = 0; 11925 final String packageName = pkg.packageName; 11926 boolean needToVerify = false; 11927 11928 synchronized (mPackages) { 11929 // If any filters need to be verified, then all need to be. 11930 for (PackageParser.Activity a : pkg.activities) { 11931 for (ActivityIntentInfo filter : a.intents) { 11932 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11933 if (DEBUG_DOMAIN_VERIFICATION) { 11934 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11935 } 11936 needToVerify = true; 11937 break; 11938 } 11939 } 11940 } 11941 if (needToVerify) { 11942 for (PackageParser.Activity a : pkg.activities) { 11943 for (ActivityIntentInfo filter : a.intents) { 11944 boolean needsFilterVerification = filter.hasWebDataURI(); 11945 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11946 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11947 "Verification needed for IntentFilter:" + filter.toString()); 11948 mIntentFilterVerifier.addOneIntentFilterVerification( 11949 verifierUid, userId, verificationId, filter, packageName); 11950 count++; 11951 } 11952 } 11953 } 11954 } 11955 } 11956 11957 if (count > 0) { 11958 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11959 + " IntentFilter verification" + (count > 1 ? "s" : "") 11960 + " for userId:" + userId); 11961 mIntentFilterVerifier.startVerifications(userId); 11962 } else { 11963 if (DEBUG_DOMAIN_VERIFICATION) { 11964 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11965 } 11966 } 11967 } 11968 11969 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11970 final ComponentName cn = filter.activity.getComponentName(); 11971 final String packageName = cn.getPackageName(); 11972 11973 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11974 packageName); 11975 if (ivi == null) { 11976 return true; 11977 } 11978 int status = ivi.getStatus(); 11979 switch (status) { 11980 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11981 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11982 return true; 11983 11984 default: 11985 // Nothing to do 11986 return false; 11987 } 11988 } 11989 11990 private static boolean isMultiArch(PackageSetting ps) { 11991 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11992 } 11993 11994 private static boolean isMultiArch(ApplicationInfo info) { 11995 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11996 } 11997 11998 private static boolean isExternal(PackageParser.Package pkg) { 11999 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12000 } 12001 12002 private static boolean isExternal(PackageSetting ps) { 12003 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12004 } 12005 12006 private static boolean isExternal(ApplicationInfo info) { 12007 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 12008 } 12009 12010 private static boolean isSystemApp(PackageParser.Package pkg) { 12011 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12012 } 12013 12014 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 12015 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 12016 } 12017 12018 private static boolean hasDomainURLs(PackageParser.Package pkg) { 12019 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 12020 } 12021 12022 private static boolean isSystemApp(PackageSetting ps) { 12023 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 12024 } 12025 12026 private static boolean isUpdatedSystemApp(PackageSetting ps) { 12027 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 12028 } 12029 12030 private int packageFlagsToInstallFlags(PackageSetting ps) { 12031 int installFlags = 0; 12032 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 12033 // This existing package was an external ASEC install when we have 12034 // the external flag without a UUID 12035 installFlags |= PackageManager.INSTALL_EXTERNAL; 12036 } 12037 if (ps.isForwardLocked()) { 12038 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12039 } 12040 return installFlags; 12041 } 12042 12043 private void deleteTempPackageFiles() { 12044 final FilenameFilter filter = new FilenameFilter() { 12045 public boolean accept(File dir, String name) { 12046 return name.startsWith("vmdl") && name.endsWith(".tmp"); 12047 } 12048 }; 12049 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 12050 file.delete(); 12051 } 12052 } 12053 12054 @Override 12055 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 12056 int flags) { 12057 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 12058 flags); 12059 } 12060 12061 @Override 12062 public void deletePackage(final String packageName, 12063 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 12064 mContext.enforceCallingOrSelfPermission( 12065 android.Manifest.permission.DELETE_PACKAGES, null); 12066 final int uid = Binder.getCallingUid(); 12067 if (UserHandle.getUserId(uid) != userId) { 12068 mContext.enforceCallingPermission( 12069 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 12070 "deletePackage for user " + userId); 12071 } 12072 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 12073 try { 12074 observer.onPackageDeleted(packageName, 12075 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 12076 } catch (RemoteException re) { 12077 } 12078 return; 12079 } 12080 12081 boolean uninstallBlocked = false; 12082 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 12083 int[] users = sUserManager.getUserIds(); 12084 for (int i = 0; i < users.length; ++i) { 12085 if (getBlockUninstallForUser(packageName, users[i])) { 12086 uninstallBlocked = true; 12087 break; 12088 } 12089 } 12090 } else { 12091 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12092 } 12093 if (uninstallBlocked) { 12094 try { 12095 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12096 null); 12097 } catch (RemoteException re) { 12098 } 12099 return; 12100 } 12101 12102 if (DEBUG_REMOVE) { 12103 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12104 } 12105 // Queue up an async operation since the package deletion may take a little while. 12106 mHandler.post(new Runnable() { 12107 public void run() { 12108 mHandler.removeCallbacks(this); 12109 final int returnCode = deletePackageX(packageName, userId, flags); 12110 if (observer != null) { 12111 try { 12112 observer.onPackageDeleted(packageName, returnCode, null); 12113 } catch (RemoteException e) { 12114 Log.i(TAG, "Observer no longer exists."); 12115 } //end catch 12116 } //end if 12117 } //end run 12118 }); 12119 } 12120 12121 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12122 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12123 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12124 try { 12125 if (dpm != null) { 12126 if (dpm.isDeviceOwner(packageName)) { 12127 return true; 12128 } 12129 int[] users; 12130 if (userId == UserHandle.USER_ALL) { 12131 users = sUserManager.getUserIds(); 12132 } else { 12133 users = new int[]{userId}; 12134 } 12135 for (int i = 0; i < users.length; ++i) { 12136 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12137 return true; 12138 } 12139 } 12140 } 12141 } catch (RemoteException e) { 12142 } 12143 return false; 12144 } 12145 12146 /** 12147 * This method is an internal method that could be get invoked either 12148 * to delete an installed package or to clean up a failed installation. 12149 * After deleting an installed package, a broadcast is sent to notify any 12150 * listeners that the package has been installed. For cleaning up a failed 12151 * installation, the broadcast is not necessary since the package's 12152 * installation wouldn't have sent the initial broadcast either 12153 * The key steps in deleting a package are 12154 * deleting the package information in internal structures like mPackages, 12155 * deleting the packages base directories through installd 12156 * updating mSettings to reflect current status 12157 * persisting settings for later use 12158 * sending a broadcast if necessary 12159 */ 12160 private int deletePackageX(String packageName, int userId, int flags) { 12161 final PackageRemovedInfo info = new PackageRemovedInfo(); 12162 final boolean res; 12163 12164 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12165 ? UserHandle.ALL : new UserHandle(userId); 12166 12167 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12168 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12169 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12170 } 12171 12172 boolean removedForAllUsers = false; 12173 boolean systemUpdate = false; 12174 12175 // for the uninstall-updates case and restricted profiles, remember the per- 12176 // userhandle installed state 12177 int[] allUsers; 12178 boolean[] perUserInstalled; 12179 synchronized (mPackages) { 12180 PackageSetting ps = mSettings.mPackages.get(packageName); 12181 allUsers = sUserManager.getUserIds(); 12182 perUserInstalled = new boolean[allUsers.length]; 12183 for (int i = 0; i < allUsers.length; i++) { 12184 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12185 } 12186 } 12187 12188 synchronized (mInstallLock) { 12189 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12190 res = deletePackageLI(packageName, removeForUser, 12191 true, allUsers, perUserInstalled, 12192 flags | REMOVE_CHATTY, info, true); 12193 systemUpdate = info.isRemovedPackageSystemUpdate; 12194 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12195 removedForAllUsers = true; 12196 } 12197 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12198 + " removedForAllUsers=" + removedForAllUsers); 12199 } 12200 12201 if (res) { 12202 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12203 12204 // If the removed package was a system update, the old system package 12205 // was re-enabled; we need to broadcast this information 12206 if (systemUpdate) { 12207 Bundle extras = new Bundle(1); 12208 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12209 ? info.removedAppId : info.uid); 12210 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12211 12212 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12213 extras, null, null, null); 12214 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12215 extras, null, null, null); 12216 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12217 null, packageName, null, null); 12218 } 12219 } 12220 // Force a gc here. 12221 Runtime.getRuntime().gc(); 12222 // Delete the resources here after sending the broadcast to let 12223 // other processes clean up before deleting resources. 12224 if (info.args != null) { 12225 synchronized (mInstallLock) { 12226 info.args.doPostDeleteLI(true); 12227 } 12228 } 12229 12230 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12231 } 12232 12233 class PackageRemovedInfo { 12234 String removedPackage; 12235 int uid = -1; 12236 int removedAppId = -1; 12237 int[] removedUsers = null; 12238 boolean isRemovedPackageSystemUpdate = false; 12239 // Clean up resources deleted packages. 12240 InstallArgs args = null; 12241 12242 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12243 Bundle extras = new Bundle(1); 12244 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12245 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12246 if (replacing) { 12247 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12248 } 12249 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12250 if (removedPackage != null) { 12251 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12252 extras, null, null, removedUsers); 12253 if (fullRemove && !replacing) { 12254 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12255 extras, null, null, removedUsers); 12256 } 12257 } 12258 if (removedAppId >= 0) { 12259 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12260 removedUsers); 12261 } 12262 } 12263 } 12264 12265 /* 12266 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12267 * flag is not set, the data directory is removed as well. 12268 * make sure this flag is set for partially installed apps. If not its meaningless to 12269 * delete a partially installed application. 12270 */ 12271 private void removePackageDataLI(PackageSetting ps, 12272 int[] allUserHandles, boolean[] perUserInstalled, 12273 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12274 String packageName = ps.name; 12275 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12276 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12277 // Retrieve object to delete permissions for shared user later on 12278 final PackageSetting deletedPs; 12279 // reader 12280 synchronized (mPackages) { 12281 deletedPs = mSettings.mPackages.get(packageName); 12282 if (outInfo != null) { 12283 outInfo.removedPackage = packageName; 12284 outInfo.removedUsers = deletedPs != null 12285 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12286 : null; 12287 } 12288 } 12289 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12290 removeDataDirsLI(ps.volumeUuid, packageName); 12291 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12292 } 12293 // writer 12294 synchronized (mPackages) { 12295 if (deletedPs != null) { 12296 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12297 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12298 clearDefaultBrowserIfNeeded(packageName); 12299 if (outInfo != null) { 12300 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12301 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12302 } 12303 updatePermissionsLPw(deletedPs.name, null, 0); 12304 if (deletedPs.sharedUser != null) { 12305 // Remove permissions associated with package. Since runtime 12306 // permissions are per user we have to kill the removed package 12307 // or packages running under the shared user of the removed 12308 // package if revoking the permissions requested only by the removed 12309 // package is successful and this causes a change in gids. 12310 for (int userId : UserManagerService.getInstance().getUserIds()) { 12311 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12312 userId); 12313 if (userIdToKill == UserHandle.USER_ALL 12314 || userIdToKill >= UserHandle.USER_OWNER) { 12315 // If gids changed for this user, kill all affected packages. 12316 mHandler.post(new Runnable() { 12317 @Override 12318 public void run() { 12319 // This has to happen with no lock held. 12320 killSettingPackagesForUser(deletedPs, userIdToKill, 12321 KILL_APP_REASON_GIDS_CHANGED); 12322 } 12323 }); 12324 break; 12325 } 12326 } 12327 } 12328 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12329 } 12330 // make sure to preserve per-user disabled state if this removal was just 12331 // a downgrade of a system app to the factory package 12332 if (allUserHandles != null && perUserInstalled != null) { 12333 if (DEBUG_REMOVE) { 12334 Slog.d(TAG, "Propagating install state across downgrade"); 12335 } 12336 for (int i = 0; i < allUserHandles.length; i++) { 12337 if (DEBUG_REMOVE) { 12338 Slog.d(TAG, " user " + allUserHandles[i] 12339 + " => " + perUserInstalled[i]); 12340 } 12341 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12342 } 12343 } 12344 } 12345 // can downgrade to reader 12346 if (writeSettings) { 12347 // Save settings now 12348 mSettings.writeLPr(); 12349 } 12350 } 12351 if (outInfo != null) { 12352 // A user ID was deleted here. Go through all users and remove it 12353 // from KeyStore. 12354 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12355 } 12356 } 12357 12358 static boolean locationIsPrivileged(File path) { 12359 try { 12360 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12361 .getCanonicalPath(); 12362 return path.getCanonicalPath().startsWith(privilegedAppDir); 12363 } catch (IOException e) { 12364 Slog.e(TAG, "Unable to access code path " + path); 12365 } 12366 return false; 12367 } 12368 12369 /* 12370 * Tries to delete system package. 12371 */ 12372 private boolean deleteSystemPackageLI(PackageSetting newPs, 12373 int[] allUserHandles, boolean[] perUserInstalled, 12374 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12375 final boolean applyUserRestrictions 12376 = (allUserHandles != null) && (perUserInstalled != null); 12377 PackageSetting disabledPs = null; 12378 // Confirm if the system package has been updated 12379 // An updated system app can be deleted. This will also have to restore 12380 // the system pkg from system partition 12381 // reader 12382 synchronized (mPackages) { 12383 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12384 } 12385 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12386 + " disabledPs=" + disabledPs); 12387 if (disabledPs == null) { 12388 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12389 return false; 12390 } else if (DEBUG_REMOVE) { 12391 Slog.d(TAG, "Deleting system pkg from data partition"); 12392 } 12393 if (DEBUG_REMOVE) { 12394 if (applyUserRestrictions) { 12395 Slog.d(TAG, "Remembering install states:"); 12396 for (int i = 0; i < allUserHandles.length; i++) { 12397 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12398 } 12399 } 12400 } 12401 // Delete the updated package 12402 outInfo.isRemovedPackageSystemUpdate = true; 12403 if (disabledPs.versionCode < newPs.versionCode) { 12404 // Delete data for downgrades 12405 flags &= ~PackageManager.DELETE_KEEP_DATA; 12406 } else { 12407 // Preserve data by setting flag 12408 flags |= PackageManager.DELETE_KEEP_DATA; 12409 } 12410 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12411 allUserHandles, perUserInstalled, outInfo, writeSettings); 12412 if (!ret) { 12413 return false; 12414 } 12415 // writer 12416 synchronized (mPackages) { 12417 // Reinstate the old system package 12418 mSettings.enableSystemPackageLPw(newPs.name); 12419 // Remove any native libraries from the upgraded package. 12420 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12421 } 12422 // Install the system package 12423 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12424 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12425 if (locationIsPrivileged(disabledPs.codePath)) { 12426 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12427 } 12428 12429 final PackageParser.Package newPkg; 12430 try { 12431 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12432 } catch (PackageManagerException e) { 12433 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12434 return false; 12435 } 12436 12437 // writer 12438 synchronized (mPackages) { 12439 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12440 updatePermissionsLPw(newPkg.packageName, newPkg, 12441 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12442 if (applyUserRestrictions) { 12443 if (DEBUG_REMOVE) { 12444 Slog.d(TAG, "Propagating install state across reinstall"); 12445 } 12446 for (int i = 0; i < allUserHandles.length; i++) { 12447 if (DEBUG_REMOVE) { 12448 Slog.d(TAG, " user " + allUserHandles[i] 12449 + " => " + perUserInstalled[i]); 12450 } 12451 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12452 } 12453 // Regardless of writeSettings we need to ensure that this restriction 12454 // state propagation is persisted 12455 mSettings.writeAllUsersPackageRestrictionsLPr(); 12456 } 12457 // can downgrade to reader here 12458 if (writeSettings) { 12459 mSettings.writeLPr(); 12460 } 12461 } 12462 return true; 12463 } 12464 12465 private boolean deleteInstalledPackageLI(PackageSetting ps, 12466 boolean deleteCodeAndResources, int flags, 12467 int[] allUserHandles, boolean[] perUserInstalled, 12468 PackageRemovedInfo outInfo, boolean writeSettings) { 12469 if (outInfo != null) { 12470 outInfo.uid = ps.appId; 12471 } 12472 12473 // Delete package data from internal structures and also remove data if flag is set 12474 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12475 12476 // Delete application code and resources 12477 if (deleteCodeAndResources && (outInfo != null)) { 12478 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12479 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12480 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12481 } 12482 return true; 12483 } 12484 12485 @Override 12486 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12487 int userId) { 12488 mContext.enforceCallingOrSelfPermission( 12489 android.Manifest.permission.DELETE_PACKAGES, null); 12490 synchronized (mPackages) { 12491 PackageSetting ps = mSettings.mPackages.get(packageName); 12492 if (ps == null) { 12493 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12494 return false; 12495 } 12496 if (!ps.getInstalled(userId)) { 12497 // Can't block uninstall for an app that is not installed or enabled. 12498 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12499 return false; 12500 } 12501 ps.setBlockUninstall(blockUninstall, userId); 12502 mSettings.writePackageRestrictionsLPr(userId); 12503 } 12504 return true; 12505 } 12506 12507 @Override 12508 public boolean getBlockUninstallForUser(String packageName, int userId) { 12509 synchronized (mPackages) { 12510 PackageSetting ps = mSettings.mPackages.get(packageName); 12511 if (ps == null) { 12512 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12513 return false; 12514 } 12515 return ps.getBlockUninstall(userId); 12516 } 12517 } 12518 12519 /* 12520 * This method handles package deletion in general 12521 */ 12522 private boolean deletePackageLI(String packageName, UserHandle user, 12523 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12524 int flags, PackageRemovedInfo outInfo, 12525 boolean writeSettings) { 12526 if (packageName == null) { 12527 Slog.w(TAG, "Attempt to delete null packageName."); 12528 return false; 12529 } 12530 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12531 PackageSetting ps; 12532 boolean dataOnly = false; 12533 int removeUser = -1; 12534 int appId = -1; 12535 synchronized (mPackages) { 12536 ps = mSettings.mPackages.get(packageName); 12537 if (ps == null) { 12538 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12539 return false; 12540 } 12541 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12542 && user.getIdentifier() != UserHandle.USER_ALL) { 12543 // The caller is asking that the package only be deleted for a single 12544 // user. To do this, we just mark its uninstalled state and delete 12545 // its data. If this is a system app, we only allow this to happen if 12546 // they have set the special DELETE_SYSTEM_APP which requests different 12547 // semantics than normal for uninstalling system apps. 12548 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12549 ps.setUserState(user.getIdentifier(), 12550 COMPONENT_ENABLED_STATE_DEFAULT, 12551 false, //installed 12552 true, //stopped 12553 true, //notLaunched 12554 false, //hidden 12555 null, null, null, 12556 false, // blockUninstall 12557 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12558 if (!isSystemApp(ps)) { 12559 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12560 // Other user still have this package installed, so all 12561 // we need to do is clear this user's data and save that 12562 // it is uninstalled. 12563 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12564 removeUser = user.getIdentifier(); 12565 appId = ps.appId; 12566 scheduleWritePackageRestrictionsLocked(removeUser); 12567 } else { 12568 // We need to set it back to 'installed' so the uninstall 12569 // broadcasts will be sent correctly. 12570 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12571 ps.setInstalled(true, user.getIdentifier()); 12572 } 12573 } else { 12574 // This is a system app, so we assume that the 12575 // other users still have this package installed, so all 12576 // we need to do is clear this user's data and save that 12577 // it is uninstalled. 12578 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12579 removeUser = user.getIdentifier(); 12580 appId = ps.appId; 12581 scheduleWritePackageRestrictionsLocked(removeUser); 12582 } 12583 } 12584 } 12585 12586 if (removeUser >= 0) { 12587 // From above, we determined that we are deleting this only 12588 // for a single user. Continue the work here. 12589 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12590 if (outInfo != null) { 12591 outInfo.removedPackage = packageName; 12592 outInfo.removedAppId = appId; 12593 outInfo.removedUsers = new int[] {removeUser}; 12594 } 12595 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12596 removeKeystoreDataIfNeeded(removeUser, appId); 12597 schedulePackageCleaning(packageName, removeUser, false); 12598 synchronized (mPackages) { 12599 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12600 scheduleWritePackageRestrictionsLocked(removeUser); 12601 } 12602 revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(), 12603 removeUser); 12604 } 12605 return true; 12606 } 12607 12608 if (dataOnly) { 12609 // Delete application data first 12610 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12611 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12612 return true; 12613 } 12614 12615 boolean ret = false; 12616 if (isSystemApp(ps)) { 12617 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12618 // When an updated system application is deleted we delete the existing resources as well and 12619 // fall back to existing code in system partition 12620 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12621 flags, outInfo, writeSettings); 12622 } else { 12623 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12624 // Kill application pre-emptively especially for apps on sd. 12625 killApplication(packageName, ps.appId, "uninstall pkg"); 12626 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12627 allUserHandles, perUserInstalled, 12628 outInfo, writeSettings); 12629 } 12630 12631 return ret; 12632 } 12633 12634 private final class ClearStorageConnection implements ServiceConnection { 12635 IMediaContainerService mContainerService; 12636 12637 @Override 12638 public void onServiceConnected(ComponentName name, IBinder service) { 12639 synchronized (this) { 12640 mContainerService = IMediaContainerService.Stub.asInterface(service); 12641 notifyAll(); 12642 } 12643 } 12644 12645 @Override 12646 public void onServiceDisconnected(ComponentName name) { 12647 } 12648 } 12649 12650 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12651 final boolean mounted; 12652 if (Environment.isExternalStorageEmulated()) { 12653 mounted = true; 12654 } else { 12655 final String status = Environment.getExternalStorageState(); 12656 12657 mounted = status.equals(Environment.MEDIA_MOUNTED) 12658 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12659 } 12660 12661 if (!mounted) { 12662 return; 12663 } 12664 12665 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12666 int[] users; 12667 if (userId == UserHandle.USER_ALL) { 12668 users = sUserManager.getUserIds(); 12669 } else { 12670 users = new int[] { userId }; 12671 } 12672 final ClearStorageConnection conn = new ClearStorageConnection(); 12673 if (mContext.bindServiceAsUser( 12674 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12675 try { 12676 for (int curUser : users) { 12677 long timeout = SystemClock.uptimeMillis() + 5000; 12678 synchronized (conn) { 12679 long now = SystemClock.uptimeMillis(); 12680 while (conn.mContainerService == null && now < timeout) { 12681 try { 12682 conn.wait(timeout - now); 12683 } catch (InterruptedException e) { 12684 } 12685 } 12686 } 12687 if (conn.mContainerService == null) { 12688 return; 12689 } 12690 12691 final UserEnvironment userEnv = new UserEnvironment(curUser); 12692 clearDirectory(conn.mContainerService, 12693 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12694 if (allData) { 12695 clearDirectory(conn.mContainerService, 12696 userEnv.buildExternalStorageAppDataDirs(packageName)); 12697 clearDirectory(conn.mContainerService, 12698 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12699 } 12700 } 12701 } finally { 12702 mContext.unbindService(conn); 12703 } 12704 } 12705 } 12706 12707 @Override 12708 public void clearApplicationUserData(final String packageName, 12709 final IPackageDataObserver observer, final int userId) { 12710 mContext.enforceCallingOrSelfPermission( 12711 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12712 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12713 // Queue up an async operation since the package deletion may take a little while. 12714 mHandler.post(new Runnable() { 12715 public void run() { 12716 mHandler.removeCallbacks(this); 12717 final boolean succeeded; 12718 synchronized (mInstallLock) { 12719 succeeded = clearApplicationUserDataLI(packageName, userId); 12720 } 12721 clearExternalStorageDataSync(packageName, userId, true); 12722 if (succeeded) { 12723 // invoke DeviceStorageMonitor's update method to clear any notifications 12724 DeviceStorageMonitorInternal 12725 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12726 if (dsm != null) { 12727 dsm.checkMemory(); 12728 } 12729 } 12730 if(observer != null) { 12731 try { 12732 observer.onRemoveCompleted(packageName, succeeded); 12733 } catch (RemoteException e) { 12734 Log.i(TAG, "Observer no longer exists."); 12735 } 12736 } //end if observer 12737 } //end run 12738 }); 12739 } 12740 12741 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12742 if (packageName == null) { 12743 Slog.w(TAG, "Attempt to delete null packageName."); 12744 return false; 12745 } 12746 12747 // Try finding details about the requested package 12748 PackageParser.Package pkg; 12749 synchronized (mPackages) { 12750 pkg = mPackages.get(packageName); 12751 if (pkg == null) { 12752 final PackageSetting ps = mSettings.mPackages.get(packageName); 12753 if (ps != null) { 12754 pkg = ps.pkg; 12755 } 12756 } 12757 12758 if (pkg == null) { 12759 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12760 return false; 12761 } 12762 12763 PackageSetting ps = (PackageSetting) pkg.mExtras; 12764 PermissionsState permissionsState = ps.getPermissionsState(); 12765 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12766 } 12767 12768 // Always delete data directories for package, even if we found no other 12769 // record of app. This helps users recover from UID mismatches without 12770 // resorting to a full data wipe. 12771 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12772 if (retCode < 0) { 12773 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12774 return false; 12775 } 12776 12777 final int appId = pkg.applicationInfo.uid; 12778 removeKeystoreDataIfNeeded(userId, appId); 12779 12780 // Create a native library symlink only if we have native libraries 12781 // and if the native libraries are 32 bit libraries. We do not provide 12782 // this symlink for 64 bit libraries. 12783 if (pkg.applicationInfo.primaryCpuAbi != null && 12784 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12785 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12786 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12787 nativeLibPath, userId) < 0) { 12788 Slog.w(TAG, "Failed linking native library dir"); 12789 return false; 12790 } 12791 } 12792 12793 return true; 12794 } 12795 12796 12797 /** 12798 * Revokes granted runtime permissions and clears resettable flags 12799 * which are flags that can be set by a user interaction. 12800 * 12801 * @param permissionsState The permission state to reset. 12802 * @param userId The device user for which to do a reset. 12803 */ 12804 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12805 PermissionsState permissionsState, int userId) { 12806 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12807 | PackageManager.FLAG_PERMISSION_USER_FIXED 12808 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12809 12810 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags); 12811 } 12812 12813 /** 12814 * Revokes granted runtime permissions and clears all flags. 12815 * 12816 * @param permissionsState The permission state to reset. 12817 * @param userId The device user for which to do a reset. 12818 */ 12819 private void revokeRuntimePermissionsAndClearAllFlagsLocked( 12820 PermissionsState permissionsState, int userId) { 12821 revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, 12822 PackageManager.MASK_PERMISSION_FLAGS); 12823 } 12824 12825 /** 12826 * Revokes granted runtime permissions and clears certain flags. 12827 * 12828 * @param permissionsState The permission state to reset. 12829 * @param userId The device user for which to do a reset. 12830 * @param flags The flags that is going to be reset. 12831 */ 12832 private void revokeRuntimePermissionsAndClearFlagsLocked( 12833 PermissionsState permissionsState, int userId, int flags) { 12834 boolean needsWrite = false; 12835 12836 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12837 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12838 if (bp != null) { 12839 permissionsState.revokeRuntimePermission(bp, userId); 12840 permissionsState.updatePermissionFlags(bp, userId, flags, 0); 12841 needsWrite = true; 12842 } 12843 } 12844 12845 // Ensure default permissions are never cleared. 12846 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 12847 12848 if (needsWrite) { 12849 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12850 } 12851 } 12852 12853 /** 12854 * Remove entries from the keystore daemon. Will only remove it if the 12855 * {@code appId} is valid. 12856 */ 12857 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12858 if (appId < 0) { 12859 return; 12860 } 12861 12862 final KeyStore keyStore = KeyStore.getInstance(); 12863 if (keyStore != null) { 12864 if (userId == UserHandle.USER_ALL) { 12865 for (final int individual : sUserManager.getUserIds()) { 12866 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12867 } 12868 } else { 12869 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12870 } 12871 } else { 12872 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12873 } 12874 } 12875 12876 @Override 12877 public void deleteApplicationCacheFiles(final String packageName, 12878 final IPackageDataObserver observer) { 12879 mContext.enforceCallingOrSelfPermission( 12880 android.Manifest.permission.DELETE_CACHE_FILES, null); 12881 // Queue up an async operation since the package deletion may take a little while. 12882 final int userId = UserHandle.getCallingUserId(); 12883 mHandler.post(new Runnable() { 12884 public void run() { 12885 mHandler.removeCallbacks(this); 12886 final boolean succeded; 12887 synchronized (mInstallLock) { 12888 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12889 } 12890 clearExternalStorageDataSync(packageName, userId, false); 12891 if (observer != null) { 12892 try { 12893 observer.onRemoveCompleted(packageName, succeded); 12894 } catch (RemoteException e) { 12895 Log.i(TAG, "Observer no longer exists."); 12896 } 12897 } //end if observer 12898 } //end run 12899 }); 12900 } 12901 12902 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12903 if (packageName == null) { 12904 Slog.w(TAG, "Attempt to delete null packageName."); 12905 return false; 12906 } 12907 PackageParser.Package p; 12908 synchronized (mPackages) { 12909 p = mPackages.get(packageName); 12910 } 12911 if (p == null) { 12912 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12913 return false; 12914 } 12915 final ApplicationInfo applicationInfo = p.applicationInfo; 12916 if (applicationInfo == null) { 12917 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12918 return false; 12919 } 12920 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12921 if (retCode < 0) { 12922 Slog.w(TAG, "Couldn't remove cache files for package: " 12923 + packageName + " u" + userId); 12924 return false; 12925 } 12926 return true; 12927 } 12928 12929 @Override 12930 public void getPackageSizeInfo(final String packageName, int userHandle, 12931 final IPackageStatsObserver observer) { 12932 mContext.enforceCallingOrSelfPermission( 12933 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12934 if (packageName == null) { 12935 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12936 } 12937 12938 PackageStats stats = new PackageStats(packageName, userHandle); 12939 12940 /* 12941 * Queue up an async operation since the package measurement may take a 12942 * little while. 12943 */ 12944 Message msg = mHandler.obtainMessage(INIT_COPY); 12945 msg.obj = new MeasureParams(stats, observer); 12946 mHandler.sendMessage(msg); 12947 } 12948 12949 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12950 PackageStats pStats) { 12951 if (packageName == null) { 12952 Slog.w(TAG, "Attempt to get size of null packageName."); 12953 return false; 12954 } 12955 PackageParser.Package p; 12956 boolean dataOnly = false; 12957 String libDirRoot = null; 12958 String asecPath = null; 12959 PackageSetting ps = null; 12960 synchronized (mPackages) { 12961 p = mPackages.get(packageName); 12962 ps = mSettings.mPackages.get(packageName); 12963 if(p == null) { 12964 dataOnly = true; 12965 if((ps == null) || (ps.pkg == null)) { 12966 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12967 return false; 12968 } 12969 p = ps.pkg; 12970 } 12971 if (ps != null) { 12972 libDirRoot = ps.legacyNativeLibraryPathString; 12973 } 12974 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12975 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12976 if (secureContainerId != null) { 12977 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12978 } 12979 } 12980 } 12981 String publicSrcDir = null; 12982 if(!dataOnly) { 12983 final ApplicationInfo applicationInfo = p.applicationInfo; 12984 if (applicationInfo == null) { 12985 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12986 return false; 12987 } 12988 if (p.isForwardLocked()) { 12989 publicSrcDir = applicationInfo.getBaseResourcePath(); 12990 } 12991 } 12992 // TODO: extend to measure size of split APKs 12993 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12994 // not just the first level. 12995 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12996 // just the primary. 12997 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12998 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12999 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 13000 if (res < 0) { 13001 return false; 13002 } 13003 13004 // Fix-up for forward-locked applications in ASEC containers. 13005 if (!isExternal(p)) { 13006 pStats.codeSize += pStats.externalCodeSize; 13007 pStats.externalCodeSize = 0L; 13008 } 13009 13010 return true; 13011 } 13012 13013 13014 @Override 13015 public void addPackageToPreferred(String packageName) { 13016 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 13017 } 13018 13019 @Override 13020 public void removePackageFromPreferred(String packageName) { 13021 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 13022 } 13023 13024 @Override 13025 public List<PackageInfo> getPreferredPackages(int flags) { 13026 return new ArrayList<PackageInfo>(); 13027 } 13028 13029 private int getUidTargetSdkVersionLockedLPr(int uid) { 13030 Object obj = mSettings.getUserIdLPr(uid); 13031 if (obj instanceof SharedUserSetting) { 13032 final SharedUserSetting sus = (SharedUserSetting) obj; 13033 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 13034 final Iterator<PackageSetting> it = sus.packages.iterator(); 13035 while (it.hasNext()) { 13036 final PackageSetting ps = it.next(); 13037 if (ps.pkg != null) { 13038 int v = ps.pkg.applicationInfo.targetSdkVersion; 13039 if (v < vers) vers = v; 13040 } 13041 } 13042 return vers; 13043 } else if (obj instanceof PackageSetting) { 13044 final PackageSetting ps = (PackageSetting) obj; 13045 if (ps.pkg != null) { 13046 return ps.pkg.applicationInfo.targetSdkVersion; 13047 } 13048 } 13049 return Build.VERSION_CODES.CUR_DEVELOPMENT; 13050 } 13051 13052 @Override 13053 public void addPreferredActivity(IntentFilter filter, int match, 13054 ComponentName[] set, ComponentName activity, int userId) { 13055 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13056 "Adding preferred"); 13057 } 13058 13059 private void addPreferredActivityInternal(IntentFilter filter, int match, 13060 ComponentName[] set, ComponentName activity, boolean always, int userId, 13061 String opname) { 13062 // writer 13063 int callingUid = Binder.getCallingUid(); 13064 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 13065 if (filter.countActions() == 0) { 13066 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13067 return; 13068 } 13069 synchronized (mPackages) { 13070 if (mContext.checkCallingOrSelfPermission( 13071 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13072 != PackageManager.PERMISSION_GRANTED) { 13073 if (getUidTargetSdkVersionLockedLPr(callingUid) 13074 < Build.VERSION_CODES.FROYO) { 13075 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 13076 + callingUid); 13077 return; 13078 } 13079 mContext.enforceCallingOrSelfPermission( 13080 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13081 } 13082 13083 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 13084 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 13085 + userId + ":"); 13086 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13087 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 13088 scheduleWritePackageRestrictionsLocked(userId); 13089 } 13090 } 13091 13092 @Override 13093 public void replacePreferredActivity(IntentFilter filter, int match, 13094 ComponentName[] set, ComponentName activity, int userId) { 13095 if (filter.countActions() != 1) { 13096 throw new IllegalArgumentException( 13097 "replacePreferredActivity expects filter to have only 1 action."); 13098 } 13099 if (filter.countDataAuthorities() != 0 13100 || filter.countDataPaths() != 0 13101 || filter.countDataSchemes() > 1 13102 || filter.countDataTypes() != 0) { 13103 throw new IllegalArgumentException( 13104 "replacePreferredActivity expects filter to have no data authorities, " + 13105 "paths, or types; and at most one scheme."); 13106 } 13107 13108 final int callingUid = Binder.getCallingUid(); 13109 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 13110 synchronized (mPackages) { 13111 if (mContext.checkCallingOrSelfPermission( 13112 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13113 != PackageManager.PERMISSION_GRANTED) { 13114 if (getUidTargetSdkVersionLockedLPr(callingUid) 13115 < Build.VERSION_CODES.FROYO) { 13116 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 13117 + Binder.getCallingUid()); 13118 return; 13119 } 13120 mContext.enforceCallingOrSelfPermission( 13121 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13122 } 13123 13124 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13125 if (pir != null) { 13126 // Get all of the existing entries that exactly match this filter. 13127 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13128 if (existing != null && existing.size() == 1) { 13129 PreferredActivity cur = existing.get(0); 13130 if (DEBUG_PREFERRED) { 13131 Slog.i(TAG, "Checking replace of preferred:"); 13132 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13133 if (!cur.mPref.mAlways) { 13134 Slog.i(TAG, " -- CUR; not mAlways!"); 13135 } else { 13136 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13137 Slog.i(TAG, " -- CUR: mSet=" 13138 + Arrays.toString(cur.mPref.mSetComponents)); 13139 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13140 Slog.i(TAG, " -- NEW: mMatch=" 13141 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13142 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13143 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13144 } 13145 } 13146 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13147 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13148 && cur.mPref.sameSet(set)) { 13149 // Setting the preferred activity to what it happens to be already 13150 if (DEBUG_PREFERRED) { 13151 Slog.i(TAG, "Replacing with same preferred activity " 13152 + cur.mPref.mShortComponent + " for user " 13153 + userId + ":"); 13154 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13155 } 13156 return; 13157 } 13158 } 13159 13160 if (existing != null) { 13161 if (DEBUG_PREFERRED) { 13162 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13163 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13164 } 13165 for (int i = 0; i < existing.size(); i++) { 13166 PreferredActivity pa = existing.get(i); 13167 if (DEBUG_PREFERRED) { 13168 Slog.i(TAG, "Removing existing preferred activity " 13169 + pa.mPref.mComponent + ":"); 13170 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13171 } 13172 pir.removeFilter(pa); 13173 } 13174 } 13175 } 13176 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13177 "Replacing preferred"); 13178 } 13179 } 13180 13181 @Override 13182 public void clearPackagePreferredActivities(String packageName) { 13183 final int uid = Binder.getCallingUid(); 13184 // writer 13185 synchronized (mPackages) { 13186 PackageParser.Package pkg = mPackages.get(packageName); 13187 if (pkg == null || pkg.applicationInfo.uid != uid) { 13188 if (mContext.checkCallingOrSelfPermission( 13189 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13190 != PackageManager.PERMISSION_GRANTED) { 13191 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13192 < Build.VERSION_CODES.FROYO) { 13193 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13194 + Binder.getCallingUid()); 13195 return; 13196 } 13197 mContext.enforceCallingOrSelfPermission( 13198 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13199 } 13200 } 13201 13202 int user = UserHandle.getCallingUserId(); 13203 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13204 scheduleWritePackageRestrictionsLocked(user); 13205 } 13206 } 13207 } 13208 13209 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13210 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13211 ArrayList<PreferredActivity> removed = null; 13212 boolean changed = false; 13213 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13214 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13215 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13216 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13217 continue; 13218 } 13219 Iterator<PreferredActivity> it = pir.filterIterator(); 13220 while (it.hasNext()) { 13221 PreferredActivity pa = it.next(); 13222 // Mark entry for removal only if it matches the package name 13223 // and the entry is of type "always". 13224 if (packageName == null || 13225 (pa.mPref.mComponent.getPackageName().equals(packageName) 13226 && pa.mPref.mAlways)) { 13227 if (removed == null) { 13228 removed = new ArrayList<PreferredActivity>(); 13229 } 13230 removed.add(pa); 13231 } 13232 } 13233 if (removed != null) { 13234 for (int j=0; j<removed.size(); j++) { 13235 PreferredActivity pa = removed.get(j); 13236 pir.removeFilter(pa); 13237 } 13238 changed = true; 13239 } 13240 } 13241 return changed; 13242 } 13243 13244 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13245 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13246 if (userId == UserHandle.USER_ALL) { 13247 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13248 sUserManager.getUserIds())) { 13249 for (int oneUserId : sUserManager.getUserIds()) { 13250 scheduleWritePackageRestrictionsLocked(oneUserId); 13251 } 13252 } 13253 } else { 13254 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13255 scheduleWritePackageRestrictionsLocked(userId); 13256 } 13257 } 13258 } 13259 13260 13261 void clearDefaultBrowserIfNeeded(String packageName) { 13262 for (int oneUserId : sUserManager.getUserIds()) { 13263 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13264 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13265 if (packageName.equals(defaultBrowserPackageName)) { 13266 setDefaultBrowserPackageName(null, oneUserId); 13267 } 13268 } 13269 } 13270 13271 @Override 13272 public void resetPreferredActivities(int userId) { 13273 /* TODO: Actually use userId. Why is it being passed in? */ 13274 mContext.enforceCallingOrSelfPermission( 13275 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13276 // writer 13277 synchronized (mPackages) { 13278 int user = UserHandle.getCallingUserId(); 13279 clearPackagePreferredActivitiesLPw(null, user); 13280 mSettings.readDefaultPreferredAppsLPw(this, user); 13281 scheduleWritePackageRestrictionsLocked(user); 13282 } 13283 } 13284 13285 @Override 13286 public int getPreferredActivities(List<IntentFilter> outFilters, 13287 List<ComponentName> outActivities, String packageName) { 13288 13289 int num = 0; 13290 final int userId = UserHandle.getCallingUserId(); 13291 // reader 13292 synchronized (mPackages) { 13293 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13294 if (pir != null) { 13295 final Iterator<PreferredActivity> it = pir.filterIterator(); 13296 while (it.hasNext()) { 13297 final PreferredActivity pa = it.next(); 13298 if (packageName == null 13299 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13300 && pa.mPref.mAlways)) { 13301 if (outFilters != null) { 13302 outFilters.add(new IntentFilter(pa)); 13303 } 13304 if (outActivities != null) { 13305 outActivities.add(pa.mPref.mComponent); 13306 } 13307 } 13308 } 13309 } 13310 } 13311 13312 return num; 13313 } 13314 13315 @Override 13316 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13317 int userId) { 13318 int callingUid = Binder.getCallingUid(); 13319 if (callingUid != Process.SYSTEM_UID) { 13320 throw new SecurityException( 13321 "addPersistentPreferredActivity can only be run by the system"); 13322 } 13323 if (filter.countActions() == 0) { 13324 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13325 return; 13326 } 13327 synchronized (mPackages) { 13328 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13329 " :"); 13330 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13331 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13332 new PersistentPreferredActivity(filter, activity)); 13333 scheduleWritePackageRestrictionsLocked(userId); 13334 } 13335 } 13336 13337 @Override 13338 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13339 int callingUid = Binder.getCallingUid(); 13340 if (callingUid != Process.SYSTEM_UID) { 13341 throw new SecurityException( 13342 "clearPackagePersistentPreferredActivities can only be run by the system"); 13343 } 13344 ArrayList<PersistentPreferredActivity> removed = null; 13345 boolean changed = false; 13346 synchronized (mPackages) { 13347 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13348 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13349 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13350 .valueAt(i); 13351 if (userId != thisUserId) { 13352 continue; 13353 } 13354 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13355 while (it.hasNext()) { 13356 PersistentPreferredActivity ppa = it.next(); 13357 // Mark entry for removal only if it matches the package name. 13358 if (ppa.mComponent.getPackageName().equals(packageName)) { 13359 if (removed == null) { 13360 removed = new ArrayList<PersistentPreferredActivity>(); 13361 } 13362 removed.add(ppa); 13363 } 13364 } 13365 if (removed != null) { 13366 for (int j=0; j<removed.size(); j++) { 13367 PersistentPreferredActivity ppa = removed.get(j); 13368 ppir.removeFilter(ppa); 13369 } 13370 changed = true; 13371 } 13372 } 13373 13374 if (changed) { 13375 scheduleWritePackageRestrictionsLocked(userId); 13376 } 13377 } 13378 } 13379 13380 /** 13381 * Non-Binder method, support for the backup/restore mechanism: write the 13382 * full set of preferred activities in its canonical XML format. Returns true 13383 * on success; false otherwise. 13384 */ 13385 @Override 13386 public byte[] getPreferredActivityBackup(int userId) { 13387 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13388 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13389 } 13390 13391 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13392 try { 13393 final XmlSerializer serializer = new FastXmlSerializer(); 13394 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13395 serializer.startDocument(null, true); 13396 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13397 13398 synchronized (mPackages) { 13399 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13400 } 13401 13402 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13403 serializer.endDocument(); 13404 serializer.flush(); 13405 } catch (Exception e) { 13406 if (DEBUG_BACKUP) { 13407 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13408 } 13409 return null; 13410 } 13411 13412 return dataStream.toByteArray(); 13413 } 13414 13415 @Override 13416 public void restorePreferredActivities(byte[] backup, int userId) { 13417 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13418 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13419 } 13420 13421 try { 13422 final XmlPullParser parser = Xml.newPullParser(); 13423 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13424 13425 int type; 13426 while ((type = parser.next()) != XmlPullParser.START_TAG 13427 && type != XmlPullParser.END_DOCUMENT) { 13428 } 13429 if (type != XmlPullParser.START_TAG) { 13430 // oops didn't find a start tag?! 13431 if (DEBUG_BACKUP) { 13432 Slog.e(TAG, "Didn't find start tag during restore"); 13433 } 13434 return; 13435 } 13436 13437 // this is supposed to be TAG_PREFERRED_BACKUP 13438 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13439 if (DEBUG_BACKUP) { 13440 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13441 } 13442 return; 13443 } 13444 13445 // skip interfering stuff, then we're aligned with the backing implementation 13446 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13447 synchronized (mPackages) { 13448 mSettings.readPreferredActivitiesLPw(parser, userId); 13449 } 13450 } catch (Exception e) { 13451 if (DEBUG_BACKUP) { 13452 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13453 } 13454 } 13455 } 13456 13457 @Override 13458 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13459 int sourceUserId, int targetUserId, int flags) { 13460 mContext.enforceCallingOrSelfPermission( 13461 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13462 int callingUid = Binder.getCallingUid(); 13463 enforceOwnerRights(ownerPackage, callingUid); 13464 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13465 if (intentFilter.countActions() == 0) { 13466 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13467 return; 13468 } 13469 synchronized (mPackages) { 13470 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13471 ownerPackage, targetUserId, flags); 13472 CrossProfileIntentResolver resolver = 13473 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13474 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13475 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13476 if (existing != null) { 13477 int size = existing.size(); 13478 for (int i = 0; i < size; i++) { 13479 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13480 return; 13481 } 13482 } 13483 } 13484 resolver.addFilter(newFilter); 13485 scheduleWritePackageRestrictionsLocked(sourceUserId); 13486 } 13487 } 13488 13489 @Override 13490 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13491 mContext.enforceCallingOrSelfPermission( 13492 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13493 int callingUid = Binder.getCallingUid(); 13494 enforceOwnerRights(ownerPackage, callingUid); 13495 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13496 synchronized (mPackages) { 13497 CrossProfileIntentResolver resolver = 13498 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13499 ArraySet<CrossProfileIntentFilter> set = 13500 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13501 for (CrossProfileIntentFilter filter : set) { 13502 if (filter.getOwnerPackage().equals(ownerPackage)) { 13503 resolver.removeFilter(filter); 13504 } 13505 } 13506 scheduleWritePackageRestrictionsLocked(sourceUserId); 13507 } 13508 } 13509 13510 // Enforcing that callingUid is owning pkg on userId 13511 private void enforceOwnerRights(String pkg, int callingUid) { 13512 // The system owns everything. 13513 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13514 return; 13515 } 13516 int callingUserId = UserHandle.getUserId(callingUid); 13517 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13518 if (pi == null) { 13519 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13520 + callingUserId); 13521 } 13522 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13523 throw new SecurityException("Calling uid " + callingUid 13524 + " does not own package " + pkg); 13525 } 13526 } 13527 13528 @Override 13529 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13530 Intent intent = new Intent(Intent.ACTION_MAIN); 13531 intent.addCategory(Intent.CATEGORY_HOME); 13532 13533 final int callingUserId = UserHandle.getCallingUserId(); 13534 List<ResolveInfo> list = queryIntentActivities(intent, null, 13535 PackageManager.GET_META_DATA, callingUserId); 13536 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13537 true, false, false, callingUserId); 13538 13539 allHomeCandidates.clear(); 13540 if (list != null) { 13541 for (ResolveInfo ri : list) { 13542 allHomeCandidates.add(ri); 13543 } 13544 } 13545 return (preferred == null || preferred.activityInfo == null) 13546 ? null 13547 : new ComponentName(preferred.activityInfo.packageName, 13548 preferred.activityInfo.name); 13549 } 13550 13551 @Override 13552 public void setApplicationEnabledSetting(String appPackageName, 13553 int newState, int flags, int userId, String callingPackage) { 13554 if (!sUserManager.exists(userId)) return; 13555 if (callingPackage == null) { 13556 callingPackage = Integer.toString(Binder.getCallingUid()); 13557 } 13558 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13559 } 13560 13561 @Override 13562 public void setComponentEnabledSetting(ComponentName componentName, 13563 int newState, int flags, int userId) { 13564 if (!sUserManager.exists(userId)) return; 13565 setEnabledSetting(componentName.getPackageName(), 13566 componentName.getClassName(), newState, flags, userId, null); 13567 } 13568 13569 private void setEnabledSetting(final String packageName, String className, int newState, 13570 final int flags, int userId, String callingPackage) { 13571 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13572 || newState == COMPONENT_ENABLED_STATE_ENABLED 13573 || newState == COMPONENT_ENABLED_STATE_DISABLED 13574 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13575 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13576 throw new IllegalArgumentException("Invalid new component state: " 13577 + newState); 13578 } 13579 PackageSetting pkgSetting; 13580 final int uid = Binder.getCallingUid(); 13581 final int permission = mContext.checkCallingOrSelfPermission( 13582 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13583 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13584 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13585 boolean sendNow = false; 13586 boolean isApp = (className == null); 13587 String componentName = isApp ? packageName : className; 13588 int packageUid = -1; 13589 ArrayList<String> components; 13590 13591 // writer 13592 synchronized (mPackages) { 13593 pkgSetting = mSettings.mPackages.get(packageName); 13594 if (pkgSetting == null) { 13595 if (className == null) { 13596 throw new IllegalArgumentException( 13597 "Unknown package: " + packageName); 13598 } 13599 throw new IllegalArgumentException( 13600 "Unknown component: " + packageName 13601 + "/" + className); 13602 } 13603 // Allow root and verify that userId is not being specified by a different user 13604 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13605 throw new SecurityException( 13606 "Permission Denial: attempt to change component state from pid=" 13607 + Binder.getCallingPid() 13608 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13609 } 13610 if (className == null) { 13611 // We're dealing with an application/package level state change 13612 if (pkgSetting.getEnabled(userId) == newState) { 13613 // Nothing to do 13614 return; 13615 } 13616 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13617 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13618 // Don't care about who enables an app. 13619 callingPackage = null; 13620 } 13621 pkgSetting.setEnabled(newState, userId, callingPackage); 13622 // pkgSetting.pkg.mSetEnabled = newState; 13623 } else { 13624 // We're dealing with a component level state change 13625 // First, verify that this is a valid class name. 13626 PackageParser.Package pkg = pkgSetting.pkg; 13627 if (pkg == null || !pkg.hasComponentClassName(className)) { 13628 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13629 throw new IllegalArgumentException("Component class " + className 13630 + " does not exist in " + packageName); 13631 } else { 13632 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13633 + className + " does not exist in " + packageName); 13634 } 13635 } 13636 switch (newState) { 13637 case COMPONENT_ENABLED_STATE_ENABLED: 13638 if (!pkgSetting.enableComponentLPw(className, userId)) { 13639 return; 13640 } 13641 break; 13642 case COMPONENT_ENABLED_STATE_DISABLED: 13643 if (!pkgSetting.disableComponentLPw(className, userId)) { 13644 return; 13645 } 13646 break; 13647 case COMPONENT_ENABLED_STATE_DEFAULT: 13648 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13649 return; 13650 } 13651 break; 13652 default: 13653 Slog.e(TAG, "Invalid new component state: " + newState); 13654 return; 13655 } 13656 } 13657 scheduleWritePackageRestrictionsLocked(userId); 13658 components = mPendingBroadcasts.get(userId, packageName); 13659 final boolean newPackage = components == null; 13660 if (newPackage) { 13661 components = new ArrayList<String>(); 13662 } 13663 if (!components.contains(componentName)) { 13664 components.add(componentName); 13665 } 13666 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13667 sendNow = true; 13668 // Purge entry from pending broadcast list if another one exists already 13669 // since we are sending one right away. 13670 mPendingBroadcasts.remove(userId, packageName); 13671 } else { 13672 if (newPackage) { 13673 mPendingBroadcasts.put(userId, packageName, components); 13674 } 13675 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13676 // Schedule a message 13677 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13678 } 13679 } 13680 } 13681 13682 long callingId = Binder.clearCallingIdentity(); 13683 try { 13684 if (sendNow) { 13685 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13686 sendPackageChangedBroadcast(packageName, 13687 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13688 } 13689 } finally { 13690 Binder.restoreCallingIdentity(callingId); 13691 } 13692 } 13693 13694 private void sendPackageChangedBroadcast(String packageName, 13695 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13696 if (DEBUG_INSTALL) 13697 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13698 + componentNames); 13699 Bundle extras = new Bundle(4); 13700 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13701 String nameList[] = new String[componentNames.size()]; 13702 componentNames.toArray(nameList); 13703 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13704 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13705 extras.putInt(Intent.EXTRA_UID, packageUid); 13706 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13707 new int[] {UserHandle.getUserId(packageUid)}); 13708 } 13709 13710 @Override 13711 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13712 if (!sUserManager.exists(userId)) return; 13713 final int uid = Binder.getCallingUid(); 13714 final int permission = mContext.checkCallingOrSelfPermission( 13715 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13716 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13717 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13718 // writer 13719 synchronized (mPackages) { 13720 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13721 allowedByPermission, uid, userId)) { 13722 scheduleWritePackageRestrictionsLocked(userId); 13723 } 13724 } 13725 } 13726 13727 @Override 13728 public String getInstallerPackageName(String packageName) { 13729 // reader 13730 synchronized (mPackages) { 13731 return mSettings.getInstallerPackageNameLPr(packageName); 13732 } 13733 } 13734 13735 @Override 13736 public int getApplicationEnabledSetting(String packageName, int userId) { 13737 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13738 int uid = Binder.getCallingUid(); 13739 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13740 // reader 13741 synchronized (mPackages) { 13742 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13743 } 13744 } 13745 13746 @Override 13747 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13748 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13749 int uid = Binder.getCallingUid(); 13750 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13751 // reader 13752 synchronized (mPackages) { 13753 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13754 } 13755 } 13756 13757 @Override 13758 public void enterSafeMode() { 13759 enforceSystemOrRoot("Only the system can request entering safe mode"); 13760 13761 if (!mSystemReady) { 13762 mSafeMode = true; 13763 } 13764 } 13765 13766 @Override 13767 public void systemReady() { 13768 mSystemReady = true; 13769 13770 // Read the compatibilty setting when the system is ready. 13771 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13772 mContext.getContentResolver(), 13773 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13774 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13775 if (DEBUG_SETTINGS) { 13776 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13777 } 13778 13779 synchronized (mPackages) { 13780 // Verify that all of the preferred activity components actually 13781 // exist. It is possible for applications to be updated and at 13782 // that point remove a previously declared activity component that 13783 // had been set as a preferred activity. We try to clean this up 13784 // the next time we encounter that preferred activity, but it is 13785 // possible for the user flow to never be able to return to that 13786 // situation so here we do a sanity check to make sure we haven't 13787 // left any junk around. 13788 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13789 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13790 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13791 removed.clear(); 13792 for (PreferredActivity pa : pir.filterSet()) { 13793 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13794 removed.add(pa); 13795 } 13796 } 13797 if (removed.size() > 0) { 13798 for (int r=0; r<removed.size(); r++) { 13799 PreferredActivity pa = removed.get(r); 13800 Slog.w(TAG, "Removing dangling preferred activity: " 13801 + pa.mPref.mComponent); 13802 pir.removeFilter(pa); 13803 } 13804 mSettings.writePackageRestrictionsLPr( 13805 mSettings.mPreferredActivities.keyAt(i)); 13806 } 13807 } 13808 } 13809 sUserManager.systemReady(); 13810 13811 // If we upgraded grant all default permissions before kicking off. 13812 if (isFirstBoot() || (CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE && mIsUpgrade)) { 13813 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 13814 for (int userId : UserManagerService.getInstance().getUserIds()) { 13815 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 13816 } 13817 } 13818 13819 // Kick off any messages waiting for system ready 13820 if (mPostSystemReadyMessages != null) { 13821 for (Message msg : mPostSystemReadyMessages) { 13822 msg.sendToTarget(); 13823 } 13824 mPostSystemReadyMessages = null; 13825 } 13826 13827 // Watch for external volumes that come and go over time 13828 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13829 storage.registerListener(mStorageListener); 13830 13831 mInstallerService.systemReady(); 13832 mPackageDexOptimizer.systemReady(); 13833 } 13834 13835 @Override 13836 public boolean isSafeMode() { 13837 return mSafeMode; 13838 } 13839 13840 @Override 13841 public boolean hasSystemUidErrors() { 13842 return mHasSystemUidErrors; 13843 } 13844 13845 static String arrayToString(int[] array) { 13846 StringBuffer buf = new StringBuffer(128); 13847 buf.append('['); 13848 if (array != null) { 13849 for (int i=0; i<array.length; i++) { 13850 if (i > 0) buf.append(", "); 13851 buf.append(array[i]); 13852 } 13853 } 13854 buf.append(']'); 13855 return buf.toString(); 13856 } 13857 13858 static class DumpState { 13859 public static final int DUMP_LIBS = 1 << 0; 13860 public static final int DUMP_FEATURES = 1 << 1; 13861 public static final int DUMP_RESOLVERS = 1 << 2; 13862 public static final int DUMP_PERMISSIONS = 1 << 3; 13863 public static final int DUMP_PACKAGES = 1 << 4; 13864 public static final int DUMP_SHARED_USERS = 1 << 5; 13865 public static final int DUMP_MESSAGES = 1 << 6; 13866 public static final int DUMP_PROVIDERS = 1 << 7; 13867 public static final int DUMP_VERIFIERS = 1 << 8; 13868 public static final int DUMP_PREFERRED = 1 << 9; 13869 public static final int DUMP_PREFERRED_XML = 1 << 10; 13870 public static final int DUMP_KEYSETS = 1 << 11; 13871 public static final int DUMP_VERSION = 1 << 12; 13872 public static final int DUMP_INSTALLS = 1 << 13; 13873 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13874 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13875 13876 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13877 13878 private int mTypes; 13879 13880 private int mOptions; 13881 13882 private boolean mTitlePrinted; 13883 13884 private SharedUserSetting mSharedUser; 13885 13886 public boolean isDumping(int type) { 13887 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13888 return true; 13889 } 13890 13891 return (mTypes & type) != 0; 13892 } 13893 13894 public void setDump(int type) { 13895 mTypes |= type; 13896 } 13897 13898 public boolean isOptionEnabled(int option) { 13899 return (mOptions & option) != 0; 13900 } 13901 13902 public void setOptionEnabled(int option) { 13903 mOptions |= option; 13904 } 13905 13906 public boolean onTitlePrinted() { 13907 final boolean printed = mTitlePrinted; 13908 mTitlePrinted = true; 13909 return printed; 13910 } 13911 13912 public boolean getTitlePrinted() { 13913 return mTitlePrinted; 13914 } 13915 13916 public void setTitlePrinted(boolean enabled) { 13917 mTitlePrinted = enabled; 13918 } 13919 13920 public SharedUserSetting getSharedUser() { 13921 return mSharedUser; 13922 } 13923 13924 public void setSharedUser(SharedUserSetting user) { 13925 mSharedUser = user; 13926 } 13927 } 13928 13929 @Override 13930 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13931 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13932 != PackageManager.PERMISSION_GRANTED) { 13933 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13934 + Binder.getCallingPid() 13935 + ", uid=" + Binder.getCallingUid() 13936 + " without permission " 13937 + android.Manifest.permission.DUMP); 13938 return; 13939 } 13940 13941 DumpState dumpState = new DumpState(); 13942 boolean fullPreferred = false; 13943 boolean checkin = false; 13944 13945 String packageName = null; 13946 13947 int opti = 0; 13948 while (opti < args.length) { 13949 String opt = args[opti]; 13950 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13951 break; 13952 } 13953 opti++; 13954 13955 if ("-a".equals(opt)) { 13956 // Right now we only know how to print all. 13957 } else if ("-h".equals(opt)) { 13958 pw.println("Package manager dump options:"); 13959 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13960 pw.println(" --checkin: dump for a checkin"); 13961 pw.println(" -f: print details of intent filters"); 13962 pw.println(" -h: print this help"); 13963 pw.println(" cmd may be one of:"); 13964 pw.println(" l[ibraries]: list known shared libraries"); 13965 pw.println(" f[ibraries]: list device features"); 13966 pw.println(" k[eysets]: print known keysets"); 13967 pw.println(" r[esolvers]: dump intent resolvers"); 13968 pw.println(" perm[issions]: dump permissions"); 13969 pw.println(" pref[erred]: print preferred package settings"); 13970 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13971 pw.println(" prov[iders]: dump content providers"); 13972 pw.println(" p[ackages]: dump installed packages"); 13973 pw.println(" s[hared-users]: dump shared user IDs"); 13974 pw.println(" m[essages]: print collected runtime messages"); 13975 pw.println(" v[erifiers]: print package verifier info"); 13976 pw.println(" version: print database version info"); 13977 pw.println(" write: write current settings now"); 13978 pw.println(" <package.name>: info about given package"); 13979 pw.println(" installs: details about install sessions"); 13980 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13981 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13982 return; 13983 } else if ("--checkin".equals(opt)) { 13984 checkin = true; 13985 } else if ("-f".equals(opt)) { 13986 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13987 } else { 13988 pw.println("Unknown argument: " + opt + "; use -h for help"); 13989 } 13990 } 13991 13992 // Is the caller requesting to dump a particular piece of data? 13993 if (opti < args.length) { 13994 String cmd = args[opti]; 13995 opti++; 13996 // Is this a package name? 13997 if ("android".equals(cmd) || cmd.contains(".")) { 13998 packageName = cmd; 13999 // When dumping a single package, we always dump all of its 14000 // filter information since the amount of data will be reasonable. 14001 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 14002 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 14003 dumpState.setDump(DumpState.DUMP_LIBS); 14004 } else if ("f".equals(cmd) || "features".equals(cmd)) { 14005 dumpState.setDump(DumpState.DUMP_FEATURES); 14006 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 14007 dumpState.setDump(DumpState.DUMP_RESOLVERS); 14008 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 14009 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 14010 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 14011 dumpState.setDump(DumpState.DUMP_PREFERRED); 14012 } else if ("preferred-xml".equals(cmd)) { 14013 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 14014 if (opti < args.length && "--full".equals(args[opti])) { 14015 fullPreferred = true; 14016 opti++; 14017 } 14018 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 14019 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 14020 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 14021 dumpState.setDump(DumpState.DUMP_PACKAGES); 14022 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 14023 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 14024 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 14025 dumpState.setDump(DumpState.DUMP_PROVIDERS); 14026 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 14027 dumpState.setDump(DumpState.DUMP_MESSAGES); 14028 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 14029 dumpState.setDump(DumpState.DUMP_VERIFIERS); 14030 } else if ("i".equals(cmd) || "ifv".equals(cmd) 14031 || "intent-filter-verifiers".equals(cmd)) { 14032 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 14033 } else if ("version".equals(cmd)) { 14034 dumpState.setDump(DumpState.DUMP_VERSION); 14035 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 14036 dumpState.setDump(DumpState.DUMP_KEYSETS); 14037 } else if ("installs".equals(cmd)) { 14038 dumpState.setDump(DumpState.DUMP_INSTALLS); 14039 } else if ("write".equals(cmd)) { 14040 synchronized (mPackages) { 14041 mSettings.writeLPr(); 14042 pw.println("Settings written."); 14043 return; 14044 } 14045 } 14046 } 14047 14048 if (checkin) { 14049 pw.println("vers,1"); 14050 } 14051 14052 // reader 14053 synchronized (mPackages) { 14054 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 14055 if (!checkin) { 14056 if (dumpState.onTitlePrinted()) 14057 pw.println(); 14058 pw.println("Database versions:"); 14059 pw.print(" SDK Version:"); 14060 pw.print(" internal="); 14061 pw.print(mSettings.mInternalSdkPlatform); 14062 pw.print(" external="); 14063 pw.println(mSettings.mExternalSdkPlatform); 14064 pw.print(" DB Version:"); 14065 pw.print(" internal="); 14066 pw.print(mSettings.mInternalDatabaseVersion); 14067 pw.print(" external="); 14068 pw.println(mSettings.mExternalDatabaseVersion); 14069 } 14070 } 14071 14072 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 14073 if (!checkin) { 14074 if (dumpState.onTitlePrinted()) 14075 pw.println(); 14076 pw.println("Verifiers:"); 14077 pw.print(" Required: "); 14078 pw.print(mRequiredVerifierPackage); 14079 pw.print(" (uid="); 14080 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 14081 pw.println(")"); 14082 } else if (mRequiredVerifierPackage != null) { 14083 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 14084 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 14085 } 14086 } 14087 14088 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 14089 packageName == null) { 14090 if (mIntentFilterVerifierComponent != null) { 14091 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 14092 if (!checkin) { 14093 if (dumpState.onTitlePrinted()) 14094 pw.println(); 14095 pw.println("Intent Filter Verifier:"); 14096 pw.print(" Using: "); 14097 pw.print(verifierPackageName); 14098 pw.print(" (uid="); 14099 pw.print(getPackageUid(verifierPackageName, 0)); 14100 pw.println(")"); 14101 } else if (verifierPackageName != null) { 14102 pw.print("ifv,"); pw.print(verifierPackageName); 14103 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 14104 } 14105 } else { 14106 pw.println(); 14107 pw.println("No Intent Filter Verifier available!"); 14108 } 14109 } 14110 14111 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 14112 boolean printedHeader = false; 14113 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 14114 while (it.hasNext()) { 14115 String name = it.next(); 14116 SharedLibraryEntry ent = mSharedLibraries.get(name); 14117 if (!checkin) { 14118 if (!printedHeader) { 14119 if (dumpState.onTitlePrinted()) 14120 pw.println(); 14121 pw.println("Libraries:"); 14122 printedHeader = true; 14123 } 14124 pw.print(" "); 14125 } else { 14126 pw.print("lib,"); 14127 } 14128 pw.print(name); 14129 if (!checkin) { 14130 pw.print(" -> "); 14131 } 14132 if (ent.path != null) { 14133 if (!checkin) { 14134 pw.print("(jar) "); 14135 pw.print(ent.path); 14136 } else { 14137 pw.print(",jar,"); 14138 pw.print(ent.path); 14139 } 14140 } else { 14141 if (!checkin) { 14142 pw.print("(apk) "); 14143 pw.print(ent.apk); 14144 } else { 14145 pw.print(",apk,"); 14146 pw.print(ent.apk); 14147 } 14148 } 14149 pw.println(); 14150 } 14151 } 14152 14153 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14154 if (dumpState.onTitlePrinted()) 14155 pw.println(); 14156 if (!checkin) { 14157 pw.println("Features:"); 14158 } 14159 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14160 while (it.hasNext()) { 14161 String name = it.next(); 14162 if (!checkin) { 14163 pw.print(" "); 14164 } else { 14165 pw.print("feat,"); 14166 } 14167 pw.println(name); 14168 } 14169 } 14170 14171 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14172 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14173 : "Activity Resolver Table:", " ", packageName, 14174 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14175 dumpState.setTitlePrinted(true); 14176 } 14177 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14178 : "Receiver Resolver Table:", " ", packageName, 14179 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14180 dumpState.setTitlePrinted(true); 14181 } 14182 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14183 : "Service Resolver Table:", " ", packageName, 14184 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14185 dumpState.setTitlePrinted(true); 14186 } 14187 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14188 : "Provider Resolver Table:", " ", packageName, 14189 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14190 dumpState.setTitlePrinted(true); 14191 } 14192 } 14193 14194 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14195 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14196 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14197 int user = mSettings.mPreferredActivities.keyAt(i); 14198 if (pir.dump(pw, 14199 dumpState.getTitlePrinted() 14200 ? "\nPreferred Activities User " + user + ":" 14201 : "Preferred Activities User " + user + ":", " ", 14202 packageName, true, false)) { 14203 dumpState.setTitlePrinted(true); 14204 } 14205 } 14206 } 14207 14208 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14209 pw.flush(); 14210 FileOutputStream fout = new FileOutputStream(fd); 14211 BufferedOutputStream str = new BufferedOutputStream(fout); 14212 XmlSerializer serializer = new FastXmlSerializer(); 14213 try { 14214 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14215 serializer.startDocument(null, true); 14216 serializer.setFeature( 14217 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14218 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14219 serializer.endDocument(); 14220 serializer.flush(); 14221 } catch (IllegalArgumentException e) { 14222 pw.println("Failed writing: " + e); 14223 } catch (IllegalStateException e) { 14224 pw.println("Failed writing: " + e); 14225 } catch (IOException e) { 14226 pw.println("Failed writing: " + e); 14227 } 14228 } 14229 14230 if (!checkin 14231 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 14232 && packageName == null) { 14233 pw.println(); 14234 int count = mSettings.mPackages.size(); 14235 if (count == 0) { 14236 pw.println("No domain preferred apps!"); 14237 pw.println(); 14238 } else { 14239 final String prefix = " "; 14240 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14241 if (allPackageSettings.size() == 0) { 14242 pw.println("No domain preferred apps!"); 14243 pw.println(); 14244 } else { 14245 pw.println("Domain preferred apps status:"); 14246 pw.println(); 14247 count = 0; 14248 for (PackageSetting ps : allPackageSettings) { 14249 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14250 if (ivi == null || ivi.getPackageName() == null) continue; 14251 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14252 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14253 pw.println(prefix + "Status: " + ivi.getStatusString()); 14254 pw.println(); 14255 count++; 14256 } 14257 if (count == 0) { 14258 pw.println(prefix + "No domain preferred app status!"); 14259 pw.println(); 14260 } 14261 for (int userId : sUserManager.getUserIds()) { 14262 pw.println("Domain preferred apps for User " + userId + ":"); 14263 pw.println(); 14264 count = 0; 14265 for (PackageSetting ps : allPackageSettings) { 14266 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14267 if (ivi == null || ivi.getPackageName() == null) { 14268 continue; 14269 } 14270 final int status = ps.getDomainVerificationStatusForUser(userId); 14271 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14272 continue; 14273 } 14274 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14275 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14276 String statusStr = IntentFilterVerificationInfo. 14277 getStatusStringFromValue(status); 14278 pw.println(prefix + "Status: " + statusStr); 14279 pw.println(); 14280 count++; 14281 } 14282 if (count == 0) { 14283 pw.println(prefix + "No domain preferred apps!"); 14284 pw.println(); 14285 } 14286 } 14287 } 14288 } 14289 } 14290 14291 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14292 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14293 if (packageName == null) { 14294 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14295 if (iperm == 0) { 14296 if (dumpState.onTitlePrinted()) 14297 pw.println(); 14298 pw.println("AppOp Permissions:"); 14299 } 14300 pw.print(" AppOp Permission "); 14301 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14302 pw.println(":"); 14303 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14304 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14305 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14306 } 14307 } 14308 } 14309 } 14310 14311 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14312 boolean printedSomething = false; 14313 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14314 if (packageName != null && !packageName.equals(p.info.packageName)) { 14315 continue; 14316 } 14317 if (!printedSomething) { 14318 if (dumpState.onTitlePrinted()) 14319 pw.println(); 14320 pw.println("Registered ContentProviders:"); 14321 printedSomething = true; 14322 } 14323 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14324 pw.print(" "); pw.println(p.toString()); 14325 } 14326 printedSomething = false; 14327 for (Map.Entry<String, PackageParser.Provider> entry : 14328 mProvidersByAuthority.entrySet()) { 14329 PackageParser.Provider p = entry.getValue(); 14330 if (packageName != null && !packageName.equals(p.info.packageName)) { 14331 continue; 14332 } 14333 if (!printedSomething) { 14334 if (dumpState.onTitlePrinted()) 14335 pw.println(); 14336 pw.println("ContentProvider Authorities:"); 14337 printedSomething = true; 14338 } 14339 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14340 pw.print(" "); pw.println(p.toString()); 14341 if (p.info != null && p.info.applicationInfo != null) { 14342 final String appInfo = p.info.applicationInfo.toString(); 14343 pw.print(" applicationInfo="); pw.println(appInfo); 14344 } 14345 } 14346 } 14347 14348 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14349 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14350 } 14351 14352 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14353 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14354 } 14355 14356 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14357 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14358 } 14359 14360 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14361 // XXX should handle packageName != null by dumping only install data that 14362 // the given package is involved with. 14363 if (dumpState.onTitlePrinted()) pw.println(); 14364 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14365 } 14366 14367 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14368 if (dumpState.onTitlePrinted()) pw.println(); 14369 mSettings.dumpReadMessagesLPr(pw, dumpState); 14370 14371 pw.println(); 14372 pw.println("Package warning messages:"); 14373 BufferedReader in = null; 14374 String line = null; 14375 try { 14376 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14377 while ((line = in.readLine()) != null) { 14378 if (line.contains("ignored: updated version")) continue; 14379 pw.println(line); 14380 } 14381 } catch (IOException ignored) { 14382 } finally { 14383 IoUtils.closeQuietly(in); 14384 } 14385 } 14386 14387 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14388 BufferedReader in = null; 14389 String line = null; 14390 try { 14391 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14392 while ((line = in.readLine()) != null) { 14393 if (line.contains("ignored: updated version")) continue; 14394 pw.print("msg,"); 14395 pw.println(line); 14396 } 14397 } catch (IOException ignored) { 14398 } finally { 14399 IoUtils.closeQuietly(in); 14400 } 14401 } 14402 } 14403 } 14404 14405 // ------- apps on sdcard specific code ------- 14406 static final boolean DEBUG_SD_INSTALL = false; 14407 14408 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14409 14410 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14411 14412 private boolean mMediaMounted = false; 14413 14414 static String getEncryptKey() { 14415 try { 14416 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14417 SD_ENCRYPTION_KEYSTORE_NAME); 14418 if (sdEncKey == null) { 14419 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14420 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14421 if (sdEncKey == null) { 14422 Slog.e(TAG, "Failed to create encryption keys"); 14423 return null; 14424 } 14425 } 14426 return sdEncKey; 14427 } catch (NoSuchAlgorithmException nsae) { 14428 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14429 return null; 14430 } catch (IOException ioe) { 14431 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14432 return null; 14433 } 14434 } 14435 14436 /* 14437 * Update media status on PackageManager. 14438 */ 14439 @Override 14440 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14441 int callingUid = Binder.getCallingUid(); 14442 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14443 throw new SecurityException("Media status can only be updated by the system"); 14444 } 14445 // reader; this apparently protects mMediaMounted, but should probably 14446 // be a different lock in that case. 14447 synchronized (mPackages) { 14448 Log.i(TAG, "Updating external media status from " 14449 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14450 + (mediaStatus ? "mounted" : "unmounted")); 14451 if (DEBUG_SD_INSTALL) 14452 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14453 + ", mMediaMounted=" + mMediaMounted); 14454 if (mediaStatus == mMediaMounted) { 14455 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14456 : 0, -1); 14457 mHandler.sendMessage(msg); 14458 return; 14459 } 14460 mMediaMounted = mediaStatus; 14461 } 14462 // Queue up an async operation since the package installation may take a 14463 // little while. 14464 mHandler.post(new Runnable() { 14465 public void run() { 14466 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14467 } 14468 }); 14469 } 14470 14471 /** 14472 * Called by MountService when the initial ASECs to scan are available. 14473 * Should block until all the ASEC containers are finished being scanned. 14474 */ 14475 public void scanAvailableAsecs() { 14476 updateExternalMediaStatusInner(true, false, false); 14477 if (mShouldRestoreconData) { 14478 SELinuxMMAC.setRestoreconDone(); 14479 mShouldRestoreconData = false; 14480 } 14481 } 14482 14483 /* 14484 * Collect information of applications on external media, map them against 14485 * existing containers and update information based on current mount status. 14486 * Please note that we always have to report status if reportStatus has been 14487 * set to true especially when unloading packages. 14488 */ 14489 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14490 boolean externalStorage) { 14491 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14492 int[] uidArr = EmptyArray.INT; 14493 14494 final String[] list = PackageHelper.getSecureContainerList(); 14495 if (ArrayUtils.isEmpty(list)) { 14496 Log.i(TAG, "No secure containers found"); 14497 } else { 14498 // Process list of secure containers and categorize them 14499 // as active or stale based on their package internal state. 14500 14501 // reader 14502 synchronized (mPackages) { 14503 for (String cid : list) { 14504 // Leave stages untouched for now; installer service owns them 14505 if (PackageInstallerService.isStageName(cid)) continue; 14506 14507 if (DEBUG_SD_INSTALL) 14508 Log.i(TAG, "Processing container " + cid); 14509 String pkgName = getAsecPackageName(cid); 14510 if (pkgName == null) { 14511 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14512 continue; 14513 } 14514 if (DEBUG_SD_INSTALL) 14515 Log.i(TAG, "Looking for pkg : " + pkgName); 14516 14517 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14518 if (ps == null) { 14519 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14520 continue; 14521 } 14522 14523 /* 14524 * Skip packages that are not external if we're unmounting 14525 * external storage. 14526 */ 14527 if (externalStorage && !isMounted && !isExternal(ps)) { 14528 continue; 14529 } 14530 14531 final AsecInstallArgs args = new AsecInstallArgs(cid, 14532 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14533 // The package status is changed only if the code path 14534 // matches between settings and the container id. 14535 if (ps.codePathString != null 14536 && ps.codePathString.startsWith(args.getCodePath())) { 14537 if (DEBUG_SD_INSTALL) { 14538 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14539 + " at code path: " + ps.codePathString); 14540 } 14541 14542 // We do have a valid package installed on sdcard 14543 processCids.put(args, ps.codePathString); 14544 final int uid = ps.appId; 14545 if (uid != -1) { 14546 uidArr = ArrayUtils.appendInt(uidArr, uid); 14547 } 14548 } else { 14549 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14550 + ps.codePathString); 14551 } 14552 } 14553 } 14554 14555 Arrays.sort(uidArr); 14556 } 14557 14558 // Process packages with valid entries. 14559 if (isMounted) { 14560 if (DEBUG_SD_INSTALL) 14561 Log.i(TAG, "Loading packages"); 14562 loadMediaPackages(processCids, uidArr); 14563 startCleaningPackages(); 14564 mInstallerService.onSecureContainersAvailable(); 14565 } else { 14566 if (DEBUG_SD_INSTALL) 14567 Log.i(TAG, "Unloading packages"); 14568 unloadMediaPackages(processCids, uidArr, reportStatus); 14569 } 14570 } 14571 14572 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14573 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14574 final int size = infos.size(); 14575 final String[] packageNames = new String[size]; 14576 final int[] packageUids = new int[size]; 14577 for (int i = 0; i < size; i++) { 14578 final ApplicationInfo info = infos.get(i); 14579 packageNames[i] = info.packageName; 14580 packageUids[i] = info.uid; 14581 } 14582 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14583 finishedReceiver); 14584 } 14585 14586 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14587 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14588 sendResourcesChangedBroadcast(mediaStatus, replacing, 14589 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14590 } 14591 14592 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14593 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14594 int size = pkgList.length; 14595 if (size > 0) { 14596 // Send broadcasts here 14597 Bundle extras = new Bundle(); 14598 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14599 if (uidArr != null) { 14600 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14601 } 14602 if (replacing) { 14603 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14604 } 14605 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14606 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14607 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14608 } 14609 } 14610 14611 /* 14612 * Look at potentially valid container ids from processCids If package 14613 * information doesn't match the one on record or package scanning fails, 14614 * the cid is added to list of removeCids. We currently don't delete stale 14615 * containers. 14616 */ 14617 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14618 ArrayList<String> pkgList = new ArrayList<String>(); 14619 Set<AsecInstallArgs> keys = processCids.keySet(); 14620 14621 for (AsecInstallArgs args : keys) { 14622 String codePath = processCids.get(args); 14623 if (DEBUG_SD_INSTALL) 14624 Log.i(TAG, "Loading container : " + args.cid); 14625 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14626 try { 14627 // Make sure there are no container errors first. 14628 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14629 Slog.e(TAG, "Failed to mount cid : " + args.cid 14630 + " when installing from sdcard"); 14631 continue; 14632 } 14633 // Check code path here. 14634 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14635 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14636 + " does not match one in settings " + codePath); 14637 continue; 14638 } 14639 // Parse package 14640 int parseFlags = mDefParseFlags; 14641 if (args.isExternalAsec()) { 14642 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14643 } 14644 if (args.isFwdLocked()) { 14645 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14646 } 14647 14648 synchronized (mInstallLock) { 14649 PackageParser.Package pkg = null; 14650 try { 14651 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14652 } catch (PackageManagerException e) { 14653 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14654 } 14655 // Scan the package 14656 if (pkg != null) { 14657 /* 14658 * TODO why is the lock being held? doPostInstall is 14659 * called in other places without the lock. This needs 14660 * to be straightened out. 14661 */ 14662 // writer 14663 synchronized (mPackages) { 14664 retCode = PackageManager.INSTALL_SUCCEEDED; 14665 pkgList.add(pkg.packageName); 14666 // Post process args 14667 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14668 pkg.applicationInfo.uid); 14669 } 14670 } else { 14671 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14672 } 14673 } 14674 14675 } finally { 14676 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14677 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14678 } 14679 } 14680 } 14681 // writer 14682 synchronized (mPackages) { 14683 // If the platform SDK has changed since the last time we booted, 14684 // we need to re-grant app permission to catch any new ones that 14685 // appear. This is really a hack, and means that apps can in some 14686 // cases get permissions that the user didn't initially explicitly 14687 // allow... it would be nice to have some better way to handle 14688 // this situation. 14689 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14690 if (regrantPermissions) 14691 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14692 + mSdkVersion + "; regranting permissions for external storage"); 14693 mSettings.mExternalSdkPlatform = mSdkVersion; 14694 14695 // Make sure group IDs have been assigned, and any permission 14696 // changes in other apps are accounted for 14697 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14698 | (regrantPermissions 14699 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14700 : 0)); 14701 14702 mSettings.updateExternalDatabaseVersion(); 14703 14704 // can downgrade to reader 14705 // Persist settings 14706 mSettings.writeLPr(); 14707 } 14708 // Send a broadcast to let everyone know we are done processing 14709 if (pkgList.size() > 0) { 14710 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14711 } 14712 } 14713 14714 /* 14715 * Utility method to unload a list of specified containers 14716 */ 14717 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14718 // Just unmount all valid containers. 14719 for (AsecInstallArgs arg : cidArgs) { 14720 synchronized (mInstallLock) { 14721 arg.doPostDeleteLI(false); 14722 } 14723 } 14724 } 14725 14726 /* 14727 * Unload packages mounted on external media. This involves deleting package 14728 * data from internal structures, sending broadcasts about diabled packages, 14729 * gc'ing to free up references, unmounting all secure containers 14730 * corresponding to packages on external media, and posting a 14731 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14732 * that we always have to post this message if status has been requested no 14733 * matter what. 14734 */ 14735 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14736 final boolean reportStatus) { 14737 if (DEBUG_SD_INSTALL) 14738 Log.i(TAG, "unloading media packages"); 14739 ArrayList<String> pkgList = new ArrayList<String>(); 14740 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14741 final Set<AsecInstallArgs> keys = processCids.keySet(); 14742 for (AsecInstallArgs args : keys) { 14743 String pkgName = args.getPackageName(); 14744 if (DEBUG_SD_INSTALL) 14745 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14746 // Delete package internally 14747 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14748 synchronized (mInstallLock) { 14749 boolean res = deletePackageLI(pkgName, null, false, null, null, 14750 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14751 if (res) { 14752 pkgList.add(pkgName); 14753 } else { 14754 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14755 failedList.add(args); 14756 } 14757 } 14758 } 14759 14760 // reader 14761 synchronized (mPackages) { 14762 // We didn't update the settings after removing each package; 14763 // write them now for all packages. 14764 mSettings.writeLPr(); 14765 } 14766 14767 // We have to absolutely send UPDATED_MEDIA_STATUS only 14768 // after confirming that all the receivers processed the ordered 14769 // broadcast when packages get disabled, force a gc to clean things up. 14770 // and unload all the containers. 14771 if (pkgList.size() > 0) { 14772 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14773 new IIntentReceiver.Stub() { 14774 public void performReceive(Intent intent, int resultCode, String data, 14775 Bundle extras, boolean ordered, boolean sticky, 14776 int sendingUser) throws RemoteException { 14777 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14778 reportStatus ? 1 : 0, 1, keys); 14779 mHandler.sendMessage(msg); 14780 } 14781 }); 14782 } else { 14783 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14784 keys); 14785 mHandler.sendMessage(msg); 14786 } 14787 } 14788 14789 private void loadPrivatePackages(VolumeInfo vol) { 14790 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14791 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14792 synchronized (mInstallLock) { 14793 synchronized (mPackages) { 14794 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14795 for (PackageSetting ps : packages) { 14796 final PackageParser.Package pkg; 14797 try { 14798 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14799 loaded.add(pkg.applicationInfo); 14800 } catch (PackageManagerException e) { 14801 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14802 } 14803 } 14804 14805 // TODO: regrant any permissions that changed based since original install 14806 14807 mSettings.writeLPr(); 14808 } 14809 } 14810 14811 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14812 sendResourcesChangedBroadcast(true, false, loaded, null); 14813 } 14814 14815 private void unloadPrivatePackages(VolumeInfo vol) { 14816 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14817 synchronized (mInstallLock) { 14818 synchronized (mPackages) { 14819 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14820 for (PackageSetting ps : packages) { 14821 if (ps.pkg == null) continue; 14822 14823 final ApplicationInfo info = ps.pkg.applicationInfo; 14824 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14825 if (deletePackageLI(ps.name, null, false, null, null, 14826 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14827 unloaded.add(info); 14828 } else { 14829 Slog.w(TAG, "Failed to unload " + ps.codePath); 14830 } 14831 } 14832 14833 mSettings.writeLPr(); 14834 } 14835 } 14836 14837 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14838 sendResourcesChangedBroadcast(false, false, unloaded, null); 14839 } 14840 14841 private void unfreezePackage(String packageName) { 14842 synchronized (mPackages) { 14843 final PackageSetting ps = mSettings.mPackages.get(packageName); 14844 if (ps != null) { 14845 ps.frozen = false; 14846 } 14847 } 14848 } 14849 14850 @Override 14851 public int movePackage(final String packageName, final String volumeUuid) { 14852 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14853 14854 final int moveId = mNextMoveId.getAndIncrement(); 14855 try { 14856 movePackageInternal(packageName, volumeUuid, moveId); 14857 } catch (PackageManagerException e) { 14858 Slog.w(TAG, "Failed to move " + packageName, e); 14859 mMoveCallbacks.notifyStatusChanged(moveId, 14860 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14861 } 14862 return moveId; 14863 } 14864 14865 private void movePackageInternal(final String packageName, final String volumeUuid, 14866 final int moveId) throws PackageManagerException { 14867 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14868 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14869 final PackageManager pm = mContext.getPackageManager(); 14870 14871 final boolean currentAsec; 14872 final String currentVolumeUuid; 14873 final File codeFile; 14874 final String installerPackageName; 14875 final String packageAbiOverride; 14876 final int appId; 14877 final String seinfo; 14878 final String label; 14879 14880 // reader 14881 synchronized (mPackages) { 14882 final PackageParser.Package pkg = mPackages.get(packageName); 14883 final PackageSetting ps = mSettings.mPackages.get(packageName); 14884 if (pkg == null || ps == null) { 14885 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14886 } 14887 14888 if (pkg.applicationInfo.isSystemApp()) { 14889 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14890 "Cannot move system application"); 14891 } 14892 14893 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14894 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14895 "Package already moved to " + volumeUuid); 14896 } 14897 14898 final File probe = new File(pkg.codePath); 14899 final File probeOat = new File(probe, "oat"); 14900 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14901 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14902 "Move only supported for modern cluster style installs"); 14903 } 14904 14905 if (ps.frozen) { 14906 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14907 "Failed to move already frozen package"); 14908 } 14909 ps.frozen = true; 14910 14911 currentAsec = pkg.applicationInfo.isForwardLocked() 14912 || pkg.applicationInfo.isExternalAsec(); 14913 currentVolumeUuid = ps.volumeUuid; 14914 codeFile = new File(pkg.codePath); 14915 installerPackageName = ps.installerPackageName; 14916 packageAbiOverride = ps.cpuAbiOverrideString; 14917 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14918 seinfo = pkg.applicationInfo.seinfo; 14919 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14920 } 14921 14922 // Now that we're guarded by frozen state, kill app during move 14923 killApplication(packageName, appId, "move pkg"); 14924 14925 final Bundle extras = new Bundle(); 14926 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14927 extras.putString(Intent.EXTRA_TITLE, label); 14928 mMoveCallbacks.notifyCreated(moveId, extras); 14929 14930 int installFlags; 14931 final boolean moveCompleteApp; 14932 final File measurePath; 14933 14934 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14935 installFlags = INSTALL_INTERNAL; 14936 moveCompleteApp = !currentAsec; 14937 measurePath = Environment.getDataAppDirectory(volumeUuid); 14938 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14939 installFlags = INSTALL_EXTERNAL; 14940 moveCompleteApp = false; 14941 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14942 } else { 14943 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14944 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14945 || !volume.isMountedWritable()) { 14946 unfreezePackage(packageName); 14947 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14948 "Move location not mounted private volume"); 14949 } 14950 14951 Preconditions.checkState(!currentAsec); 14952 14953 installFlags = INSTALL_INTERNAL; 14954 moveCompleteApp = true; 14955 measurePath = Environment.getDataAppDirectory(volumeUuid); 14956 } 14957 14958 final PackageStats stats = new PackageStats(null, -1); 14959 synchronized (mInstaller) { 14960 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14961 unfreezePackage(packageName); 14962 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14963 "Failed to measure package size"); 14964 } 14965 } 14966 14967 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14968 + stats.dataSize); 14969 14970 final long startFreeBytes = measurePath.getFreeSpace(); 14971 final long sizeBytes; 14972 if (moveCompleteApp) { 14973 sizeBytes = stats.codeSize + stats.dataSize; 14974 } else { 14975 sizeBytes = stats.codeSize; 14976 } 14977 14978 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14979 unfreezePackage(packageName); 14980 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14981 "Not enough free space to move"); 14982 } 14983 14984 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14985 14986 final CountDownLatch installedLatch = new CountDownLatch(1); 14987 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14988 @Override 14989 public void onUserActionRequired(Intent intent) throws RemoteException { 14990 throw new IllegalStateException(); 14991 } 14992 14993 @Override 14994 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14995 Bundle extras) throws RemoteException { 14996 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14997 + PackageManager.installStatusToString(returnCode, msg)); 14998 14999 installedLatch.countDown(); 15000 15001 // Regardless of success or failure of the move operation, 15002 // always unfreeze the package 15003 unfreezePackage(packageName); 15004 15005 final int status = PackageManager.installStatusToPublicStatus(returnCode); 15006 switch (status) { 15007 case PackageInstaller.STATUS_SUCCESS: 15008 mMoveCallbacks.notifyStatusChanged(moveId, 15009 PackageManager.MOVE_SUCCEEDED); 15010 break; 15011 case PackageInstaller.STATUS_FAILURE_STORAGE: 15012 mMoveCallbacks.notifyStatusChanged(moveId, 15013 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 15014 break; 15015 default: 15016 mMoveCallbacks.notifyStatusChanged(moveId, 15017 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 15018 break; 15019 } 15020 } 15021 }; 15022 15023 final MoveInfo move; 15024 if (moveCompleteApp) { 15025 // Kick off a thread to report progress estimates 15026 new Thread() { 15027 @Override 15028 public void run() { 15029 while (true) { 15030 try { 15031 if (installedLatch.await(1, TimeUnit.SECONDS)) { 15032 break; 15033 } 15034 } catch (InterruptedException ignored) { 15035 } 15036 15037 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 15038 final int progress = 10 + (int) MathUtils.constrain( 15039 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 15040 mMoveCallbacks.notifyStatusChanged(moveId, progress); 15041 } 15042 } 15043 }.start(); 15044 15045 final String dataAppName = codeFile.getName(); 15046 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 15047 dataAppName, appId, seinfo); 15048 } else { 15049 move = null; 15050 } 15051 15052 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 15053 15054 final Message msg = mHandler.obtainMessage(INIT_COPY); 15055 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 15056 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 15057 installerPackageName, volumeUuid, null, user, packageAbiOverride); 15058 mHandler.sendMessage(msg); 15059 } 15060 15061 @Override 15062 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 15063 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 15064 15065 final int realMoveId = mNextMoveId.getAndIncrement(); 15066 final Bundle extras = new Bundle(); 15067 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 15068 mMoveCallbacks.notifyCreated(realMoveId, extras); 15069 15070 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 15071 @Override 15072 public void onCreated(int moveId, Bundle extras) { 15073 // Ignored 15074 } 15075 15076 @Override 15077 public void onStatusChanged(int moveId, int status, long estMillis) { 15078 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 15079 } 15080 }; 15081 15082 final StorageManager storage = mContext.getSystemService(StorageManager.class); 15083 storage.setPrimaryStorageUuid(volumeUuid, callback); 15084 return realMoveId; 15085 } 15086 15087 @Override 15088 public int getMoveStatus(int moveId) { 15089 mContext.enforceCallingOrSelfPermission( 15090 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15091 return mMoveCallbacks.mLastStatus.get(moveId); 15092 } 15093 15094 @Override 15095 public void registerMoveCallback(IPackageMoveObserver callback) { 15096 mContext.enforceCallingOrSelfPermission( 15097 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15098 mMoveCallbacks.register(callback); 15099 } 15100 15101 @Override 15102 public void unregisterMoveCallback(IPackageMoveObserver callback) { 15103 mContext.enforceCallingOrSelfPermission( 15104 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 15105 mMoveCallbacks.unregister(callback); 15106 } 15107 15108 @Override 15109 public boolean setInstallLocation(int loc) { 15110 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 15111 null); 15112 if (getInstallLocation() == loc) { 15113 return true; 15114 } 15115 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 15116 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 15117 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 15118 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 15119 return true; 15120 } 15121 return false; 15122 } 15123 15124 @Override 15125 public int getInstallLocation() { 15126 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 15127 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 15128 PackageHelper.APP_INSTALL_AUTO); 15129 } 15130 15131 /** Called by UserManagerService */ 15132 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15133 mDirtyUsers.remove(userHandle); 15134 mSettings.removeUserLPw(userHandle); 15135 mPendingBroadcasts.remove(userHandle); 15136 if (mInstaller != null) { 15137 // Technically, we shouldn't be doing this with the package lock 15138 // held. However, this is very rare, and there is already so much 15139 // other disk I/O going on, that we'll let it slide for now. 15140 final StorageManager storage = StorageManager.from(mContext); 15141 final List<VolumeInfo> vols = storage.getVolumes(); 15142 for (VolumeInfo vol : vols) { 15143 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15144 final String volumeUuid = vol.getFsUuid(); 15145 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15146 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15147 } 15148 } 15149 } 15150 mUserNeedsBadging.delete(userHandle); 15151 removeUnusedPackagesLILPw(userManager, userHandle); 15152 } 15153 15154 /** 15155 * We're removing userHandle and would like to remove any downloaded packages 15156 * that are no longer in use by any other user. 15157 * @param userHandle the user being removed 15158 */ 15159 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15160 final boolean DEBUG_CLEAN_APKS = false; 15161 int [] users = userManager.getUserIdsLPr(); 15162 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15163 while (psit.hasNext()) { 15164 PackageSetting ps = psit.next(); 15165 if (ps.pkg == null) { 15166 continue; 15167 } 15168 final String packageName = ps.pkg.packageName; 15169 // Skip over if system app 15170 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15171 continue; 15172 } 15173 if (DEBUG_CLEAN_APKS) { 15174 Slog.i(TAG, "Checking package " + packageName); 15175 } 15176 boolean keep = false; 15177 for (int i = 0; i < users.length; i++) { 15178 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15179 keep = true; 15180 if (DEBUG_CLEAN_APKS) { 15181 Slog.i(TAG, " Keeping package " + packageName + " for user " 15182 + users[i]); 15183 } 15184 break; 15185 } 15186 } 15187 if (!keep) { 15188 if (DEBUG_CLEAN_APKS) { 15189 Slog.i(TAG, " Removing package " + packageName); 15190 } 15191 mHandler.post(new Runnable() { 15192 public void run() { 15193 deletePackageX(packageName, userHandle, 0); 15194 } //end run 15195 }); 15196 } 15197 } 15198 } 15199 15200 /** Called by UserManagerService */ 15201 void createNewUserLILPw(int userHandle, File path) { 15202 if (mInstaller != null) { 15203 mInstaller.createUserConfig(userHandle); 15204 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15205 } 15206 } 15207 15208 void newUserCreatedLILPw(final int userHandle) { 15209 // We cannot grant the default permissions with a lock held as 15210 // we query providers from other components for default handlers 15211 // such as enabled IMEs, etc. 15212 mHandler.post(new Runnable() { 15213 @Override 15214 public void run() { 15215 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 15216 } 15217 }); 15218 } 15219 15220 @Override 15221 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15222 mContext.enforceCallingOrSelfPermission( 15223 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15224 "Only package verification agents can read the verifier device identity"); 15225 15226 synchronized (mPackages) { 15227 return mSettings.getVerifierDeviceIdentityLPw(); 15228 } 15229 } 15230 15231 @Override 15232 public void setPermissionEnforced(String permission, boolean enforced) { 15233 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15234 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15235 synchronized (mPackages) { 15236 if (mSettings.mReadExternalStorageEnforced == null 15237 || mSettings.mReadExternalStorageEnforced != enforced) { 15238 mSettings.mReadExternalStorageEnforced = enforced; 15239 mSettings.writeLPr(); 15240 } 15241 } 15242 // kill any non-foreground processes so we restart them and 15243 // grant/revoke the GID. 15244 final IActivityManager am = ActivityManagerNative.getDefault(); 15245 if (am != null) { 15246 final long token = Binder.clearCallingIdentity(); 15247 try { 15248 am.killProcessesBelowForeground("setPermissionEnforcement"); 15249 } catch (RemoteException e) { 15250 } finally { 15251 Binder.restoreCallingIdentity(token); 15252 } 15253 } 15254 } else { 15255 throw new IllegalArgumentException("No selective enforcement for " + permission); 15256 } 15257 } 15258 15259 @Override 15260 @Deprecated 15261 public boolean isPermissionEnforced(String permission) { 15262 return true; 15263 } 15264 15265 @Override 15266 public boolean isStorageLow() { 15267 final long token = Binder.clearCallingIdentity(); 15268 try { 15269 final DeviceStorageMonitorInternal 15270 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15271 if (dsm != null) { 15272 return dsm.isMemoryLow(); 15273 } else { 15274 return false; 15275 } 15276 } finally { 15277 Binder.restoreCallingIdentity(token); 15278 } 15279 } 15280 15281 @Override 15282 public IPackageInstaller getPackageInstaller() { 15283 return mInstallerService; 15284 } 15285 15286 private boolean userNeedsBadging(int userId) { 15287 int index = mUserNeedsBadging.indexOfKey(userId); 15288 if (index < 0) { 15289 final UserInfo userInfo; 15290 final long token = Binder.clearCallingIdentity(); 15291 try { 15292 userInfo = sUserManager.getUserInfo(userId); 15293 } finally { 15294 Binder.restoreCallingIdentity(token); 15295 } 15296 final boolean b; 15297 if (userInfo != null && userInfo.isManagedProfile()) { 15298 b = true; 15299 } else { 15300 b = false; 15301 } 15302 mUserNeedsBadging.put(userId, b); 15303 return b; 15304 } 15305 return mUserNeedsBadging.valueAt(index); 15306 } 15307 15308 @Override 15309 public KeySet getKeySetByAlias(String packageName, String alias) { 15310 if (packageName == null || alias == null) { 15311 return null; 15312 } 15313 synchronized(mPackages) { 15314 final PackageParser.Package pkg = mPackages.get(packageName); 15315 if (pkg == null) { 15316 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15317 throw new IllegalArgumentException("Unknown package: " + packageName); 15318 } 15319 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15320 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15321 } 15322 } 15323 15324 @Override 15325 public KeySet getSigningKeySet(String packageName) { 15326 if (packageName == null) { 15327 return null; 15328 } 15329 synchronized(mPackages) { 15330 final PackageParser.Package pkg = mPackages.get(packageName); 15331 if (pkg == null) { 15332 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15333 throw new IllegalArgumentException("Unknown package: " + packageName); 15334 } 15335 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15336 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15337 throw new SecurityException("May not access signing KeySet of other apps."); 15338 } 15339 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15340 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15341 } 15342 } 15343 15344 @Override 15345 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15346 if (packageName == null || ks == null) { 15347 return false; 15348 } 15349 synchronized(mPackages) { 15350 final PackageParser.Package pkg = mPackages.get(packageName); 15351 if (pkg == null) { 15352 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15353 throw new IllegalArgumentException("Unknown package: " + packageName); 15354 } 15355 IBinder ksh = ks.getToken(); 15356 if (ksh instanceof KeySetHandle) { 15357 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15358 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15359 } 15360 return false; 15361 } 15362 } 15363 15364 @Override 15365 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15366 if (packageName == null || ks == null) { 15367 return false; 15368 } 15369 synchronized(mPackages) { 15370 final PackageParser.Package pkg = mPackages.get(packageName); 15371 if (pkg == null) { 15372 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15373 throw new IllegalArgumentException("Unknown package: " + packageName); 15374 } 15375 IBinder ksh = ks.getToken(); 15376 if (ksh instanceof KeySetHandle) { 15377 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15378 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15379 } 15380 return false; 15381 } 15382 } 15383 15384 public void getUsageStatsIfNoPackageUsageInfo() { 15385 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15386 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15387 if (usm == null) { 15388 throw new IllegalStateException("UsageStatsManager must be initialized"); 15389 } 15390 long now = System.currentTimeMillis(); 15391 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15392 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15393 String packageName = entry.getKey(); 15394 PackageParser.Package pkg = mPackages.get(packageName); 15395 if (pkg == null) { 15396 continue; 15397 } 15398 UsageStats usage = entry.getValue(); 15399 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15400 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15401 } 15402 } 15403 } 15404 15405 /** 15406 * Check and throw if the given before/after packages would be considered a 15407 * downgrade. 15408 */ 15409 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15410 throws PackageManagerException { 15411 if (after.versionCode < before.mVersionCode) { 15412 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15413 "Update version code " + after.versionCode + " is older than current " 15414 + before.mVersionCode); 15415 } else if (after.versionCode == before.mVersionCode) { 15416 if (after.baseRevisionCode < before.baseRevisionCode) { 15417 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15418 "Update base revision code " + after.baseRevisionCode 15419 + " is older than current " + before.baseRevisionCode); 15420 } 15421 15422 if (!ArrayUtils.isEmpty(after.splitNames)) { 15423 for (int i = 0; i < after.splitNames.length; i++) { 15424 final String splitName = after.splitNames[i]; 15425 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15426 if (j != -1) { 15427 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15428 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15429 "Update split " + splitName + " revision code " 15430 + after.splitRevisionCodes[i] + " is older than current " 15431 + before.splitRevisionCodes[j]); 15432 } 15433 } 15434 } 15435 } 15436 } 15437 } 15438 15439 private static class MoveCallbacks extends Handler { 15440 private static final int MSG_CREATED = 1; 15441 private static final int MSG_STATUS_CHANGED = 2; 15442 15443 private final RemoteCallbackList<IPackageMoveObserver> 15444 mCallbacks = new RemoteCallbackList<>(); 15445 15446 private final SparseIntArray mLastStatus = new SparseIntArray(); 15447 15448 public MoveCallbacks(Looper looper) { 15449 super(looper); 15450 } 15451 15452 public void register(IPackageMoveObserver callback) { 15453 mCallbacks.register(callback); 15454 } 15455 15456 public void unregister(IPackageMoveObserver callback) { 15457 mCallbacks.unregister(callback); 15458 } 15459 15460 @Override 15461 public void handleMessage(Message msg) { 15462 final SomeArgs args = (SomeArgs) msg.obj; 15463 final int n = mCallbacks.beginBroadcast(); 15464 for (int i = 0; i < n; i++) { 15465 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15466 try { 15467 invokeCallback(callback, msg.what, args); 15468 } catch (RemoteException ignored) { 15469 } 15470 } 15471 mCallbacks.finishBroadcast(); 15472 args.recycle(); 15473 } 15474 15475 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15476 throws RemoteException { 15477 switch (what) { 15478 case MSG_CREATED: { 15479 callback.onCreated(args.argi1, (Bundle) args.arg2); 15480 break; 15481 } 15482 case MSG_STATUS_CHANGED: { 15483 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15484 break; 15485 } 15486 } 15487 } 15488 15489 private void notifyCreated(int moveId, Bundle extras) { 15490 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15491 15492 final SomeArgs args = SomeArgs.obtain(); 15493 args.argi1 = moveId; 15494 args.arg2 = extras; 15495 obtainMessage(MSG_CREATED, args).sendToTarget(); 15496 } 15497 15498 private void notifyStatusChanged(int moveId, int status) { 15499 notifyStatusChanged(moveId, status, -1); 15500 } 15501 15502 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15503 Slog.v(TAG, "Move " + moveId + " status " + status); 15504 15505 final SomeArgs args = SomeArgs.obtain(); 15506 args.argi1 = moveId; 15507 args.argi2 = status; 15508 args.arg3 = estMillis; 15509 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15510 15511 synchronized (mLastStatus) { 15512 mLastStatus.put(moveId, status); 15513 } 15514 } 15515 } 15516 15517 private final class OnPermissionChangeListeners extends Handler { 15518 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15519 15520 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15521 new RemoteCallbackList<>(); 15522 15523 public OnPermissionChangeListeners(Looper looper) { 15524 super(looper); 15525 } 15526 15527 @Override 15528 public void handleMessage(Message msg) { 15529 switch (msg.what) { 15530 case MSG_ON_PERMISSIONS_CHANGED: { 15531 final int uid = msg.arg1; 15532 handleOnPermissionsChanged(uid); 15533 } break; 15534 } 15535 } 15536 15537 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15538 mPermissionListeners.register(listener); 15539 15540 } 15541 15542 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15543 mPermissionListeners.unregister(listener); 15544 } 15545 15546 public void onPermissionsChanged(int uid) { 15547 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15548 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15549 } 15550 } 15551 15552 private void handleOnPermissionsChanged(int uid) { 15553 final int count = mPermissionListeners.beginBroadcast(); 15554 try { 15555 for (int i = 0; i < count; i++) { 15556 IOnPermissionsChangeListener callback = mPermissionListeners 15557 .getBroadcastItem(i); 15558 try { 15559 callback.onPermissionsChanged(uid); 15560 } catch (RemoteException e) { 15561 Log.e(TAG, "Permission listener is dead", e); 15562 } 15563 } 15564 } finally { 15565 mPermissionListeners.finishBroadcast(); 15566 } 15567 } 15568 } 15569 15570 private class PackageManagerInternalImpl extends PackageManagerInternal { 15571 @Override 15572 public void setLocationPackagesProvider(PackagesProvider provider) { 15573 synchronized (mPackages) { 15574 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 15575 } 15576 } 15577 15578 @Override 15579 public void setImePackagesProvider(PackagesProvider provider) { 15580 synchronized (mPackages) { 15581 mDefaultPermissionPolicy.setImePackagesProviderLPr(provider); 15582 } 15583 } 15584 15585 @Override 15586 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 15587 synchronized (mPackages) { 15588 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 15589 } 15590 } 15591 } 15592} 15593