PackageManagerService.java revision e2f43948d1de58e49192b97306e8a4e1c99412f4
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.IPackageDataObserver; 95import android.content.pm.IPackageDeleteObserver; 96import android.content.pm.IPackageDeleteObserver2; 97import android.content.pm.IPackageInstallObserver2; 98import android.content.pm.IPackageInstaller; 99import android.content.pm.IPackageManager; 100import android.content.pm.IPackageMoveObserver; 101import android.content.pm.IPackageStatsObserver; 102import android.content.pm.InstrumentationInfo; 103import android.content.pm.IntentFilterVerificationInfo; 104import android.content.pm.KeySet; 105import android.content.pm.ManifestDigest; 106import android.content.pm.PackageCleanItem; 107import android.content.pm.PackageInfo; 108import android.content.pm.PackageInfoLite; 109import android.content.pm.PackageInstaller; 110import android.content.pm.PackageManager; 111import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 112import android.content.pm.PackageParser; 113import android.content.pm.PackageParser.ActivityIntentInfo; 114import android.content.pm.PackageParser.PackageLite; 115import android.content.pm.PackageParser.PackageParserException; 116import android.content.pm.PackageStats; 117import android.content.pm.PackageUserState; 118import android.content.pm.ParceledListSlice; 119import android.content.pm.PermissionGroupInfo; 120import android.content.pm.PermissionInfo; 121import android.content.pm.ProviderInfo; 122import android.content.pm.ResolveInfo; 123import android.content.pm.ServiceInfo; 124import android.content.pm.Signature; 125import android.content.pm.UserInfo; 126import android.content.pm.VerificationParams; 127import android.content.pm.VerifierDeviceIdentity; 128import android.content.pm.VerifierInfo; 129import android.content.res.Resources; 130import android.hardware.display.DisplayManager; 131import android.net.Uri; 132import android.os.Binder; 133import android.os.Build; 134import android.os.Bundle; 135import android.os.Debug; 136import android.os.Environment; 137import android.os.Environment.UserEnvironment; 138import android.os.FileUtils; 139import android.os.Handler; 140import android.os.IBinder; 141import android.os.Looper; 142import android.os.Message; 143import android.os.Parcel; 144import android.os.ParcelFileDescriptor; 145import android.os.Process; 146import android.os.RemoteCallbackList; 147import android.os.RemoteException; 148import android.os.SELinux; 149import android.os.ServiceManager; 150import android.os.SystemClock; 151import android.os.SystemProperties; 152import android.os.UserHandle; 153import android.os.UserManager; 154import android.os.storage.IMountService; 155import android.os.storage.StorageEventListener; 156import android.os.storage.StorageManager; 157import android.os.storage.VolumeInfo; 158import android.os.storage.VolumeRecord; 159import android.security.KeyStore; 160import android.security.SystemKeyStore; 161import android.system.ErrnoException; 162import android.system.Os; 163import android.system.StructStat; 164import android.text.TextUtils; 165import android.text.format.DateUtils; 166import android.util.ArrayMap; 167import android.util.ArraySet; 168import android.util.AtomicFile; 169import android.util.DisplayMetrics; 170import android.util.EventLog; 171import android.util.ExceptionUtils; 172import android.util.Log; 173import android.util.LogPrinter; 174import android.util.MathUtils; 175import android.util.PrintStreamPrinter; 176import android.util.Slog; 177import android.util.SparseArray; 178import android.util.SparseBooleanArray; 179import android.util.SparseIntArray; 180import android.util.Xml; 181import android.view.Display; 182 183import dalvik.system.DexFile; 184import dalvik.system.VMRuntime; 185 186import libcore.io.IoUtils; 187import libcore.util.EmptyArray; 188 189import com.android.internal.R; 190import com.android.internal.app.IMediaContainerService; 191import com.android.internal.app.ResolverActivity; 192import com.android.internal.content.NativeLibraryHelper; 193import com.android.internal.content.PackageHelper; 194import com.android.internal.os.IParcelFileDescriptorFactory; 195import com.android.internal.os.SomeArgs; 196import com.android.internal.util.ArrayUtils; 197import com.android.internal.util.FastPrintWriter; 198import com.android.internal.util.FastXmlSerializer; 199import com.android.internal.util.IndentingPrintWriter; 200import com.android.internal.util.Preconditions; 201import com.android.server.EventLogTags; 202import com.android.server.FgThread; 203import com.android.server.IntentResolver; 204import com.android.server.LocalServices; 205import com.android.server.ServiceThread; 206import com.android.server.SystemConfig; 207import com.android.server.Watchdog; 208import com.android.server.pm.Settings.DatabaseVersion; 209import com.android.server.pm.PermissionsState.PermissionState; 210import com.android.server.storage.DeviceStorageMonitorInternal; 211 212import org.xmlpull.v1.XmlPullParser; 213import org.xmlpull.v1.XmlSerializer; 214 215import java.io.BufferedInputStream; 216import java.io.BufferedOutputStream; 217import java.io.BufferedReader; 218import java.io.ByteArrayInputStream; 219import java.io.ByteArrayOutputStream; 220import java.io.File; 221import java.io.FileDescriptor; 222import java.io.FileNotFoundException; 223import java.io.FileOutputStream; 224import java.io.FileReader; 225import java.io.FilenameFilter; 226import java.io.IOException; 227import java.io.InputStream; 228import java.io.PrintWriter; 229import java.nio.charset.StandardCharsets; 230import java.security.NoSuchAlgorithmException; 231import java.security.PublicKey; 232import java.security.cert.CertificateEncodingException; 233import java.security.cert.CertificateException; 234import java.text.SimpleDateFormat; 235import java.util.ArrayList; 236import java.util.Arrays; 237import java.util.Collection; 238import java.util.Collections; 239import java.util.Comparator; 240import java.util.Date; 241import java.util.Iterator; 242import java.util.List; 243import java.util.Map; 244import java.util.Objects; 245import java.util.Set; 246import java.util.concurrent.CountDownLatch; 247import java.util.concurrent.TimeUnit; 248import java.util.concurrent.atomic.AtomicBoolean; 249import java.util.concurrent.atomic.AtomicInteger; 250import java.util.concurrent.atomic.AtomicLong; 251 252/** 253 * Keep track of all those .apks everywhere. 254 * 255 * This is very central to the platform's security; please run the unit 256 * tests whenever making modifications here: 257 * 258mmm frameworks/base/tests/AndroidTests 259adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 260adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 261 * 262 * {@hide} 263 */ 264public class PackageManagerService extends IPackageManager.Stub { 265 static final String TAG = "PackageManager"; 266 static final boolean DEBUG_SETTINGS = false; 267 static final boolean DEBUG_PREFERRED = false; 268 static final boolean DEBUG_UPGRADE = false; 269 private static final boolean DEBUG_BACKUP = true; 270 private static final boolean DEBUG_INSTALL = false; 271 private static final boolean DEBUG_REMOVE = false; 272 private static final boolean DEBUG_BROADCASTS = false; 273 private static final boolean DEBUG_SHOW_INFO = false; 274 private static final boolean DEBUG_PACKAGE_INFO = false; 275 private static final boolean DEBUG_INTENT_MATCHING = false; 276 private static final boolean DEBUG_PACKAGE_SCANNING = false; 277 private static final boolean DEBUG_VERIFY = false; 278 private static final boolean DEBUG_DEXOPT = false; 279 private static final boolean DEBUG_ABI_SELECTION = false; 280 281 private static final int RADIO_UID = Process.PHONE_UID; 282 private static final int LOG_UID = Process.LOG_UID; 283 private static final int NFC_UID = Process.NFC_UID; 284 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 285 private static final int SHELL_UID = Process.SHELL_UID; 286 287 // Cap the size of permission trees that 3rd party apps can define 288 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 289 290 // Suffix used during package installation when copying/moving 291 // package apks to install directory. 292 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 293 294 static final int SCAN_NO_DEX = 1<<1; 295 static final int SCAN_FORCE_DEX = 1<<2; 296 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 297 static final int SCAN_NEW_INSTALL = 1<<4; 298 static final int SCAN_NO_PATHS = 1<<5; 299 static final int SCAN_UPDATE_TIME = 1<<6; 300 static final int SCAN_DEFER_DEX = 1<<7; 301 static final int SCAN_BOOTING = 1<<8; 302 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 303 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 304 static final int SCAN_REQUIRE_KNOWN = 1<<12; 305 306 static final int REMOVE_CHATTY = 1<<16; 307 308 private static final int[] EMPTY_INT_ARRAY = new int[0]; 309 310 /** 311 * Timeout (in milliseconds) after which the watchdog should declare that 312 * our handler thread is wedged. The usual default for such things is one 313 * minute but we sometimes do very lengthy I/O operations on this thread, 314 * such as installing multi-gigabyte applications, so ours needs to be longer. 315 */ 316 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 317 318 /** 319 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 320 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 321 * settings entry if available, otherwise we use the hardcoded default. If it's been 322 * more than this long since the last fstrim, we force one during the boot sequence. 323 * 324 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 325 * one gets run at the next available charging+idle time. This final mandatory 326 * no-fstrim check kicks in only of the other scheduling criteria is never met. 327 */ 328 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 329 330 /** 331 * Whether verification is enabled by default. 332 */ 333 private static final boolean DEFAULT_VERIFY_ENABLE = true; 334 335 /** 336 * The default maximum time to wait for the verification agent to return in 337 * milliseconds. 338 */ 339 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 340 341 /** 342 * The default response for package verification timeout. 343 * 344 * This can be either PackageManager.VERIFICATION_ALLOW or 345 * PackageManager.VERIFICATION_REJECT. 346 */ 347 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 348 349 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 350 351 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 352 DEFAULT_CONTAINER_PACKAGE, 353 "com.android.defcontainer.DefaultContainerService"); 354 355 private static final String KILL_APP_REASON_GIDS_CHANGED = 356 "permission grant or revoke changed gids"; 357 358 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 359 "permissions revoked"; 360 361 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 362 363 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 364 365 /** Permission grant: not grant the permission. */ 366 private static final int GRANT_DENIED = 1; 367 368 /** Permission grant: grant the permission as an install permission. */ 369 private static final int GRANT_INSTALL = 2; 370 371 /** Permission grant: grant the permission as a runtime one. */ 372 private static final int GRANT_RUNTIME = 3; 373 374 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 375 private static final int GRANT_UPGRADE = 4; 376 377 final ServiceThread mHandlerThread; 378 379 final PackageHandler mHandler; 380 381 /** 382 * Messages for {@link #mHandler} that need to wait for system ready before 383 * being dispatched. 384 */ 385 private ArrayList<Message> mPostSystemReadyMessages; 386 387 final int mSdkVersion = Build.VERSION.SDK_INT; 388 389 final Context mContext; 390 final boolean mFactoryTest; 391 final boolean mOnlyCore; 392 final boolean mLazyDexOpt; 393 final long mDexOptLRUThresholdInMills; 394 final DisplayMetrics mMetrics; 395 final int mDefParseFlags; 396 final String[] mSeparateProcesses; 397 final boolean mIsUpgrade; 398 399 // This is where all application persistent data goes. 400 final File mAppDataDir; 401 402 // This is where all application persistent data goes for secondary users. 403 final File mUserAppDataDir; 404 405 /** The location for ASEC container files on internal storage. */ 406 final String mAsecInternalPath; 407 408 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 409 // LOCK HELD. Can be called with mInstallLock held. 410 final Installer mInstaller; 411 412 /** Directory where installed third-party apps stored */ 413 final File mAppInstallDir; 414 415 /** 416 * Directory to which applications installed internally have their 417 * 32 bit native libraries copied. 418 */ 419 private File mAppLib32InstallDir; 420 421 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 422 // apps. 423 final File mDrmAppPrivateInstallDir; 424 425 // ---------------------------------------------------------------- 426 427 // Lock for state used when installing and doing other long running 428 // operations. Methods that must be called with this lock held have 429 // the suffix "LI". 430 final Object mInstallLock = new Object(); 431 432 // ---------------------------------------------------------------- 433 434 // Keys are String (package name), values are Package. This also serves 435 // as the lock for the global state. Methods that must be called with 436 // this lock held have the prefix "LP". 437 final ArrayMap<String, PackageParser.Package> mPackages = 438 new ArrayMap<String, PackageParser.Package>(); 439 440 // Tracks available target package names -> overlay package paths. 441 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 442 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 443 444 final Settings mSettings; 445 boolean mRestoredSettings; 446 447 // System configuration read by SystemConfig. 448 final int[] mGlobalGids; 449 final SparseArray<ArraySet<String>> mSystemPermissions; 450 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 451 452 // If mac_permissions.xml was found for seinfo labeling. 453 boolean mFoundPolicyFile; 454 455 // If a recursive restorecon of /data/data/<pkg> is needed. 456 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 457 458 public static final class SharedLibraryEntry { 459 public final String path; 460 public final String apk; 461 462 SharedLibraryEntry(String _path, String _apk) { 463 path = _path; 464 apk = _apk; 465 } 466 } 467 468 // Currently known shared libraries. 469 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 470 new ArrayMap<String, SharedLibraryEntry>(); 471 472 // All available activities, for your resolving pleasure. 473 final ActivityIntentResolver mActivities = 474 new ActivityIntentResolver(); 475 476 // All available receivers, for your resolving pleasure. 477 final ActivityIntentResolver mReceivers = 478 new ActivityIntentResolver(); 479 480 // All available services, for your resolving pleasure. 481 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 482 483 // All available providers, for your resolving pleasure. 484 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 485 486 // Mapping from provider base names (first directory in content URI codePath) 487 // to the provider information. 488 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 489 new ArrayMap<String, PackageParser.Provider>(); 490 491 // Mapping from instrumentation class names to info about them. 492 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 493 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 494 495 // Mapping from permission names to info about them. 496 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 497 new ArrayMap<String, PackageParser.PermissionGroup>(); 498 499 // Packages whose data we have transfered into another package, thus 500 // should no longer exist. 501 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 502 503 // Broadcast actions that are only available to the system. 504 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 505 506 /** List of packages waiting for verification. */ 507 final SparseArray<PackageVerificationState> mPendingVerification 508 = new SparseArray<PackageVerificationState>(); 509 510 /** Set of packages associated with each app op permission. */ 511 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 512 513 final PackageInstallerService mInstallerService; 514 515 private final PackageDexOptimizer mPackageDexOptimizer; 516 517 private AtomicInteger mNextMoveId = new AtomicInteger(); 518 private final MoveCallbacks mMoveCallbacks; 519 520 // Cache of users who need badging. 521 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 522 523 /** Token for keys in mPendingVerification. */ 524 private int mPendingVerificationToken = 0; 525 526 volatile boolean mSystemReady; 527 volatile boolean mSafeMode; 528 volatile boolean mHasSystemUidErrors; 529 530 ApplicationInfo mAndroidApplication; 531 final ActivityInfo mResolveActivity = new ActivityInfo(); 532 final ResolveInfo mResolveInfo = new ResolveInfo(); 533 ComponentName mResolveComponentName; 534 PackageParser.Package mPlatformPackage; 535 ComponentName mCustomResolverComponentName; 536 537 boolean mResolverReplaced = false; 538 539 private final ComponentName mIntentFilterVerifierComponent; 540 private int mIntentFilterVerificationToken = 0; 541 542 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 543 = new SparseArray<IntentFilterVerificationState>(); 544 545 private interface IntentFilterVerifier<T extends IntentFilter> { 546 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 547 T filter, String packageName); 548 void startVerifications(int userId); 549 void receiveVerificationResponse(int verificationId); 550 } 551 552 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 553 private Context mContext; 554 private ComponentName mIntentFilterVerifierComponent; 555 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 556 557 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 558 mContext = context; 559 mIntentFilterVerifierComponent = verifierComponent; 560 } 561 562 private String getDefaultScheme() { 563 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 564 return IntentFilter.SCHEME_HTTP; 565 } 566 567 @Override 568 public void startVerifications(int userId) { 569 // Launch verifications requests 570 int count = mCurrentIntentFilterVerifications.size(); 571 for (int n=0; n<count; n++) { 572 int verificationId = mCurrentIntentFilterVerifications.get(n); 573 final IntentFilterVerificationState ivs = 574 mIntentFilterVerificationStates.get(verificationId); 575 576 String packageName = ivs.getPackageName(); 577 578 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 579 final int filterCount = filters.size(); 580 ArraySet<String> domainsSet = new ArraySet<>(); 581 for (int m=0; m<filterCount; m++) { 582 PackageParser.ActivityIntentInfo filter = filters.get(m); 583 domainsSet.addAll(filter.getHostsList()); 584 } 585 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 586 synchronized (mPackages) { 587 if (mSettings.createIntentFilterVerificationIfNeededLPw( 588 packageName, domainsList) != null) { 589 scheduleWriteSettingsLocked(); 590 } 591 } 592 sendVerificationRequest(userId, verificationId, ivs); 593 } 594 mCurrentIntentFilterVerifications.clear(); 595 } 596 597 private void sendVerificationRequest(int userId, int verificationId, 598 IntentFilterVerificationState ivs) { 599 600 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 601 verificationIntent.putExtra( 602 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 603 verificationId); 604 verificationIntent.putExtra( 605 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 606 getDefaultScheme()); 607 verificationIntent.putExtra( 608 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 609 ivs.getHostsString()); 610 verificationIntent.putExtra( 611 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 612 ivs.getPackageName()); 613 verificationIntent.setComponent(mIntentFilterVerifierComponent); 614 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 615 616 UserHandle user = new UserHandle(userId); 617 mContext.sendBroadcastAsUser(verificationIntent, user); 618 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 619 } 620 621 public void receiveVerificationResponse(int verificationId) { 622 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 623 624 final boolean verified = ivs.isVerified(); 625 626 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 627 final int count = filters.size(); 628 for (int n=0; n<count; n++) { 629 PackageParser.ActivityIntentInfo filter = filters.get(n); 630 filter.setVerified(verified); 631 632 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 633 + verified + " and hosts:" + ivs.getHostsString()); 634 } 635 636 mIntentFilterVerificationStates.remove(verificationId); 637 638 final String packageName = ivs.getPackageName(); 639 IntentFilterVerificationInfo ivi = null; 640 641 synchronized (mPackages) { 642 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 643 } 644 if (ivi == null) { 645 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 646 + verificationId + " packageName:" + packageName); 647 return; 648 } 649 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 650 + verificationId); 651 652 synchronized (mPackages) { 653 if (verified) { 654 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 655 } else { 656 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 657 } 658 scheduleWriteSettingsLocked(); 659 660 final int userId = ivs.getUserId(); 661 if (userId != UserHandle.USER_ALL) { 662 final int userStatus = 663 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 664 665 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 666 boolean needUpdate = false; 667 668 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 669 // already been set by the User thru the Disambiguation dialog 670 switch (userStatus) { 671 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 672 if (verified) { 673 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 674 } else { 675 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 676 } 677 needUpdate = true; 678 break; 679 680 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 681 if (verified) { 682 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 683 needUpdate = true; 684 } 685 break; 686 687 default: 688 // Nothing to do 689 } 690 691 if (needUpdate) { 692 mSettings.updateIntentFilterVerificationStatusLPw( 693 packageName, updatedStatus, userId); 694 scheduleWritePackageRestrictionsLocked(userId); 695 } 696 } 697 } 698 } 699 700 @Override 701 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 702 ActivityIntentInfo filter, String packageName) { 703 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 704 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 705 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 706 return false; 707 } 708 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 709 if (ivs == null) { 710 ivs = createDomainVerificationState(verifierId, userId, verificationId, 711 packageName); 712 } 713 if (!hasValidDomains(filter)) { 714 return false; 715 } 716 ivs.addFilter(filter); 717 return true; 718 } 719 720 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 721 int userId, int verificationId, String packageName) { 722 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 723 verifierId, userId, packageName); 724 ivs.setPendingState(); 725 synchronized (mPackages) { 726 mIntentFilterVerificationStates.append(verificationId, ivs); 727 mCurrentIntentFilterVerifications.add(verificationId); 728 } 729 return ivs; 730 } 731 } 732 733 private static boolean hasValidDomains(ActivityIntentInfo filter) { 734 return hasValidDomains(filter, true); 735 } 736 737 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 738 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 739 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 740 if (!hasHTTPorHTTPS) { 741 if (logging) { 742 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 743 } 744 return false; 745 } 746 return true; 747 } 748 749 private IntentFilterVerifier mIntentFilterVerifier; 750 751 // Set of pending broadcasts for aggregating enable/disable of components. 752 static class PendingPackageBroadcasts { 753 // for each user id, a map of <package name -> components within that package> 754 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 755 756 public PendingPackageBroadcasts() { 757 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 758 } 759 760 public ArrayList<String> get(int userId, String packageName) { 761 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 762 return packages.get(packageName); 763 } 764 765 public void put(int userId, String packageName, ArrayList<String> components) { 766 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 767 packages.put(packageName, components); 768 } 769 770 public void remove(int userId, String packageName) { 771 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 772 if (packages != null) { 773 packages.remove(packageName); 774 } 775 } 776 777 public void remove(int userId) { 778 mUidMap.remove(userId); 779 } 780 781 public int userIdCount() { 782 return mUidMap.size(); 783 } 784 785 public int userIdAt(int n) { 786 return mUidMap.keyAt(n); 787 } 788 789 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 790 return mUidMap.get(userId); 791 } 792 793 public int size() { 794 // total number of pending broadcast entries across all userIds 795 int num = 0; 796 for (int i = 0; i< mUidMap.size(); i++) { 797 num += mUidMap.valueAt(i).size(); 798 } 799 return num; 800 } 801 802 public void clear() { 803 mUidMap.clear(); 804 } 805 806 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 807 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 808 if (map == null) { 809 map = new ArrayMap<String, ArrayList<String>>(); 810 mUidMap.put(userId, map); 811 } 812 return map; 813 } 814 } 815 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 816 817 // Service Connection to remote media container service to copy 818 // package uri's from external media onto secure containers 819 // or internal storage. 820 private IMediaContainerService mContainerService = null; 821 822 static final int SEND_PENDING_BROADCAST = 1; 823 static final int MCS_BOUND = 3; 824 static final int END_COPY = 4; 825 static final int INIT_COPY = 5; 826 static final int MCS_UNBIND = 6; 827 static final int START_CLEANING_PACKAGE = 7; 828 static final int FIND_INSTALL_LOC = 8; 829 static final int POST_INSTALL = 9; 830 static final int MCS_RECONNECT = 10; 831 static final int MCS_GIVE_UP = 11; 832 static final int UPDATED_MEDIA_STATUS = 12; 833 static final int WRITE_SETTINGS = 13; 834 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 835 static final int PACKAGE_VERIFIED = 15; 836 static final int CHECK_PENDING_VERIFICATION = 16; 837 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 838 static final int INTENT_FILTER_VERIFIED = 18; 839 840 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 841 842 // Delay time in millisecs 843 static final int BROADCAST_DELAY = 10 * 1000; 844 845 static UserManagerService sUserManager; 846 847 // Stores a list of users whose package restrictions file needs to be updated 848 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 849 850 final private DefaultContainerConnection mDefContainerConn = 851 new DefaultContainerConnection(); 852 class DefaultContainerConnection implements ServiceConnection { 853 public void onServiceConnected(ComponentName name, IBinder service) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 855 IMediaContainerService imcs = 856 IMediaContainerService.Stub.asInterface(service); 857 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 858 } 859 860 public void onServiceDisconnected(ComponentName name) { 861 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 862 } 863 }; 864 865 // Recordkeeping of restore-after-install operations that are currently in flight 866 // between the Package Manager and the Backup Manager 867 class PostInstallData { 868 public InstallArgs args; 869 public PackageInstalledInfo res; 870 871 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 872 args = _a; 873 res = _r; 874 } 875 }; 876 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 877 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 878 879 // backup/restore of preferred activity state 880 private static final String TAG_PREFERRED_BACKUP = "pa"; 881 882 private final String mRequiredVerifierPackage; 883 884 private final PackageUsage mPackageUsage = new PackageUsage(); 885 886 private class PackageUsage { 887 private static final int WRITE_INTERVAL 888 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 889 890 private final Object mFileLock = new Object(); 891 private final AtomicLong mLastWritten = new AtomicLong(0); 892 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 893 894 private boolean mIsHistoricalPackageUsageAvailable = true; 895 896 boolean isHistoricalPackageUsageAvailable() { 897 return mIsHistoricalPackageUsageAvailable; 898 } 899 900 void write(boolean force) { 901 if (force) { 902 writeInternal(); 903 return; 904 } 905 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 906 && !DEBUG_DEXOPT) { 907 return; 908 } 909 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 910 new Thread("PackageUsage_DiskWriter") { 911 @Override 912 public void run() { 913 try { 914 writeInternal(); 915 } finally { 916 mBackgroundWriteRunning.set(false); 917 } 918 } 919 }.start(); 920 } 921 } 922 923 private void writeInternal() { 924 synchronized (mPackages) { 925 synchronized (mFileLock) { 926 AtomicFile file = getFile(); 927 FileOutputStream f = null; 928 try { 929 f = file.startWrite(); 930 BufferedOutputStream out = new BufferedOutputStream(f); 931 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 932 StringBuilder sb = new StringBuilder(); 933 for (PackageParser.Package pkg : mPackages.values()) { 934 if (pkg.mLastPackageUsageTimeInMills == 0) { 935 continue; 936 } 937 sb.setLength(0); 938 sb.append(pkg.packageName); 939 sb.append(' '); 940 sb.append((long)pkg.mLastPackageUsageTimeInMills); 941 sb.append('\n'); 942 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 943 } 944 out.flush(); 945 file.finishWrite(f); 946 } catch (IOException e) { 947 if (f != null) { 948 file.failWrite(f); 949 } 950 Log.e(TAG, "Failed to write package usage times", e); 951 } 952 } 953 } 954 mLastWritten.set(SystemClock.elapsedRealtime()); 955 } 956 957 void readLP() { 958 synchronized (mFileLock) { 959 AtomicFile file = getFile(); 960 BufferedInputStream in = null; 961 try { 962 in = new BufferedInputStream(file.openRead()); 963 StringBuffer sb = new StringBuffer(); 964 while (true) { 965 String packageName = readToken(in, sb, ' '); 966 if (packageName == null) { 967 break; 968 } 969 String timeInMillisString = readToken(in, sb, '\n'); 970 if (timeInMillisString == null) { 971 throw new IOException("Failed to find last usage time for package " 972 + packageName); 973 } 974 PackageParser.Package pkg = mPackages.get(packageName); 975 if (pkg == null) { 976 continue; 977 } 978 long timeInMillis; 979 try { 980 timeInMillis = Long.parseLong(timeInMillisString.toString()); 981 } catch (NumberFormatException e) { 982 throw new IOException("Failed to parse " + timeInMillisString 983 + " as a long.", e); 984 } 985 pkg.mLastPackageUsageTimeInMills = timeInMillis; 986 } 987 } catch (FileNotFoundException expected) { 988 mIsHistoricalPackageUsageAvailable = false; 989 } catch (IOException e) { 990 Log.w(TAG, "Failed to read package usage times", e); 991 } finally { 992 IoUtils.closeQuietly(in); 993 } 994 } 995 mLastWritten.set(SystemClock.elapsedRealtime()); 996 } 997 998 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 999 throws IOException { 1000 sb.setLength(0); 1001 while (true) { 1002 int ch = in.read(); 1003 if (ch == -1) { 1004 if (sb.length() == 0) { 1005 return null; 1006 } 1007 throw new IOException("Unexpected EOF"); 1008 } 1009 if (ch == endOfToken) { 1010 return sb.toString(); 1011 } 1012 sb.append((char)ch); 1013 } 1014 } 1015 1016 private AtomicFile getFile() { 1017 File dataDir = Environment.getDataDirectory(); 1018 File systemDir = new File(dataDir, "system"); 1019 File fname = new File(systemDir, "package-usage.list"); 1020 return new AtomicFile(fname); 1021 } 1022 } 1023 1024 class PackageHandler extends Handler { 1025 private boolean mBound = false; 1026 final ArrayList<HandlerParams> mPendingInstalls = 1027 new ArrayList<HandlerParams>(); 1028 1029 private boolean connectToService() { 1030 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1031 " DefaultContainerService"); 1032 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1033 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1034 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1035 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1037 mBound = true; 1038 return true; 1039 } 1040 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1041 return false; 1042 } 1043 1044 private void disconnectService() { 1045 mContainerService = null; 1046 mBound = false; 1047 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1048 mContext.unbindService(mDefContainerConn); 1049 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1050 } 1051 1052 PackageHandler(Looper looper) { 1053 super(looper); 1054 } 1055 1056 public void handleMessage(Message msg) { 1057 try { 1058 doHandleMessage(msg); 1059 } finally { 1060 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1061 } 1062 } 1063 1064 void doHandleMessage(Message msg) { 1065 switch (msg.what) { 1066 case INIT_COPY: { 1067 HandlerParams params = (HandlerParams) msg.obj; 1068 int idx = mPendingInstalls.size(); 1069 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1070 // If a bind was already initiated we dont really 1071 // need to do anything. The pending install 1072 // will be processed later on. 1073 if (!mBound) { 1074 // If this is the only one pending we might 1075 // have to bind to the service again. 1076 if (!connectToService()) { 1077 Slog.e(TAG, "Failed to bind to media container service"); 1078 params.serviceError(); 1079 return; 1080 } else { 1081 // Once we bind to the service, the first 1082 // pending request will be processed. 1083 mPendingInstalls.add(idx, params); 1084 } 1085 } else { 1086 mPendingInstalls.add(idx, params); 1087 // Already bound to the service. Just make 1088 // sure we trigger off processing the first request. 1089 if (idx == 0) { 1090 mHandler.sendEmptyMessage(MCS_BOUND); 1091 } 1092 } 1093 break; 1094 } 1095 case MCS_BOUND: { 1096 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1097 if (msg.obj != null) { 1098 mContainerService = (IMediaContainerService) msg.obj; 1099 } 1100 if (mContainerService == null) { 1101 // Something seriously wrong. Bail out 1102 Slog.e(TAG, "Cannot bind to media container service"); 1103 for (HandlerParams params : mPendingInstalls) { 1104 // Indicate service bind error 1105 params.serviceError(); 1106 } 1107 mPendingInstalls.clear(); 1108 } else if (mPendingInstalls.size() > 0) { 1109 HandlerParams params = mPendingInstalls.get(0); 1110 if (params != null) { 1111 if (params.startCopy()) { 1112 // We are done... look for more work or to 1113 // go idle. 1114 if (DEBUG_SD_INSTALL) Log.i(TAG, 1115 "Checking for more work or unbind..."); 1116 // Delete pending install 1117 if (mPendingInstalls.size() > 0) { 1118 mPendingInstalls.remove(0); 1119 } 1120 if (mPendingInstalls.size() == 0) { 1121 if (mBound) { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, 1123 "Posting delayed MCS_UNBIND"); 1124 removeMessages(MCS_UNBIND); 1125 Message ubmsg = obtainMessage(MCS_UNBIND); 1126 // Unbind after a little delay, to avoid 1127 // continual thrashing. 1128 sendMessageDelayed(ubmsg, 10000); 1129 } 1130 } else { 1131 // There are more pending requests in queue. 1132 // Just post MCS_BOUND message to trigger processing 1133 // of next pending install. 1134 if (DEBUG_SD_INSTALL) Log.i(TAG, 1135 "Posting MCS_BOUND for next work"); 1136 mHandler.sendEmptyMessage(MCS_BOUND); 1137 } 1138 } 1139 } 1140 } else { 1141 // Should never happen ideally. 1142 Slog.w(TAG, "Empty queue"); 1143 } 1144 break; 1145 } 1146 case MCS_RECONNECT: { 1147 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1148 if (mPendingInstalls.size() > 0) { 1149 if (mBound) { 1150 disconnectService(); 1151 } 1152 if (!connectToService()) { 1153 Slog.e(TAG, "Failed to bind to media container service"); 1154 for (HandlerParams params : mPendingInstalls) { 1155 // Indicate service bind error 1156 params.serviceError(); 1157 } 1158 mPendingInstalls.clear(); 1159 } 1160 } 1161 break; 1162 } 1163 case MCS_UNBIND: { 1164 // If there is no actual work left, then time to unbind. 1165 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1166 1167 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1168 if (mBound) { 1169 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1170 1171 disconnectService(); 1172 } 1173 } else if (mPendingInstalls.size() > 0) { 1174 // There are more pending requests in queue. 1175 // Just post MCS_BOUND message to trigger processing 1176 // of next pending install. 1177 mHandler.sendEmptyMessage(MCS_BOUND); 1178 } 1179 1180 break; 1181 } 1182 case MCS_GIVE_UP: { 1183 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1184 mPendingInstalls.remove(0); 1185 break; 1186 } 1187 case SEND_PENDING_BROADCAST: { 1188 String packages[]; 1189 ArrayList<String> components[]; 1190 int size = 0; 1191 int uids[]; 1192 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1193 synchronized (mPackages) { 1194 if (mPendingBroadcasts == null) { 1195 return; 1196 } 1197 size = mPendingBroadcasts.size(); 1198 if (size <= 0) { 1199 // Nothing to be done. Just return 1200 return; 1201 } 1202 packages = new String[size]; 1203 components = new ArrayList[size]; 1204 uids = new int[size]; 1205 int i = 0; // filling out the above arrays 1206 1207 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1208 int packageUserId = mPendingBroadcasts.userIdAt(n); 1209 Iterator<Map.Entry<String, ArrayList<String>>> it 1210 = mPendingBroadcasts.packagesForUserId(packageUserId) 1211 .entrySet().iterator(); 1212 while (it.hasNext() && i < size) { 1213 Map.Entry<String, ArrayList<String>> ent = it.next(); 1214 packages[i] = ent.getKey(); 1215 components[i] = ent.getValue(); 1216 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1217 uids[i] = (ps != null) 1218 ? UserHandle.getUid(packageUserId, ps.appId) 1219 : -1; 1220 i++; 1221 } 1222 } 1223 size = i; 1224 mPendingBroadcasts.clear(); 1225 } 1226 // Send broadcasts 1227 for (int i = 0; i < size; i++) { 1228 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1229 } 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1231 break; 1232 } 1233 case START_CLEANING_PACKAGE: { 1234 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1235 final String packageName = (String)msg.obj; 1236 final int userId = msg.arg1; 1237 final boolean andCode = msg.arg2 != 0; 1238 synchronized (mPackages) { 1239 if (userId == UserHandle.USER_ALL) { 1240 int[] users = sUserManager.getUserIds(); 1241 for (int user : users) { 1242 mSettings.addPackageToCleanLPw( 1243 new PackageCleanItem(user, packageName, andCode)); 1244 } 1245 } else { 1246 mSettings.addPackageToCleanLPw( 1247 new PackageCleanItem(userId, packageName, andCode)); 1248 } 1249 } 1250 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1251 startCleaningPackages(); 1252 } break; 1253 case POST_INSTALL: { 1254 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1255 PostInstallData data = mRunningInstalls.get(msg.arg1); 1256 mRunningInstalls.delete(msg.arg1); 1257 boolean deleteOld = false; 1258 1259 if (data != null) { 1260 InstallArgs args = data.args; 1261 PackageInstalledInfo res = data.res; 1262 1263 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1264 res.removedInfo.sendBroadcast(false, true, false); 1265 Bundle extras = new Bundle(1); 1266 extras.putInt(Intent.EXTRA_UID, res.uid); 1267 1268 // Now that we successfully installed the package, grant runtime 1269 // permissions if requested before broadcasting the install. 1270 if ((args.installFlags 1271 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1272 grantRequestedRuntimePermissions(res.pkg, 1273 args.user.getIdentifier()); 1274 } 1275 1276 // Determine the set of users who are adding this 1277 // package for the first time vs. those who are seeing 1278 // an update. 1279 int[] firstUsers; 1280 int[] updateUsers = new int[0]; 1281 if (res.origUsers == null || res.origUsers.length == 0) { 1282 firstUsers = res.newUsers; 1283 } else { 1284 firstUsers = new int[0]; 1285 for (int i=0; i<res.newUsers.length; i++) { 1286 int user = res.newUsers[i]; 1287 boolean isNew = true; 1288 for (int j=0; j<res.origUsers.length; j++) { 1289 if (res.origUsers[j] == user) { 1290 isNew = false; 1291 break; 1292 } 1293 } 1294 if (isNew) { 1295 int[] newFirst = new int[firstUsers.length+1]; 1296 System.arraycopy(firstUsers, 0, newFirst, 0, 1297 firstUsers.length); 1298 newFirst[firstUsers.length] = user; 1299 firstUsers = newFirst; 1300 } else { 1301 int[] newUpdate = new int[updateUsers.length+1]; 1302 System.arraycopy(updateUsers, 0, newUpdate, 0, 1303 updateUsers.length); 1304 newUpdate[updateUsers.length] = user; 1305 updateUsers = newUpdate; 1306 } 1307 } 1308 } 1309 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1310 res.pkg.applicationInfo.packageName, 1311 extras, null, null, firstUsers); 1312 final boolean update = res.removedInfo.removedPackage != null; 1313 if (update) { 1314 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1315 } 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, updateUsers); 1319 if (update) { 1320 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1321 res.pkg.applicationInfo.packageName, 1322 extras, null, null, updateUsers); 1323 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1324 null, null, 1325 res.pkg.applicationInfo.packageName, null, updateUsers); 1326 1327 // treat asec-hosted packages like removable media on upgrade 1328 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1329 if (DEBUG_INSTALL) { 1330 Slog.i(TAG, "upgrading pkg " + res.pkg 1331 + " is ASEC-hosted -> AVAILABLE"); 1332 } 1333 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1334 ArrayList<String> pkgList = new ArrayList<String>(1); 1335 pkgList.add(res.pkg.applicationInfo.packageName); 1336 sendResourcesChangedBroadcast(true, true, 1337 pkgList,uidArray, null); 1338 } 1339 } 1340 if (res.removedInfo.args != null) { 1341 // Remove the replaced package's older resources safely now 1342 deleteOld = true; 1343 } 1344 1345 // Log current value of "unknown sources" setting 1346 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1347 getUnknownSourcesSettings()); 1348 } 1349 // Force a gc to clear up things 1350 Runtime.getRuntime().gc(); 1351 // We delete after a gc for applications on sdcard. 1352 if (deleteOld) { 1353 synchronized (mInstallLock) { 1354 res.removedInfo.args.doPostDeleteLI(true); 1355 } 1356 } 1357 if (args.observer != null) { 1358 try { 1359 Bundle extras = extrasForInstallResult(res); 1360 args.observer.onPackageInstalled(res.name, res.returnCode, 1361 res.returnMsg, extras); 1362 } catch (RemoteException e) { 1363 Slog.i(TAG, "Observer no longer exists."); 1364 } 1365 } 1366 } else { 1367 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1368 } 1369 } break; 1370 case UPDATED_MEDIA_STATUS: { 1371 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1372 boolean reportStatus = msg.arg1 == 1; 1373 boolean doGc = msg.arg2 == 1; 1374 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1375 if (doGc) { 1376 // Force a gc to clear up stale containers. 1377 Runtime.getRuntime().gc(); 1378 } 1379 if (msg.obj != null) { 1380 @SuppressWarnings("unchecked") 1381 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1383 // Unload containers 1384 unloadAllContainers(args); 1385 } 1386 if (reportStatus) { 1387 try { 1388 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1389 PackageHelper.getMountService().finishMediaUpdate(); 1390 } catch (RemoteException e) { 1391 Log.e(TAG, "MountService not running?"); 1392 } 1393 } 1394 } break; 1395 case WRITE_SETTINGS: { 1396 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1397 synchronized (mPackages) { 1398 removeMessages(WRITE_SETTINGS); 1399 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1400 mSettings.writeLPr(); 1401 mDirtyUsers.clear(); 1402 } 1403 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1404 } break; 1405 case WRITE_PACKAGE_RESTRICTIONS: { 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1407 synchronized (mPackages) { 1408 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1409 for (int userId : mDirtyUsers) { 1410 mSettings.writePackageRestrictionsLPr(userId); 1411 } 1412 mDirtyUsers.clear(); 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 } break; 1416 case CHECK_PENDING_VERIFICATION: { 1417 final int verificationId = msg.arg1; 1418 final PackageVerificationState state = mPendingVerification.get(verificationId); 1419 1420 if ((state != null) && !state.timeoutExtended()) { 1421 final InstallArgs args = state.getInstallArgs(); 1422 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1423 1424 Slog.i(TAG, "Verification timed out for " + originUri); 1425 mPendingVerification.remove(verificationId); 1426 1427 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1428 1429 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1430 Slog.i(TAG, "Continuing with installation of " + originUri); 1431 state.setVerifierResponse(Binder.getCallingUid(), 1432 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1433 broadcastPackageVerified(verificationId, originUri, 1434 PackageManager.VERIFICATION_ALLOW, 1435 state.getInstallArgs().getUser()); 1436 try { 1437 ret = args.copyApk(mContainerService, true); 1438 } catch (RemoteException e) { 1439 Slog.e(TAG, "Could not contact the ContainerService"); 1440 } 1441 } else { 1442 broadcastPackageVerified(verificationId, originUri, 1443 PackageManager.VERIFICATION_REJECT, 1444 state.getInstallArgs().getUser()); 1445 } 1446 1447 processPendingInstall(args, ret); 1448 mHandler.sendEmptyMessage(MCS_UNBIND); 1449 } 1450 break; 1451 } 1452 case PACKAGE_VERIFIED: { 1453 final int verificationId = msg.arg1; 1454 1455 final PackageVerificationState state = mPendingVerification.get(verificationId); 1456 if (state == null) { 1457 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1458 break; 1459 } 1460 1461 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1462 1463 state.setVerifierResponse(response.callerUid, response.code); 1464 1465 if (state.isVerificationComplete()) { 1466 mPendingVerification.remove(verificationId); 1467 1468 final InstallArgs args = state.getInstallArgs(); 1469 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1470 1471 int ret; 1472 if (state.isInstallAllowed()) { 1473 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1474 broadcastPackageVerified(verificationId, originUri, 1475 response.code, state.getInstallArgs().getUser()); 1476 try { 1477 ret = args.copyApk(mContainerService, true); 1478 } catch (RemoteException e) { 1479 Slog.e(TAG, "Could not contact the ContainerService"); 1480 } 1481 } else { 1482 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1483 } 1484 1485 processPendingInstall(args, ret); 1486 1487 mHandler.sendEmptyMessage(MCS_UNBIND); 1488 } 1489 1490 break; 1491 } 1492 case START_INTENT_FILTER_VERIFICATIONS: { 1493 int userId = msg.arg1; 1494 int verifierUid = msg.arg2; 1495 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1496 1497 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1498 break; 1499 } 1500 case INTENT_FILTER_VERIFIED: { 1501 final int verificationId = msg.arg1; 1502 1503 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1504 verificationId); 1505 if (state == null) { 1506 Slog.w(TAG, "Invalid IntentFilter verification token " 1507 + verificationId + " received"); 1508 break; 1509 } 1510 1511 final int userId = state.getUserId(); 1512 1513 Slog.d(TAG, "Processing IntentFilter verification with token:" 1514 + verificationId + " and userId:" + userId); 1515 1516 final IntentFilterVerificationResponse response = 1517 (IntentFilterVerificationResponse) msg.obj; 1518 1519 state.setVerifierResponse(response.callerUid, response.code); 1520 1521 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1522 + " and userId:" + userId 1523 + " is settings verifier response with response code:" 1524 + response.code); 1525 1526 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1527 Slog.d(TAG, "Domains failing verification: " 1528 + response.getFailedDomainsString()); 1529 } 1530 1531 if (state.isVerificationComplete()) { 1532 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1533 } else { 1534 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1535 + " was not said to be complete"); 1536 } 1537 1538 break; 1539 } 1540 } 1541 } 1542 } 1543 1544 private StorageEventListener mStorageListener = new StorageEventListener() { 1545 @Override 1546 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1547 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1548 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1549 // TODO: ensure that private directories exist for all active users 1550 // TODO: remove user data whose serial number doesn't match 1551 loadPrivatePackages(vol); 1552 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1553 unloadPrivatePackages(vol); 1554 } 1555 } 1556 1557 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1558 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1559 updateExternalMediaStatus(true, false); 1560 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1561 updateExternalMediaStatus(false, false); 1562 } 1563 } 1564 } 1565 1566 @Override 1567 public void onVolumeForgotten(String fsUuid) { 1568 // TODO: remove all packages hosted on this uuid 1569 } 1570 }; 1571 1572 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1573 if (userId >= UserHandle.USER_OWNER) { 1574 grantRequestedRuntimePermissionsForUser(pkg, userId); 1575 } else if (userId == UserHandle.USER_ALL) { 1576 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1577 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1578 } 1579 } 1580 } 1581 1582 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1583 SettingBase sb = (SettingBase) pkg.mExtras; 1584 if (sb == null) { 1585 return; 1586 } 1587 1588 PermissionsState permissionsState = sb.getPermissionsState(); 1589 1590 for (String permission : pkg.requestedPermissions) { 1591 BasePermission bp = mSettings.mPermissions.get(permission); 1592 if (bp != null && bp.isRuntime()) { 1593 permissionsState.grantRuntimePermission(bp, userId); 1594 } 1595 } 1596 } 1597 1598 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1599 Bundle extras = null; 1600 switch (res.returnCode) { 1601 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1602 extras = new Bundle(); 1603 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1604 res.origPermission); 1605 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1606 res.origPackage); 1607 break; 1608 } 1609 case PackageManager.INSTALL_SUCCEEDED: { 1610 extras = new Bundle(); 1611 extras.putBoolean(Intent.EXTRA_REPLACING, 1612 res.removedInfo != null && res.removedInfo.removedPackage != null); 1613 break; 1614 } 1615 } 1616 return extras; 1617 } 1618 1619 void scheduleWriteSettingsLocked() { 1620 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1621 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1622 } 1623 } 1624 1625 void scheduleWritePackageRestrictionsLocked(int userId) { 1626 if (!sUserManager.exists(userId)) return; 1627 mDirtyUsers.add(userId); 1628 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1629 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1630 } 1631 } 1632 1633 public static PackageManagerService main(Context context, Installer installer, 1634 boolean factoryTest, boolean onlyCore) { 1635 PackageManagerService m = new PackageManagerService(context, installer, 1636 factoryTest, onlyCore); 1637 ServiceManager.addService("package", m); 1638 return m; 1639 } 1640 1641 static String[] splitString(String str, char sep) { 1642 int count = 1; 1643 int i = 0; 1644 while ((i=str.indexOf(sep, i)) >= 0) { 1645 count++; 1646 i++; 1647 } 1648 1649 String[] res = new String[count]; 1650 i=0; 1651 count = 0; 1652 int lastI=0; 1653 while ((i=str.indexOf(sep, i)) >= 0) { 1654 res[count] = str.substring(lastI, i); 1655 count++; 1656 i++; 1657 lastI = i; 1658 } 1659 res[count] = str.substring(lastI, str.length()); 1660 return res; 1661 } 1662 1663 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1664 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1665 Context.DISPLAY_SERVICE); 1666 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1667 } 1668 1669 public PackageManagerService(Context context, Installer installer, 1670 boolean factoryTest, boolean onlyCore) { 1671 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1672 SystemClock.uptimeMillis()); 1673 1674 if (mSdkVersion <= 0) { 1675 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1676 } 1677 1678 mContext = context; 1679 mFactoryTest = factoryTest; 1680 mOnlyCore = onlyCore; 1681 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1682 mMetrics = new DisplayMetrics(); 1683 mSettings = new Settings(mPackages); 1684 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1685 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1686 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1687 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1688 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1689 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1690 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1691 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1692 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1693 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1694 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1695 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1696 1697 // TODO: add a property to control this? 1698 long dexOptLRUThresholdInMinutes; 1699 if (mLazyDexOpt) { 1700 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1701 } else { 1702 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1703 } 1704 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1705 1706 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1707 if (separateProcesses != null && separateProcesses.length() > 0) { 1708 if ("*".equals(separateProcesses)) { 1709 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1710 mSeparateProcesses = null; 1711 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1712 } else { 1713 mDefParseFlags = 0; 1714 mSeparateProcesses = separateProcesses.split(","); 1715 Slog.w(TAG, "Running with debug.separate_processes: " 1716 + separateProcesses); 1717 } 1718 } else { 1719 mDefParseFlags = 0; 1720 mSeparateProcesses = null; 1721 } 1722 1723 mInstaller = installer; 1724 mPackageDexOptimizer = new PackageDexOptimizer(this); 1725 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1726 1727 getDefaultDisplayMetrics(context, mMetrics); 1728 1729 SystemConfig systemConfig = SystemConfig.getInstance(); 1730 mGlobalGids = systemConfig.getGlobalGids(); 1731 mSystemPermissions = systemConfig.getSystemPermissions(); 1732 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1733 1734 synchronized (mInstallLock) { 1735 // writer 1736 synchronized (mPackages) { 1737 mHandlerThread = new ServiceThread(TAG, 1738 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1739 mHandlerThread.start(); 1740 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1741 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1742 1743 File dataDir = Environment.getDataDirectory(); 1744 mAppDataDir = new File(dataDir, "data"); 1745 mAppInstallDir = new File(dataDir, "app"); 1746 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1747 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1748 mUserAppDataDir = new File(dataDir, "user"); 1749 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1750 1751 sUserManager = new UserManagerService(context, this, 1752 mInstallLock, mPackages); 1753 1754 // Propagate permission configuration in to package manager. 1755 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1756 = systemConfig.getPermissions(); 1757 for (int i=0; i<permConfig.size(); i++) { 1758 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1759 BasePermission bp = mSettings.mPermissions.get(perm.name); 1760 if (bp == null) { 1761 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1762 mSettings.mPermissions.put(perm.name, bp); 1763 } 1764 if (perm.gids != null) { 1765 bp.setGids(perm.gids, perm.perUser); 1766 } 1767 } 1768 1769 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1770 for (int i=0; i<libConfig.size(); i++) { 1771 mSharedLibraries.put(libConfig.keyAt(i), 1772 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1773 } 1774 1775 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1776 1777 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1778 mSdkVersion, mOnlyCore); 1779 1780 String customResolverActivity = Resources.getSystem().getString( 1781 R.string.config_customResolverActivity); 1782 if (TextUtils.isEmpty(customResolverActivity)) { 1783 customResolverActivity = null; 1784 } else { 1785 mCustomResolverComponentName = ComponentName.unflattenFromString( 1786 customResolverActivity); 1787 } 1788 1789 long startTime = SystemClock.uptimeMillis(); 1790 1791 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1792 startTime); 1793 1794 // Set flag to monitor and not change apk file paths when 1795 // scanning install directories. 1796 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1797 1798 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1799 1800 /** 1801 * Add everything in the in the boot class path to the 1802 * list of process files because dexopt will have been run 1803 * if necessary during zygote startup. 1804 */ 1805 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1806 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1807 1808 if (bootClassPath != null) { 1809 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1810 for (String element : bootClassPathElements) { 1811 alreadyDexOpted.add(element); 1812 } 1813 } else { 1814 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1815 } 1816 1817 if (systemServerClassPath != null) { 1818 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1819 for (String element : systemServerClassPathElements) { 1820 alreadyDexOpted.add(element); 1821 } 1822 } else { 1823 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1824 } 1825 1826 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1827 final String[] dexCodeInstructionSets = 1828 getDexCodeInstructionSets( 1829 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1830 1831 /** 1832 * Ensure all external libraries have had dexopt run on them. 1833 */ 1834 if (mSharedLibraries.size() > 0) { 1835 // NOTE: For now, we're compiling these system "shared libraries" 1836 // (and framework jars) into all available architectures. It's possible 1837 // to compile them only when we come across an app that uses them (there's 1838 // already logic for that in scanPackageLI) but that adds some complexity. 1839 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1840 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1841 final String lib = libEntry.path; 1842 if (lib == null) { 1843 continue; 1844 } 1845 1846 try { 1847 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1848 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1849 alreadyDexOpted.add(lib); 1850 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1851 } 1852 } catch (FileNotFoundException e) { 1853 Slog.w(TAG, "Library not found: " + lib); 1854 } catch (IOException e) { 1855 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1856 + e.getMessage()); 1857 } 1858 } 1859 } 1860 } 1861 1862 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1863 1864 // Gross hack for now: we know this file doesn't contain any 1865 // code, so don't dexopt it to avoid the resulting log spew. 1866 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1867 1868 // Gross hack for now: we know this file is only part of 1869 // the boot class path for art, so don't dexopt it to 1870 // avoid the resulting log spew. 1871 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1872 1873 /** 1874 * And there are a number of commands implemented in Java, which 1875 * we currently need to do the dexopt on so that they can be 1876 * run from a non-root shell. 1877 */ 1878 String[] frameworkFiles = frameworkDir.list(); 1879 if (frameworkFiles != null) { 1880 // TODO: We could compile these only for the most preferred ABI. We should 1881 // first double check that the dex files for these commands are not referenced 1882 // by other system apps. 1883 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1884 for (int i=0; i<frameworkFiles.length; i++) { 1885 File libPath = new File(frameworkDir, frameworkFiles[i]); 1886 String path = libPath.getPath(); 1887 // Skip the file if we already did it. 1888 if (alreadyDexOpted.contains(path)) { 1889 continue; 1890 } 1891 // Skip the file if it is not a type we want to dexopt. 1892 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1893 continue; 1894 } 1895 try { 1896 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1897 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1898 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1899 } 1900 } catch (FileNotFoundException e) { 1901 Slog.w(TAG, "Jar not found: " + path); 1902 } catch (IOException e) { 1903 Slog.w(TAG, "Exception reading jar: " + path, e); 1904 } 1905 } 1906 } 1907 } 1908 1909 // Collect vendor overlay packages. 1910 // (Do this before scanning any apps.) 1911 // For security and version matching reason, only consider 1912 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1913 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1914 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1915 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1916 1917 // Find base frameworks (resource packages without code). 1918 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1919 | PackageParser.PARSE_IS_SYSTEM_DIR 1920 | PackageParser.PARSE_IS_PRIVILEGED, 1921 scanFlags | SCAN_NO_DEX, 0); 1922 1923 // Collected privileged system packages. 1924 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1925 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1926 | PackageParser.PARSE_IS_SYSTEM_DIR 1927 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1928 1929 // Collect ordinary system packages. 1930 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1931 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1933 1934 // Collect all vendor packages. 1935 File vendorAppDir = new File("/vendor/app"); 1936 try { 1937 vendorAppDir = vendorAppDir.getCanonicalFile(); 1938 } catch (IOException e) { 1939 // failed to look up canonical path, continue with original one 1940 } 1941 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1942 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1943 1944 // Collect all OEM packages. 1945 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1946 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1947 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1948 1949 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1950 mInstaller.moveFiles(); 1951 1952 // Prune any system packages that no longer exist. 1953 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1954 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1955 if (!mOnlyCore) { 1956 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1957 while (psit.hasNext()) { 1958 PackageSetting ps = psit.next(); 1959 1960 /* 1961 * If this is not a system app, it can't be a 1962 * disable system app. 1963 */ 1964 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1965 continue; 1966 } 1967 1968 /* 1969 * If the package is scanned, it's not erased. 1970 */ 1971 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1972 if (scannedPkg != null) { 1973 /* 1974 * If the system app is both scanned and in the 1975 * disabled packages list, then it must have been 1976 * added via OTA. Remove it from the currently 1977 * scanned package so the previously user-installed 1978 * application can be scanned. 1979 */ 1980 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1981 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1982 + ps.name + "; removing system app. Last known codePath=" 1983 + ps.codePathString + ", installStatus=" + ps.installStatus 1984 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1985 + scannedPkg.mVersionCode); 1986 removePackageLI(ps, true); 1987 expectingBetter.put(ps.name, ps.codePath); 1988 } 1989 1990 continue; 1991 } 1992 1993 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1994 psit.remove(); 1995 logCriticalInfo(Log.WARN, "System package " + ps.name 1996 + " no longer exists; wiping its data"); 1997 removeDataDirsLI(null, ps.name); 1998 } else { 1999 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2000 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2001 possiblyDeletedUpdatedSystemApps.add(ps.name); 2002 } 2003 } 2004 } 2005 } 2006 2007 //look for any incomplete package installations 2008 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2009 //clean up list 2010 for(int i = 0; i < deletePkgsList.size(); i++) { 2011 //clean up here 2012 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2013 } 2014 //delete tmp files 2015 deleteTempPackageFiles(); 2016 2017 // Remove any shared userIDs that have no associated packages 2018 mSettings.pruneSharedUsersLPw(); 2019 2020 if (!mOnlyCore) { 2021 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2022 SystemClock.uptimeMillis()); 2023 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2024 2025 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2026 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2027 2028 /** 2029 * Remove disable package settings for any updated system 2030 * apps that were removed via an OTA. If they're not a 2031 * previously-updated app, remove them completely. 2032 * Otherwise, just revoke their system-level permissions. 2033 */ 2034 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2035 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2036 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2037 2038 String msg; 2039 if (deletedPkg == null) { 2040 msg = "Updated system package " + deletedAppName 2041 + " no longer exists; wiping its data"; 2042 removeDataDirsLI(null, deletedAppName); 2043 } else { 2044 msg = "Updated system app + " + deletedAppName 2045 + " no longer present; removing system privileges for " 2046 + deletedAppName; 2047 2048 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2049 2050 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2051 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2052 } 2053 logCriticalInfo(Log.WARN, msg); 2054 } 2055 2056 /** 2057 * Make sure all system apps that we expected to appear on 2058 * the userdata partition actually showed up. If they never 2059 * appeared, crawl back and revive the system version. 2060 */ 2061 for (int i = 0; i < expectingBetter.size(); i++) { 2062 final String packageName = expectingBetter.keyAt(i); 2063 if (!mPackages.containsKey(packageName)) { 2064 final File scanFile = expectingBetter.valueAt(i); 2065 2066 logCriticalInfo(Log.WARN, "Expected better " + packageName 2067 + " but never showed up; reverting to system"); 2068 2069 final int reparseFlags; 2070 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2071 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2072 | PackageParser.PARSE_IS_SYSTEM_DIR 2073 | PackageParser.PARSE_IS_PRIVILEGED; 2074 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2075 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2076 | PackageParser.PARSE_IS_SYSTEM_DIR; 2077 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2078 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2079 | PackageParser.PARSE_IS_SYSTEM_DIR; 2080 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2081 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR; 2083 } else { 2084 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2085 continue; 2086 } 2087 2088 mSettings.enableSystemPackageLPw(packageName); 2089 2090 try { 2091 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2092 } catch (PackageManagerException e) { 2093 Slog.e(TAG, "Failed to parse original system package: " 2094 + e.getMessage()); 2095 } 2096 } 2097 } 2098 } 2099 2100 // Now that we know all of the shared libraries, update all clients to have 2101 // the correct library paths. 2102 updateAllSharedLibrariesLPw(); 2103 2104 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2105 // NOTE: We ignore potential failures here during a system scan (like 2106 // the rest of the commands above) because there's precious little we 2107 // can do about it. A settings error is reported, though. 2108 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2109 false /* force dexopt */, false /* defer dexopt */); 2110 } 2111 2112 // Now that we know all the packages we are keeping, 2113 // read and update their last usage times. 2114 mPackageUsage.readLP(); 2115 2116 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2117 SystemClock.uptimeMillis()); 2118 Slog.i(TAG, "Time to scan packages: " 2119 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2120 + " seconds"); 2121 2122 // If the platform SDK has changed since the last time we booted, 2123 // we need to re-grant app permission to catch any new ones that 2124 // appear. This is really a hack, and means that apps can in some 2125 // cases get permissions that the user didn't initially explicitly 2126 // allow... it would be nice to have some better way to handle 2127 // this situation. 2128 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2129 != mSdkVersion; 2130 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2131 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2132 + "; regranting permissions for internal storage"); 2133 mSettings.mInternalSdkPlatform = mSdkVersion; 2134 2135 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2136 | (regrantPermissions 2137 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2138 : 0)); 2139 2140 // If this is the first boot, and it is a normal boot, then 2141 // we need to initialize the default preferred apps. 2142 if (!mRestoredSettings && !onlyCore) { 2143 mSettings.readDefaultPreferredAppsLPw(this, 0); 2144 } 2145 2146 // If this is first boot after an OTA, and a normal boot, then 2147 // we need to clear code cache directories. 2148 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2149 if (mIsUpgrade && !onlyCore) { 2150 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2151 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2152 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2153 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2154 } 2155 mSettings.mFingerprint = Build.FINGERPRINT; 2156 } 2157 2158 primeDomainVerificationsLPw(false); 2159 checkDefaultBrowser(); 2160 2161 // All the changes are done during package scanning. 2162 mSettings.updateInternalDatabaseVersion(); 2163 2164 // can downgrade to reader 2165 mSettings.writeLPr(); 2166 2167 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2168 SystemClock.uptimeMillis()); 2169 2170 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2171 2172 mInstallerService = new PackageInstallerService(context, this); 2173 2174 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2175 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2176 mIntentFilterVerifierComponent); 2177 2178 } // synchronized (mPackages) 2179 } // synchronized (mInstallLock) 2180 2181 // Now after opening every single application zip, make sure they 2182 // are all flushed. Not really needed, but keeps things nice and 2183 // tidy. 2184 Runtime.getRuntime().gc(); 2185 } 2186 2187 @Override 2188 public boolean isFirstBoot() { 2189 return !mRestoredSettings; 2190 } 2191 2192 @Override 2193 public boolean isOnlyCoreApps() { 2194 return mOnlyCore; 2195 } 2196 2197 @Override 2198 public boolean isUpgrade() { 2199 return mIsUpgrade; 2200 } 2201 2202 private String getRequiredVerifierLPr() { 2203 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2204 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2205 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2206 2207 String requiredVerifier = null; 2208 2209 final int N = receivers.size(); 2210 for (int i = 0; i < N; i++) { 2211 final ResolveInfo info = receivers.get(i); 2212 2213 if (info.activityInfo == null) { 2214 continue; 2215 } 2216 2217 final String packageName = info.activityInfo.packageName; 2218 2219 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2220 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2221 continue; 2222 } 2223 2224 if (requiredVerifier != null) { 2225 throw new RuntimeException("There can be only one required verifier"); 2226 } 2227 2228 requiredVerifier = packageName; 2229 } 2230 2231 return requiredVerifier; 2232 } 2233 2234 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2235 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2236 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2237 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2238 2239 ComponentName verifierComponentName = null; 2240 2241 int priority = -1000; 2242 final int N = receivers.size(); 2243 for (int i = 0; i < N; i++) { 2244 final ResolveInfo info = receivers.get(i); 2245 2246 if (info.activityInfo == null) { 2247 continue; 2248 } 2249 2250 final String packageName = info.activityInfo.packageName; 2251 2252 final PackageSetting ps = mSettings.mPackages.get(packageName); 2253 if (ps == null) { 2254 continue; 2255 } 2256 2257 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2258 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2259 continue; 2260 } 2261 2262 // Select the IntentFilterVerifier with the highest priority 2263 if (priority < info.priority) { 2264 priority = info.priority; 2265 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2266 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2267 " with priority: " + info.priority); 2268 } 2269 } 2270 2271 return verifierComponentName; 2272 } 2273 2274 private void primeDomainVerificationsLPw(boolean logging) { 2275 Slog.d(TAG, "Start priming domain verifications"); 2276 boolean updated = false; 2277 ArraySet<String> allHostsSet = new ArraySet<>(); 2278 for (PackageParser.Package pkg : mPackages.values()) { 2279 final String packageName = pkg.packageName; 2280 if (!hasDomainURLs(pkg)) { 2281 if (logging) { 2282 Slog.d(TAG, "No priming domain verifications for " + 2283 "package with no domain URLs: " + packageName); 2284 } 2285 continue; 2286 } 2287 if (!pkg.isSystemApp()) { 2288 if (logging) { 2289 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2290 packageName); 2291 } 2292 continue; 2293 } 2294 for (PackageParser.Activity a : pkg.activities) { 2295 for (ActivityIntentInfo filter : a.intents) { 2296 if (hasValidDomains(filter, false)) { 2297 allHostsSet.addAll(filter.getHostsList()); 2298 } 2299 } 2300 } 2301 if (allHostsSet.size() == 0) { 2302 allHostsSet.add("*"); 2303 } 2304 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2305 IntentFilterVerificationInfo ivi = 2306 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2307 if (ivi != null) { 2308 // We will always log this 2309 Slog.d(TAG, "Priming domain verifications for package: " + packageName + 2310 " with hosts:" + ivi.getDomainsString()); 2311 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2312 updated = true; 2313 } 2314 else { 2315 if (logging) { 2316 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2317 } 2318 } 2319 allHostsSet.clear(); 2320 } 2321 if (updated) { 2322 if (logging) { 2323 Slog.d(TAG, "Will need to write primed domain verifications"); 2324 } 2325 } 2326 Slog.d(TAG, "End priming domain verifications"); 2327 } 2328 2329 private void checkDefaultBrowser() { 2330 final int myUserId = UserHandle.myUserId(); 2331 final String packageName = getDefaultBrowserPackageName(myUserId); 2332 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2333 if (info == null) { 2334 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2335 packageName); 2336 setDefaultBrowserPackageName(null, myUserId); 2337 } 2338 } 2339 2340 @Override 2341 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2342 throws RemoteException { 2343 try { 2344 return super.onTransact(code, data, reply, flags); 2345 } catch (RuntimeException e) { 2346 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2347 Slog.wtf(TAG, "Package Manager Crash", e); 2348 } 2349 throw e; 2350 } 2351 } 2352 2353 void cleanupInstallFailedPackage(PackageSetting ps) { 2354 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2355 2356 removeDataDirsLI(ps.volumeUuid, ps.name); 2357 if (ps.codePath != null) { 2358 if (ps.codePath.isDirectory()) { 2359 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2360 } else { 2361 ps.codePath.delete(); 2362 } 2363 } 2364 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2365 if (ps.resourcePath.isDirectory()) { 2366 FileUtils.deleteContents(ps.resourcePath); 2367 } 2368 ps.resourcePath.delete(); 2369 } 2370 mSettings.removePackageLPw(ps.name); 2371 } 2372 2373 static int[] appendInts(int[] cur, int[] add) { 2374 if (add == null) return cur; 2375 if (cur == null) return add; 2376 final int N = add.length; 2377 for (int i=0; i<N; i++) { 2378 cur = appendInt(cur, add[i]); 2379 } 2380 return cur; 2381 } 2382 2383 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2384 if (!sUserManager.exists(userId)) return null; 2385 final PackageSetting ps = (PackageSetting) p.mExtras; 2386 if (ps == null) { 2387 return null; 2388 } 2389 2390 final PermissionsState permissionsState = ps.getPermissionsState(); 2391 2392 final int[] gids = permissionsState.computeGids(userId); 2393 final Set<String> permissions = permissionsState.getPermissions(userId); 2394 final PackageUserState state = ps.readUserState(userId); 2395 2396 return PackageParser.generatePackageInfo(p, gids, flags, 2397 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2398 } 2399 2400 @Override 2401 public boolean isPackageFrozen(String packageName) { 2402 synchronized (mPackages) { 2403 final PackageSetting ps = mSettings.mPackages.get(packageName); 2404 if (ps != null) { 2405 return ps.frozen; 2406 } 2407 } 2408 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2409 return true; 2410 } 2411 2412 @Override 2413 public boolean isPackageAvailable(String packageName, int userId) { 2414 if (!sUserManager.exists(userId)) return false; 2415 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2416 synchronized (mPackages) { 2417 PackageParser.Package p = mPackages.get(packageName); 2418 if (p != null) { 2419 final PackageSetting ps = (PackageSetting) p.mExtras; 2420 if (ps != null) { 2421 final PackageUserState state = ps.readUserState(userId); 2422 if (state != null) { 2423 return PackageParser.isAvailable(state); 2424 } 2425 } 2426 } 2427 } 2428 return false; 2429 } 2430 2431 @Override 2432 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2433 if (!sUserManager.exists(userId)) return null; 2434 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2435 // reader 2436 synchronized (mPackages) { 2437 PackageParser.Package p = mPackages.get(packageName); 2438 if (DEBUG_PACKAGE_INFO) 2439 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2440 if (p != null) { 2441 return generatePackageInfo(p, flags, userId); 2442 } 2443 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2444 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2445 } 2446 } 2447 return null; 2448 } 2449 2450 @Override 2451 public String[] currentToCanonicalPackageNames(String[] names) { 2452 String[] out = new String[names.length]; 2453 // reader 2454 synchronized (mPackages) { 2455 for (int i=names.length-1; i>=0; i--) { 2456 PackageSetting ps = mSettings.mPackages.get(names[i]); 2457 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2458 } 2459 } 2460 return out; 2461 } 2462 2463 @Override 2464 public String[] canonicalToCurrentPackageNames(String[] names) { 2465 String[] out = new String[names.length]; 2466 // reader 2467 synchronized (mPackages) { 2468 for (int i=names.length-1; i>=0; i--) { 2469 String cur = mSettings.mRenamedPackages.get(names[i]); 2470 out[i] = cur != null ? cur : names[i]; 2471 } 2472 } 2473 return out; 2474 } 2475 2476 @Override 2477 public int getPackageUid(String packageName, int userId) { 2478 if (!sUserManager.exists(userId)) return -1; 2479 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2480 2481 // reader 2482 synchronized (mPackages) { 2483 PackageParser.Package p = mPackages.get(packageName); 2484 if(p != null) { 2485 return UserHandle.getUid(userId, p.applicationInfo.uid); 2486 } 2487 PackageSetting ps = mSettings.mPackages.get(packageName); 2488 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2489 return -1; 2490 } 2491 p = ps.pkg; 2492 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2493 } 2494 } 2495 2496 @Override 2497 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2498 if (!sUserManager.exists(userId)) { 2499 return null; 2500 } 2501 2502 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2503 "getPackageGids"); 2504 2505 // reader 2506 synchronized (mPackages) { 2507 PackageParser.Package p = mPackages.get(packageName); 2508 if (DEBUG_PACKAGE_INFO) { 2509 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2510 } 2511 if (p != null) { 2512 PackageSetting ps = (PackageSetting) p.mExtras; 2513 return ps.getPermissionsState().computeGids(userId); 2514 } 2515 } 2516 2517 return null; 2518 } 2519 2520 static PermissionInfo generatePermissionInfo( 2521 BasePermission bp, int flags) { 2522 if (bp.perm != null) { 2523 return PackageParser.generatePermissionInfo(bp.perm, flags); 2524 } 2525 PermissionInfo pi = new PermissionInfo(); 2526 pi.name = bp.name; 2527 pi.packageName = bp.sourcePackage; 2528 pi.nonLocalizedLabel = bp.name; 2529 pi.protectionLevel = bp.protectionLevel; 2530 return pi; 2531 } 2532 2533 @Override 2534 public PermissionInfo getPermissionInfo(String name, int flags) { 2535 // reader 2536 synchronized (mPackages) { 2537 final BasePermission p = mSettings.mPermissions.get(name); 2538 if (p != null) { 2539 return generatePermissionInfo(p, flags); 2540 } 2541 return null; 2542 } 2543 } 2544 2545 @Override 2546 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2547 // reader 2548 synchronized (mPackages) { 2549 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2550 for (BasePermission p : mSettings.mPermissions.values()) { 2551 if (group == null) { 2552 if (p.perm == null || p.perm.info.group == null) { 2553 out.add(generatePermissionInfo(p, flags)); 2554 } 2555 } else { 2556 if (p.perm != null && group.equals(p.perm.info.group)) { 2557 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2558 } 2559 } 2560 } 2561 2562 if (out.size() > 0) { 2563 return out; 2564 } 2565 return mPermissionGroups.containsKey(group) ? out : null; 2566 } 2567 } 2568 2569 @Override 2570 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2571 // reader 2572 synchronized (mPackages) { 2573 return PackageParser.generatePermissionGroupInfo( 2574 mPermissionGroups.get(name), flags); 2575 } 2576 } 2577 2578 @Override 2579 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2580 // reader 2581 synchronized (mPackages) { 2582 final int N = mPermissionGroups.size(); 2583 ArrayList<PermissionGroupInfo> out 2584 = new ArrayList<PermissionGroupInfo>(N); 2585 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2586 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2587 } 2588 return out; 2589 } 2590 } 2591 2592 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2593 int userId) { 2594 if (!sUserManager.exists(userId)) return null; 2595 PackageSetting ps = mSettings.mPackages.get(packageName); 2596 if (ps != null) { 2597 if (ps.pkg == null) { 2598 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2599 flags, userId); 2600 if (pInfo != null) { 2601 return pInfo.applicationInfo; 2602 } 2603 return null; 2604 } 2605 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2606 ps.readUserState(userId), userId); 2607 } 2608 return null; 2609 } 2610 2611 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2612 int userId) { 2613 if (!sUserManager.exists(userId)) return null; 2614 PackageSetting ps = mSettings.mPackages.get(packageName); 2615 if (ps != null) { 2616 PackageParser.Package pkg = ps.pkg; 2617 if (pkg == null) { 2618 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2619 return null; 2620 } 2621 // Only data remains, so we aren't worried about code paths 2622 pkg = new PackageParser.Package(packageName); 2623 pkg.applicationInfo.packageName = packageName; 2624 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2625 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2626 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2627 packageName, userId).getAbsolutePath(); 2628 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2629 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2630 } 2631 return generatePackageInfo(pkg, flags, userId); 2632 } 2633 return null; 2634 } 2635 2636 @Override 2637 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2638 if (!sUserManager.exists(userId)) return null; 2639 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2640 // writer 2641 synchronized (mPackages) { 2642 PackageParser.Package p = mPackages.get(packageName); 2643 if (DEBUG_PACKAGE_INFO) Log.v( 2644 TAG, "getApplicationInfo " + packageName 2645 + ": " + p); 2646 if (p != null) { 2647 PackageSetting ps = mSettings.mPackages.get(packageName); 2648 if (ps == null) return null; 2649 // Note: isEnabledLP() does not apply here - always return info 2650 return PackageParser.generateApplicationInfo( 2651 p, flags, ps.readUserState(userId), userId); 2652 } 2653 if ("android".equals(packageName)||"system".equals(packageName)) { 2654 return mAndroidApplication; 2655 } 2656 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2657 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2658 } 2659 } 2660 return null; 2661 } 2662 2663 @Override 2664 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2665 final IPackageDataObserver observer) { 2666 mContext.enforceCallingOrSelfPermission( 2667 android.Manifest.permission.CLEAR_APP_CACHE, null); 2668 // Queue up an async operation since clearing cache may take a little while. 2669 mHandler.post(new Runnable() { 2670 public void run() { 2671 mHandler.removeCallbacks(this); 2672 int retCode = -1; 2673 synchronized (mInstallLock) { 2674 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2675 if (retCode < 0) { 2676 Slog.w(TAG, "Couldn't clear application caches"); 2677 } 2678 } 2679 if (observer != null) { 2680 try { 2681 observer.onRemoveCompleted(null, (retCode >= 0)); 2682 } catch (RemoteException e) { 2683 Slog.w(TAG, "RemoveException when invoking call back"); 2684 } 2685 } 2686 } 2687 }); 2688 } 2689 2690 @Override 2691 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2692 final IntentSender pi) { 2693 mContext.enforceCallingOrSelfPermission( 2694 android.Manifest.permission.CLEAR_APP_CACHE, null); 2695 // Queue up an async operation since clearing cache may take a little while. 2696 mHandler.post(new Runnable() { 2697 public void run() { 2698 mHandler.removeCallbacks(this); 2699 int retCode = -1; 2700 synchronized (mInstallLock) { 2701 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2702 if (retCode < 0) { 2703 Slog.w(TAG, "Couldn't clear application caches"); 2704 } 2705 } 2706 if(pi != null) { 2707 try { 2708 // Callback via pending intent 2709 int code = (retCode >= 0) ? 1 : 0; 2710 pi.sendIntent(null, code, null, 2711 null, null); 2712 } catch (SendIntentException e1) { 2713 Slog.i(TAG, "Failed to send pending intent"); 2714 } 2715 } 2716 } 2717 }); 2718 } 2719 2720 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2721 synchronized (mInstallLock) { 2722 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2723 throw new IOException("Failed to free enough space"); 2724 } 2725 } 2726 } 2727 2728 @Override 2729 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2730 if (!sUserManager.exists(userId)) return null; 2731 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2732 synchronized (mPackages) { 2733 PackageParser.Activity a = mActivities.mActivities.get(component); 2734 2735 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2736 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2737 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2738 if (ps == null) return null; 2739 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2740 userId); 2741 } 2742 if (mResolveComponentName.equals(component)) { 2743 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2744 new PackageUserState(), userId); 2745 } 2746 } 2747 return null; 2748 } 2749 2750 @Override 2751 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2752 String resolvedType) { 2753 synchronized (mPackages) { 2754 PackageParser.Activity a = mActivities.mActivities.get(component); 2755 if (a == null) { 2756 return false; 2757 } 2758 for (int i=0; i<a.intents.size(); i++) { 2759 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2760 intent.getData(), intent.getCategories(), TAG) >= 0) { 2761 return true; 2762 } 2763 } 2764 return false; 2765 } 2766 } 2767 2768 @Override 2769 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2770 if (!sUserManager.exists(userId)) return null; 2771 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2772 synchronized (mPackages) { 2773 PackageParser.Activity a = mReceivers.mActivities.get(component); 2774 if (DEBUG_PACKAGE_INFO) Log.v( 2775 TAG, "getReceiverInfo " + component + ": " + a); 2776 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2777 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2778 if (ps == null) return null; 2779 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2780 userId); 2781 } 2782 } 2783 return null; 2784 } 2785 2786 @Override 2787 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2788 if (!sUserManager.exists(userId)) return null; 2789 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2790 synchronized (mPackages) { 2791 PackageParser.Service s = mServices.mServices.get(component); 2792 if (DEBUG_PACKAGE_INFO) Log.v( 2793 TAG, "getServiceInfo " + component + ": " + s); 2794 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2795 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2796 if (ps == null) return null; 2797 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2798 userId); 2799 } 2800 } 2801 return null; 2802 } 2803 2804 @Override 2805 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2806 if (!sUserManager.exists(userId)) return null; 2807 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2808 synchronized (mPackages) { 2809 PackageParser.Provider p = mProviders.mProviders.get(component); 2810 if (DEBUG_PACKAGE_INFO) Log.v( 2811 TAG, "getProviderInfo " + component + ": " + p); 2812 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2813 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2814 if (ps == null) return null; 2815 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2816 userId); 2817 } 2818 } 2819 return null; 2820 } 2821 2822 @Override 2823 public String[] getSystemSharedLibraryNames() { 2824 Set<String> libSet; 2825 synchronized (mPackages) { 2826 libSet = mSharedLibraries.keySet(); 2827 int size = libSet.size(); 2828 if (size > 0) { 2829 String[] libs = new String[size]; 2830 libSet.toArray(libs); 2831 return libs; 2832 } 2833 } 2834 return null; 2835 } 2836 2837 /** 2838 * @hide 2839 */ 2840 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2841 synchronized (mPackages) { 2842 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2843 if (lib != null && lib.apk != null) { 2844 return mPackages.get(lib.apk); 2845 } 2846 } 2847 return null; 2848 } 2849 2850 @Override 2851 public FeatureInfo[] getSystemAvailableFeatures() { 2852 Collection<FeatureInfo> featSet; 2853 synchronized (mPackages) { 2854 featSet = mAvailableFeatures.values(); 2855 int size = featSet.size(); 2856 if (size > 0) { 2857 FeatureInfo[] features = new FeatureInfo[size+1]; 2858 featSet.toArray(features); 2859 FeatureInfo fi = new FeatureInfo(); 2860 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2861 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2862 features[size] = fi; 2863 return features; 2864 } 2865 } 2866 return null; 2867 } 2868 2869 @Override 2870 public boolean hasSystemFeature(String name) { 2871 synchronized (mPackages) { 2872 return mAvailableFeatures.containsKey(name); 2873 } 2874 } 2875 2876 private void checkValidCaller(int uid, int userId) { 2877 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2878 return; 2879 2880 throw new SecurityException("Caller uid=" + uid 2881 + " is not privileged to communicate with user=" + userId); 2882 } 2883 2884 @Override 2885 public int checkPermission(String permName, String pkgName, int userId) { 2886 if (!sUserManager.exists(userId)) { 2887 return PackageManager.PERMISSION_DENIED; 2888 } 2889 2890 synchronized (mPackages) { 2891 final PackageParser.Package p = mPackages.get(pkgName); 2892 if (p != null && p.mExtras != null) { 2893 final PackageSetting ps = (PackageSetting) p.mExtras; 2894 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2895 return PackageManager.PERMISSION_GRANTED; 2896 } 2897 } 2898 } 2899 2900 return PackageManager.PERMISSION_DENIED; 2901 } 2902 2903 @Override 2904 public int checkUidPermission(String permName, int uid) { 2905 final int userId = UserHandle.getUserId(uid); 2906 2907 if (!sUserManager.exists(userId)) { 2908 return PackageManager.PERMISSION_DENIED; 2909 } 2910 2911 synchronized (mPackages) { 2912 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2913 if (obj != null) { 2914 final SettingBase ps = (SettingBase) obj; 2915 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2916 return PackageManager.PERMISSION_GRANTED; 2917 } 2918 } else { 2919 ArraySet<String> perms = mSystemPermissions.get(uid); 2920 if (perms != null && perms.contains(permName)) { 2921 return PackageManager.PERMISSION_GRANTED; 2922 } 2923 } 2924 } 2925 2926 return PackageManager.PERMISSION_DENIED; 2927 } 2928 2929 /** 2930 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2931 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2932 * @param checkShell TODO(yamasani): 2933 * @param message the message to log on security exception 2934 */ 2935 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2936 boolean checkShell, String message) { 2937 if (userId < 0) { 2938 throw new IllegalArgumentException("Invalid userId " + userId); 2939 } 2940 if (checkShell) { 2941 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2942 } 2943 if (userId == UserHandle.getUserId(callingUid)) return; 2944 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2945 if (requireFullPermission) { 2946 mContext.enforceCallingOrSelfPermission( 2947 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2948 } else { 2949 try { 2950 mContext.enforceCallingOrSelfPermission( 2951 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2952 } catch (SecurityException se) { 2953 mContext.enforceCallingOrSelfPermission( 2954 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2955 } 2956 } 2957 } 2958 } 2959 2960 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2961 if (callingUid == Process.SHELL_UID) { 2962 if (userHandle >= 0 2963 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2964 throw new SecurityException("Shell does not have permission to access user " 2965 + userHandle); 2966 } else if (userHandle < 0) { 2967 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2968 + Debug.getCallers(3)); 2969 } 2970 } 2971 } 2972 2973 private BasePermission findPermissionTreeLP(String permName) { 2974 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2975 if (permName.startsWith(bp.name) && 2976 permName.length() > bp.name.length() && 2977 permName.charAt(bp.name.length()) == '.') { 2978 return bp; 2979 } 2980 } 2981 return null; 2982 } 2983 2984 private BasePermission checkPermissionTreeLP(String permName) { 2985 if (permName != null) { 2986 BasePermission bp = findPermissionTreeLP(permName); 2987 if (bp != null) { 2988 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2989 return bp; 2990 } 2991 throw new SecurityException("Calling uid " 2992 + Binder.getCallingUid() 2993 + " is not allowed to add to permission tree " 2994 + bp.name + " owned by uid " + bp.uid); 2995 } 2996 } 2997 throw new SecurityException("No permission tree found for " + permName); 2998 } 2999 3000 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3001 if (s1 == null) { 3002 return s2 == null; 3003 } 3004 if (s2 == null) { 3005 return false; 3006 } 3007 if (s1.getClass() != s2.getClass()) { 3008 return false; 3009 } 3010 return s1.equals(s2); 3011 } 3012 3013 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3014 if (pi1.icon != pi2.icon) return false; 3015 if (pi1.logo != pi2.logo) return false; 3016 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3017 if (!compareStrings(pi1.name, pi2.name)) return false; 3018 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3019 // We'll take care of setting this one. 3020 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3021 // These are not currently stored in settings. 3022 //if (!compareStrings(pi1.group, pi2.group)) return false; 3023 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3024 //if (pi1.labelRes != pi2.labelRes) return false; 3025 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3026 return true; 3027 } 3028 3029 int permissionInfoFootprint(PermissionInfo info) { 3030 int size = info.name.length(); 3031 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3032 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3033 return size; 3034 } 3035 3036 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3037 int size = 0; 3038 for (BasePermission perm : mSettings.mPermissions.values()) { 3039 if (perm.uid == tree.uid) { 3040 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3041 } 3042 } 3043 return size; 3044 } 3045 3046 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3047 // We calculate the max size of permissions defined by this uid and throw 3048 // if that plus the size of 'info' would exceed our stated maximum. 3049 if (tree.uid != Process.SYSTEM_UID) { 3050 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3051 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3052 throw new SecurityException("Permission tree size cap exceeded"); 3053 } 3054 } 3055 } 3056 3057 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3058 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3059 throw new SecurityException("Label must be specified in permission"); 3060 } 3061 BasePermission tree = checkPermissionTreeLP(info.name); 3062 BasePermission bp = mSettings.mPermissions.get(info.name); 3063 boolean added = bp == null; 3064 boolean changed = true; 3065 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3066 if (added) { 3067 enforcePermissionCapLocked(info, tree); 3068 bp = new BasePermission(info.name, tree.sourcePackage, 3069 BasePermission.TYPE_DYNAMIC); 3070 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3071 throw new SecurityException( 3072 "Not allowed to modify non-dynamic permission " 3073 + info.name); 3074 } else { 3075 if (bp.protectionLevel == fixedLevel 3076 && bp.perm.owner.equals(tree.perm.owner) 3077 && bp.uid == tree.uid 3078 && comparePermissionInfos(bp.perm.info, info)) { 3079 changed = false; 3080 } 3081 } 3082 bp.protectionLevel = fixedLevel; 3083 info = new PermissionInfo(info); 3084 info.protectionLevel = fixedLevel; 3085 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3086 bp.perm.info.packageName = tree.perm.info.packageName; 3087 bp.uid = tree.uid; 3088 if (added) { 3089 mSettings.mPermissions.put(info.name, bp); 3090 } 3091 if (changed) { 3092 if (!async) { 3093 mSettings.writeLPr(); 3094 } else { 3095 scheduleWriteSettingsLocked(); 3096 } 3097 } 3098 return added; 3099 } 3100 3101 @Override 3102 public boolean addPermission(PermissionInfo info) { 3103 synchronized (mPackages) { 3104 return addPermissionLocked(info, false); 3105 } 3106 } 3107 3108 @Override 3109 public boolean addPermissionAsync(PermissionInfo info) { 3110 synchronized (mPackages) { 3111 return addPermissionLocked(info, true); 3112 } 3113 } 3114 3115 @Override 3116 public void removePermission(String name) { 3117 synchronized (mPackages) { 3118 checkPermissionTreeLP(name); 3119 BasePermission bp = mSettings.mPermissions.get(name); 3120 if (bp != null) { 3121 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3122 throw new SecurityException( 3123 "Not allowed to modify non-dynamic permission " 3124 + name); 3125 } 3126 mSettings.mPermissions.remove(name); 3127 mSettings.writeLPr(); 3128 } 3129 } 3130 } 3131 3132 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3133 BasePermission bp) { 3134 int index = pkg.requestedPermissions.indexOf(bp.name); 3135 if (index == -1) { 3136 throw new SecurityException("Package " + pkg.packageName 3137 + " has not requested permission " + bp.name); 3138 } 3139 if (!bp.isRuntime()) { 3140 throw new SecurityException("Permission " + bp.name 3141 + " is not a changeable permission type"); 3142 } 3143 } 3144 3145 private static void enforceOnlySystemUpdatesPermissionPolicyFlags(int flagMask, int flagValues) { 3146 if (((flagMask & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0 3147 || (flagValues & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) 3148 && getCallingUid() != Process.SYSTEM_UID) { 3149 throw new SecurityException("Only the system can modify policy flags"); 3150 } 3151 } 3152 3153 @Override 3154 public void grantRuntimePermission(String packageName, String name, int userId) { 3155 if (!sUserManager.exists(userId)) { 3156 return; 3157 } 3158 3159 mContext.enforceCallingOrSelfPermission( 3160 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3161 "grantRuntimePermission"); 3162 3163 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3164 "grantRuntimePermission"); 3165 3166 boolean gidsChanged = false; 3167 final SettingBase sb; 3168 3169 synchronized (mPackages) { 3170 final PackageParser.Package pkg = mPackages.get(packageName); 3171 if (pkg == null) { 3172 throw new IllegalArgumentException("Unknown package: " + packageName); 3173 } 3174 3175 final BasePermission bp = mSettings.mPermissions.get(name); 3176 if (bp == null) { 3177 throw new IllegalArgumentException("Unknown permission: " + name); 3178 } 3179 3180 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3181 3182 sb = (SettingBase) pkg.mExtras; 3183 if (sb == null) { 3184 throw new IllegalArgumentException("Unknown package: " + packageName); 3185 } 3186 3187 final PermissionsState permissionsState = sb.getPermissionsState(); 3188 3189 final int result = permissionsState.grantRuntimePermission(bp, userId); 3190 switch (result) { 3191 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3192 return; 3193 } 3194 3195 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3196 gidsChanged = true; 3197 } 3198 break; 3199 } 3200 3201 // Not critical if that is lost - app has to request again. 3202 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3203 } 3204 3205 if (gidsChanged) { 3206 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3207 } 3208 } 3209 3210 @Override 3211 public void revokeRuntimePermission(String packageName, String name, int userId) { 3212 if (!sUserManager.exists(userId)) { 3213 return; 3214 } 3215 3216 mContext.enforceCallingOrSelfPermission( 3217 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3218 "revokeRuntimePermission"); 3219 3220 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3221 "revokeRuntimePermission"); 3222 3223 final SettingBase sb; 3224 3225 synchronized (mPackages) { 3226 final PackageParser.Package pkg = mPackages.get(packageName); 3227 if (pkg == null) { 3228 throw new IllegalArgumentException("Unknown package: " + packageName); 3229 } 3230 3231 final BasePermission bp = mSettings.mPermissions.get(name); 3232 if (bp == null) { 3233 throw new IllegalArgumentException("Unknown permission: " + name); 3234 } 3235 3236 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3237 3238 sb = (SettingBase) pkg.mExtras; 3239 if (sb == null) { 3240 throw new IllegalArgumentException("Unknown package: " + packageName); 3241 } 3242 3243 final PermissionsState permissionsState = sb.getPermissionsState(); 3244 3245 if (permissionsState.revokeRuntimePermission(bp, userId) == 3246 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3247 return; 3248 } 3249 3250 // Critical, after this call app should never have the permission. 3251 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3252 } 3253 3254 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3255 } 3256 3257 @Override 3258 public int getPermissionFlags(String name, String packageName, int userId) { 3259 if (!sUserManager.exists(userId)) { 3260 return 0; 3261 } 3262 3263 mContext.enforceCallingOrSelfPermission( 3264 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3265 "getPermissionFlags"); 3266 3267 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3268 "getPermissionFlags"); 3269 3270 synchronized (mPackages) { 3271 final PackageParser.Package pkg = mPackages.get(packageName); 3272 if (pkg == null) { 3273 throw new IllegalArgumentException("Unknown package: " + packageName); 3274 } 3275 3276 final BasePermission bp = mSettings.mPermissions.get(name); 3277 if (bp == null) { 3278 throw new IllegalArgumentException("Unknown permission: " + name); 3279 } 3280 3281 SettingBase sb = (SettingBase) pkg.mExtras; 3282 if (sb == null) { 3283 throw new IllegalArgumentException("Unknown package: " + packageName); 3284 } 3285 3286 PermissionsState permissionsState = sb.getPermissionsState(); 3287 return permissionsState.getPermissionFlags(name, userId); 3288 } 3289 } 3290 3291 @Override 3292 public void updatePermissionFlags(String name, String packageName, int flagMask, 3293 int flagValues, int userId) { 3294 if (!sUserManager.exists(userId)) { 3295 return; 3296 } 3297 3298 mContext.enforceCallingOrSelfPermission( 3299 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3300 "updatePermissionFlags"); 3301 3302 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3303 "updatePermissionFlags"); 3304 3305 enforceOnlySystemUpdatesPermissionPolicyFlags(flagMask, flagValues); 3306 3307 synchronized (mPackages) { 3308 final PackageParser.Package pkg = mPackages.get(packageName); 3309 if (pkg == null) { 3310 throw new IllegalArgumentException("Unknown package: " + packageName); 3311 } 3312 3313 final BasePermission bp = mSettings.mPermissions.get(name); 3314 if (bp == null) { 3315 throw new IllegalArgumentException("Unknown permission: " + name); 3316 } 3317 3318 SettingBase sb = (SettingBase) pkg.mExtras; 3319 if (sb == null) { 3320 throw new IllegalArgumentException("Unknown package: " + packageName); 3321 } 3322 3323 PermissionsState permissionsState = sb.getPermissionsState(); 3324 3325 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3326 // Install and runtime permissions are stored in different places, 3327 // so figure out what permission changed and persist the change. 3328 if (permissionsState.getInstallPermissionState(name) != null) { 3329 scheduleWriteSettingsLocked(); 3330 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3331 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3332 } 3333 } 3334 } 3335 } 3336 3337 @Override 3338 public boolean isProtectedBroadcast(String actionName) { 3339 synchronized (mPackages) { 3340 return mProtectedBroadcasts.contains(actionName); 3341 } 3342 } 3343 3344 @Override 3345 public int checkSignatures(String pkg1, String pkg2) { 3346 synchronized (mPackages) { 3347 final PackageParser.Package p1 = mPackages.get(pkg1); 3348 final PackageParser.Package p2 = mPackages.get(pkg2); 3349 if (p1 == null || p1.mExtras == null 3350 || p2 == null || p2.mExtras == null) { 3351 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3352 } 3353 return compareSignatures(p1.mSignatures, p2.mSignatures); 3354 } 3355 } 3356 3357 @Override 3358 public int checkUidSignatures(int uid1, int uid2) { 3359 // Map to base uids. 3360 uid1 = UserHandle.getAppId(uid1); 3361 uid2 = UserHandle.getAppId(uid2); 3362 // reader 3363 synchronized (mPackages) { 3364 Signature[] s1; 3365 Signature[] s2; 3366 Object obj = mSettings.getUserIdLPr(uid1); 3367 if (obj != null) { 3368 if (obj instanceof SharedUserSetting) { 3369 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3370 } else if (obj instanceof PackageSetting) { 3371 s1 = ((PackageSetting)obj).signatures.mSignatures; 3372 } else { 3373 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3374 } 3375 } else { 3376 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3377 } 3378 obj = mSettings.getUserIdLPr(uid2); 3379 if (obj != null) { 3380 if (obj instanceof SharedUserSetting) { 3381 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3382 } else if (obj instanceof PackageSetting) { 3383 s2 = ((PackageSetting)obj).signatures.mSignatures; 3384 } else { 3385 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3386 } 3387 } else { 3388 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3389 } 3390 return compareSignatures(s1, s2); 3391 } 3392 } 3393 3394 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3395 final long identity = Binder.clearCallingIdentity(); 3396 try { 3397 if (sb instanceof SharedUserSetting) { 3398 SharedUserSetting sus = (SharedUserSetting) sb; 3399 final int packageCount = sus.packages.size(); 3400 for (int i = 0; i < packageCount; i++) { 3401 PackageSetting susPs = sus.packages.valueAt(i); 3402 if (userId == UserHandle.USER_ALL) { 3403 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3404 } else { 3405 final int uid = UserHandle.getUid(userId, susPs.appId); 3406 killUid(uid, reason); 3407 } 3408 } 3409 } else if (sb instanceof PackageSetting) { 3410 PackageSetting ps = (PackageSetting) sb; 3411 if (userId == UserHandle.USER_ALL) { 3412 killApplication(ps.pkg.packageName, ps.appId, reason); 3413 } else { 3414 final int uid = UserHandle.getUid(userId, ps.appId); 3415 killUid(uid, reason); 3416 } 3417 } 3418 } finally { 3419 Binder.restoreCallingIdentity(identity); 3420 } 3421 } 3422 3423 private static void killUid(int uid, String reason) { 3424 IActivityManager am = ActivityManagerNative.getDefault(); 3425 if (am != null) { 3426 try { 3427 am.killUid(uid, reason); 3428 } catch (RemoteException e) { 3429 /* ignore - same process */ 3430 } 3431 } 3432 } 3433 3434 /** 3435 * Compares two sets of signatures. Returns: 3436 * <br /> 3437 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3438 * <br /> 3439 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3440 * <br /> 3441 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3442 * <br /> 3443 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3444 * <br /> 3445 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3446 */ 3447 static int compareSignatures(Signature[] s1, Signature[] s2) { 3448 if (s1 == null) { 3449 return s2 == null 3450 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3451 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3452 } 3453 3454 if (s2 == null) { 3455 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3456 } 3457 3458 if (s1.length != s2.length) { 3459 return PackageManager.SIGNATURE_NO_MATCH; 3460 } 3461 3462 // Since both signature sets are of size 1, we can compare without HashSets. 3463 if (s1.length == 1) { 3464 return s1[0].equals(s2[0]) ? 3465 PackageManager.SIGNATURE_MATCH : 3466 PackageManager.SIGNATURE_NO_MATCH; 3467 } 3468 3469 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3470 for (Signature sig : s1) { 3471 set1.add(sig); 3472 } 3473 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3474 for (Signature sig : s2) { 3475 set2.add(sig); 3476 } 3477 // Make sure s2 contains all signatures in s1. 3478 if (set1.equals(set2)) { 3479 return PackageManager.SIGNATURE_MATCH; 3480 } 3481 return PackageManager.SIGNATURE_NO_MATCH; 3482 } 3483 3484 /** 3485 * If the database version for this type of package (internal storage or 3486 * external storage) is less than the version where package signatures 3487 * were updated, return true. 3488 */ 3489 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3490 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3491 DatabaseVersion.SIGNATURE_END_ENTITY)) 3492 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3493 DatabaseVersion.SIGNATURE_END_ENTITY)); 3494 } 3495 3496 /** 3497 * Used for backward compatibility to make sure any packages with 3498 * certificate chains get upgraded to the new style. {@code existingSigs} 3499 * will be in the old format (since they were stored on disk from before the 3500 * system upgrade) and {@code scannedSigs} will be in the newer format. 3501 */ 3502 private int compareSignaturesCompat(PackageSignatures existingSigs, 3503 PackageParser.Package scannedPkg) { 3504 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3505 return PackageManager.SIGNATURE_NO_MATCH; 3506 } 3507 3508 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3509 for (Signature sig : existingSigs.mSignatures) { 3510 existingSet.add(sig); 3511 } 3512 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3513 for (Signature sig : scannedPkg.mSignatures) { 3514 try { 3515 Signature[] chainSignatures = sig.getChainSignatures(); 3516 for (Signature chainSig : chainSignatures) { 3517 scannedCompatSet.add(chainSig); 3518 } 3519 } catch (CertificateEncodingException e) { 3520 scannedCompatSet.add(sig); 3521 } 3522 } 3523 /* 3524 * Make sure the expanded scanned set contains all signatures in the 3525 * existing one. 3526 */ 3527 if (scannedCompatSet.equals(existingSet)) { 3528 // Migrate the old signatures to the new scheme. 3529 existingSigs.assignSignatures(scannedPkg.mSignatures); 3530 // The new KeySets will be re-added later in the scanning process. 3531 synchronized (mPackages) { 3532 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3533 } 3534 return PackageManager.SIGNATURE_MATCH; 3535 } 3536 return PackageManager.SIGNATURE_NO_MATCH; 3537 } 3538 3539 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3540 if (isExternal(scannedPkg)) { 3541 return mSettings.isExternalDatabaseVersionOlderThan( 3542 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3543 } else { 3544 return mSettings.isInternalDatabaseVersionOlderThan( 3545 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3546 } 3547 } 3548 3549 private int compareSignaturesRecover(PackageSignatures existingSigs, 3550 PackageParser.Package scannedPkg) { 3551 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3552 return PackageManager.SIGNATURE_NO_MATCH; 3553 } 3554 3555 String msg = null; 3556 try { 3557 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3558 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3559 + scannedPkg.packageName); 3560 return PackageManager.SIGNATURE_MATCH; 3561 } 3562 } catch (CertificateException e) { 3563 msg = e.getMessage(); 3564 } 3565 3566 logCriticalInfo(Log.INFO, 3567 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3568 return PackageManager.SIGNATURE_NO_MATCH; 3569 } 3570 3571 @Override 3572 public String[] getPackagesForUid(int uid) { 3573 uid = UserHandle.getAppId(uid); 3574 // reader 3575 synchronized (mPackages) { 3576 Object obj = mSettings.getUserIdLPr(uid); 3577 if (obj instanceof SharedUserSetting) { 3578 final SharedUserSetting sus = (SharedUserSetting) obj; 3579 final int N = sus.packages.size(); 3580 final String[] res = new String[N]; 3581 final Iterator<PackageSetting> it = sus.packages.iterator(); 3582 int i = 0; 3583 while (it.hasNext()) { 3584 res[i++] = it.next().name; 3585 } 3586 return res; 3587 } else if (obj instanceof PackageSetting) { 3588 final PackageSetting ps = (PackageSetting) obj; 3589 return new String[] { ps.name }; 3590 } 3591 } 3592 return null; 3593 } 3594 3595 @Override 3596 public String getNameForUid(int uid) { 3597 // reader 3598 synchronized (mPackages) { 3599 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3600 if (obj instanceof SharedUserSetting) { 3601 final SharedUserSetting sus = (SharedUserSetting) obj; 3602 return sus.name + ":" + sus.userId; 3603 } else if (obj instanceof PackageSetting) { 3604 final PackageSetting ps = (PackageSetting) obj; 3605 return ps.name; 3606 } 3607 } 3608 return null; 3609 } 3610 3611 @Override 3612 public int getUidForSharedUser(String sharedUserName) { 3613 if(sharedUserName == null) { 3614 return -1; 3615 } 3616 // reader 3617 synchronized (mPackages) { 3618 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3619 if (suid == null) { 3620 return -1; 3621 } 3622 return suid.userId; 3623 } 3624 } 3625 3626 @Override 3627 public int getFlagsForUid(int uid) { 3628 synchronized (mPackages) { 3629 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3630 if (obj instanceof SharedUserSetting) { 3631 final SharedUserSetting sus = (SharedUserSetting) obj; 3632 return sus.pkgFlags; 3633 } else if (obj instanceof PackageSetting) { 3634 final PackageSetting ps = (PackageSetting) obj; 3635 return ps.pkgFlags; 3636 } 3637 } 3638 return 0; 3639 } 3640 3641 @Override 3642 public int getPrivateFlagsForUid(int uid) { 3643 synchronized (mPackages) { 3644 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3645 if (obj instanceof SharedUserSetting) { 3646 final SharedUserSetting sus = (SharedUserSetting) obj; 3647 return sus.pkgPrivateFlags; 3648 } else if (obj instanceof PackageSetting) { 3649 final PackageSetting ps = (PackageSetting) obj; 3650 return ps.pkgPrivateFlags; 3651 } 3652 } 3653 return 0; 3654 } 3655 3656 @Override 3657 public boolean isUidPrivileged(int uid) { 3658 uid = UserHandle.getAppId(uid); 3659 // reader 3660 synchronized (mPackages) { 3661 Object obj = mSettings.getUserIdLPr(uid); 3662 if (obj instanceof SharedUserSetting) { 3663 final SharedUserSetting sus = (SharedUserSetting) obj; 3664 final Iterator<PackageSetting> it = sus.packages.iterator(); 3665 while (it.hasNext()) { 3666 if (it.next().isPrivileged()) { 3667 return true; 3668 } 3669 } 3670 } else if (obj instanceof PackageSetting) { 3671 final PackageSetting ps = (PackageSetting) obj; 3672 return ps.isPrivileged(); 3673 } 3674 } 3675 return false; 3676 } 3677 3678 @Override 3679 public String[] getAppOpPermissionPackages(String permissionName) { 3680 synchronized (mPackages) { 3681 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3682 if (pkgs == null) { 3683 return null; 3684 } 3685 return pkgs.toArray(new String[pkgs.size()]); 3686 } 3687 } 3688 3689 @Override 3690 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3691 int flags, int userId) { 3692 if (!sUserManager.exists(userId)) return null; 3693 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3694 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3695 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3696 } 3697 3698 @Override 3699 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3700 IntentFilter filter, int match, ComponentName activity) { 3701 final int userId = UserHandle.getCallingUserId(); 3702 if (DEBUG_PREFERRED) { 3703 Log.v(TAG, "setLastChosenActivity intent=" + intent 3704 + " resolvedType=" + resolvedType 3705 + " flags=" + flags 3706 + " filter=" + filter 3707 + " match=" + match 3708 + " activity=" + activity); 3709 filter.dump(new PrintStreamPrinter(System.out), " "); 3710 } 3711 intent.setComponent(null); 3712 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3713 // Find any earlier preferred or last chosen entries and nuke them 3714 findPreferredActivity(intent, resolvedType, 3715 flags, query, 0, false, true, false, userId); 3716 // Add the new activity as the last chosen for this filter 3717 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3718 "Setting last chosen"); 3719 } 3720 3721 @Override 3722 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3723 final int userId = UserHandle.getCallingUserId(); 3724 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3725 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3726 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3727 false, false, false, userId); 3728 } 3729 3730 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3731 int flags, List<ResolveInfo> query, int userId) { 3732 if (query != null) { 3733 final int N = query.size(); 3734 if (N == 1) { 3735 return query.get(0); 3736 } else if (N > 1) { 3737 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3738 // If there is more than one activity with the same priority, 3739 // then let the user decide between them. 3740 ResolveInfo r0 = query.get(0); 3741 ResolveInfo r1 = query.get(1); 3742 if (DEBUG_INTENT_MATCHING || debug) { 3743 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3744 + r1.activityInfo.name + "=" + r1.priority); 3745 } 3746 // If the first activity has a higher priority, or a different 3747 // default, then it is always desireable to pick it. 3748 if (r0.priority != r1.priority 3749 || r0.preferredOrder != r1.preferredOrder 3750 || r0.isDefault != r1.isDefault) { 3751 return query.get(0); 3752 } 3753 // If we have saved a preference for a preferred activity for 3754 // this Intent, use that. 3755 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3756 flags, query, r0.priority, true, false, debug, userId); 3757 if (ri != null) { 3758 return ri; 3759 } 3760 if (userId != 0) { 3761 ri = new ResolveInfo(mResolveInfo); 3762 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3763 ri.activityInfo.applicationInfo = new ApplicationInfo( 3764 ri.activityInfo.applicationInfo); 3765 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3766 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3767 return ri; 3768 } 3769 return mResolveInfo; 3770 } 3771 } 3772 return null; 3773 } 3774 3775 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3776 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3777 final int N = query.size(); 3778 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3779 .get(userId); 3780 // Get the list of persistent preferred activities that handle the intent 3781 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3782 List<PersistentPreferredActivity> pprefs = ppir != null 3783 ? ppir.queryIntent(intent, resolvedType, 3784 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3785 : null; 3786 if (pprefs != null && pprefs.size() > 0) { 3787 final int M = pprefs.size(); 3788 for (int i=0; i<M; i++) { 3789 final PersistentPreferredActivity ppa = pprefs.get(i); 3790 if (DEBUG_PREFERRED || debug) { 3791 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3792 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3793 + "\n component=" + ppa.mComponent); 3794 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3795 } 3796 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3797 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3798 if (DEBUG_PREFERRED || debug) { 3799 Slog.v(TAG, "Found persistent preferred activity:"); 3800 if (ai != null) { 3801 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3802 } else { 3803 Slog.v(TAG, " null"); 3804 } 3805 } 3806 if (ai == null) { 3807 // This previously registered persistent preferred activity 3808 // component is no longer known. Ignore it and do NOT remove it. 3809 continue; 3810 } 3811 for (int j=0; j<N; j++) { 3812 final ResolveInfo ri = query.get(j); 3813 if (!ri.activityInfo.applicationInfo.packageName 3814 .equals(ai.applicationInfo.packageName)) { 3815 continue; 3816 } 3817 if (!ri.activityInfo.name.equals(ai.name)) { 3818 continue; 3819 } 3820 // Found a persistent preference that can handle the intent. 3821 if (DEBUG_PREFERRED || debug) { 3822 Slog.v(TAG, "Returning persistent preferred activity: " + 3823 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3824 } 3825 return ri; 3826 } 3827 } 3828 } 3829 return null; 3830 } 3831 3832 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3833 List<ResolveInfo> query, int priority, boolean always, 3834 boolean removeMatches, boolean debug, int userId) { 3835 if (!sUserManager.exists(userId)) return null; 3836 // writer 3837 synchronized (mPackages) { 3838 if (intent.getSelector() != null) { 3839 intent = intent.getSelector(); 3840 } 3841 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3842 3843 // Try to find a matching persistent preferred activity. 3844 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3845 debug, userId); 3846 3847 // If a persistent preferred activity matched, use it. 3848 if (pri != null) { 3849 return pri; 3850 } 3851 3852 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3853 // Get the list of preferred activities that handle the intent 3854 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3855 List<PreferredActivity> prefs = pir != null 3856 ? pir.queryIntent(intent, resolvedType, 3857 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3858 : null; 3859 if (prefs != null && prefs.size() > 0) { 3860 boolean changed = false; 3861 try { 3862 // First figure out how good the original match set is. 3863 // We will only allow preferred activities that came 3864 // from the same match quality. 3865 int match = 0; 3866 3867 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3868 3869 final int N = query.size(); 3870 for (int j=0; j<N; j++) { 3871 final ResolveInfo ri = query.get(j); 3872 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3873 + ": 0x" + Integer.toHexString(match)); 3874 if (ri.match > match) { 3875 match = ri.match; 3876 } 3877 } 3878 3879 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3880 + Integer.toHexString(match)); 3881 3882 match &= IntentFilter.MATCH_CATEGORY_MASK; 3883 final int M = prefs.size(); 3884 for (int i=0; i<M; i++) { 3885 final PreferredActivity pa = prefs.get(i); 3886 if (DEBUG_PREFERRED || debug) { 3887 Slog.v(TAG, "Checking PreferredActivity ds=" 3888 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3889 + "\n component=" + pa.mPref.mComponent); 3890 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3891 } 3892 if (pa.mPref.mMatch != match) { 3893 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3894 + Integer.toHexString(pa.mPref.mMatch)); 3895 continue; 3896 } 3897 // If it's not an "always" type preferred activity and that's what we're 3898 // looking for, skip it. 3899 if (always && !pa.mPref.mAlways) { 3900 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3901 continue; 3902 } 3903 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3904 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3905 if (DEBUG_PREFERRED || debug) { 3906 Slog.v(TAG, "Found preferred activity:"); 3907 if (ai != null) { 3908 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3909 } else { 3910 Slog.v(TAG, " null"); 3911 } 3912 } 3913 if (ai == null) { 3914 // This previously registered preferred activity 3915 // component is no longer known. Most likely an update 3916 // to the app was installed and in the new version this 3917 // component no longer exists. Clean it up by removing 3918 // it from the preferred activities list, and skip it. 3919 Slog.w(TAG, "Removing dangling preferred activity: " 3920 + pa.mPref.mComponent); 3921 pir.removeFilter(pa); 3922 changed = true; 3923 continue; 3924 } 3925 for (int j=0; j<N; j++) { 3926 final ResolveInfo ri = query.get(j); 3927 if (!ri.activityInfo.applicationInfo.packageName 3928 .equals(ai.applicationInfo.packageName)) { 3929 continue; 3930 } 3931 if (!ri.activityInfo.name.equals(ai.name)) { 3932 continue; 3933 } 3934 3935 if (removeMatches) { 3936 pir.removeFilter(pa); 3937 changed = true; 3938 if (DEBUG_PREFERRED) { 3939 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3940 } 3941 break; 3942 } 3943 3944 // Okay we found a previously set preferred or last chosen app. 3945 // If the result set is different from when this 3946 // was created, we need to clear it and re-ask the 3947 // user their preference, if we're looking for an "always" type entry. 3948 if (always && !pa.mPref.sameSet(query)) { 3949 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3950 + intent + " type " + resolvedType); 3951 if (DEBUG_PREFERRED) { 3952 Slog.v(TAG, "Removing preferred activity since set changed " 3953 + pa.mPref.mComponent); 3954 } 3955 pir.removeFilter(pa); 3956 // Re-add the filter as a "last chosen" entry (!always) 3957 PreferredActivity lastChosen = new PreferredActivity( 3958 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3959 pir.addFilter(lastChosen); 3960 changed = true; 3961 return null; 3962 } 3963 3964 // Yay! Either the set matched or we're looking for the last chosen 3965 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3966 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3967 return ri; 3968 } 3969 } 3970 } finally { 3971 if (changed) { 3972 if (DEBUG_PREFERRED) { 3973 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3974 } 3975 scheduleWritePackageRestrictionsLocked(userId); 3976 } 3977 } 3978 } 3979 } 3980 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3981 return null; 3982 } 3983 3984 /* 3985 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3986 */ 3987 @Override 3988 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3989 int targetUserId) { 3990 mContext.enforceCallingOrSelfPermission( 3991 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3992 List<CrossProfileIntentFilter> matches = 3993 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3994 if (matches != null) { 3995 int size = matches.size(); 3996 for (int i = 0; i < size; i++) { 3997 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3998 } 3999 } 4000 return false; 4001 } 4002 4003 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4004 String resolvedType, int userId) { 4005 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4006 if (resolver != null) { 4007 return resolver.queryIntent(intent, resolvedType, false, userId); 4008 } 4009 return null; 4010 } 4011 4012 @Override 4013 public List<ResolveInfo> queryIntentActivities(Intent intent, 4014 String resolvedType, int flags, int userId) { 4015 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4016 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4017 ComponentName comp = intent.getComponent(); 4018 if (comp == null) { 4019 if (intent.getSelector() != null) { 4020 intent = intent.getSelector(); 4021 comp = intent.getComponent(); 4022 } 4023 } 4024 4025 if (comp != null) { 4026 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4027 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4028 if (ai != null) { 4029 final ResolveInfo ri = new ResolveInfo(); 4030 ri.activityInfo = ai; 4031 list.add(ri); 4032 } 4033 return list; 4034 } 4035 4036 // reader 4037 synchronized (mPackages) { 4038 final String pkgName = intent.getPackage(); 4039 if (pkgName == null) { 4040 List<CrossProfileIntentFilter> matchingFilters = 4041 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4042 // Check for results that need to skip the current profile. 4043 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4044 resolvedType, flags, userId); 4045 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4046 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4047 result.add(resolveInfo); 4048 return filterIfNotPrimaryUser(result, userId); 4049 } 4050 4051 // Check for results in the current profile. 4052 List<ResolveInfo> result = mActivities.queryIntent( 4053 intent, resolvedType, flags, userId); 4054 4055 // Check for cross profile results. 4056 resolveInfo = queryCrossProfileIntents( 4057 matchingFilters, intent, resolvedType, flags, userId); 4058 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4059 result.add(resolveInfo); 4060 Collections.sort(result, mResolvePrioritySorter); 4061 } 4062 result = filterIfNotPrimaryUser(result, userId); 4063 if (result.size() > 1 && hasWebURI(intent)) { 4064 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4065 } 4066 return result; 4067 } 4068 final PackageParser.Package pkg = mPackages.get(pkgName); 4069 if (pkg != null) { 4070 return filterIfNotPrimaryUser( 4071 mActivities.queryIntentForPackage( 4072 intent, resolvedType, flags, pkg.activities, userId), 4073 userId); 4074 } 4075 return new ArrayList<ResolveInfo>(); 4076 } 4077 } 4078 4079 private boolean isUserEnabled(int userId) { 4080 long callingId = Binder.clearCallingIdentity(); 4081 try { 4082 UserInfo userInfo = sUserManager.getUserInfo(userId); 4083 return userInfo != null && userInfo.isEnabled(); 4084 } finally { 4085 Binder.restoreCallingIdentity(callingId); 4086 } 4087 } 4088 4089 /** 4090 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4091 * 4092 * @return filtered list 4093 */ 4094 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4095 if (userId == UserHandle.USER_OWNER) { 4096 return resolveInfos; 4097 } 4098 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4099 ResolveInfo info = resolveInfos.get(i); 4100 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4101 resolveInfos.remove(i); 4102 } 4103 } 4104 return resolveInfos; 4105 } 4106 4107 private static boolean hasWebURI(Intent intent) { 4108 if (intent.getData() == null) { 4109 return false; 4110 } 4111 final String scheme = intent.getScheme(); 4112 if (TextUtils.isEmpty(scheme)) { 4113 return false; 4114 } 4115 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4116 } 4117 4118 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4119 int flags, List<ResolveInfo> candidates) { 4120 if (DEBUG_PREFERRED) { 4121 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4122 candidates.size()); 4123 } 4124 4125 final int userId = UserHandle.getCallingUserId(); 4126 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4127 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4128 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4129 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4130 4131 synchronized (mPackages) { 4132 final int count = candidates.size(); 4133 // First, try to use the domain prefered App 4134 for (int n=0; n<count; n++) { 4135 ResolveInfo info = candidates.get(n); 4136 String packageName = info.activityInfo.packageName; 4137 PackageSetting ps = mSettings.mPackages.get(packageName); 4138 if (ps != null) { 4139 // Add to the special match all list (Browser use case) 4140 if (info.handleAllWebDataURI) { 4141 matchAllList.add(info); 4142 continue; 4143 } 4144 // Try to get the status from User settings first 4145 int status = getDomainVerificationStatusLPr(ps, userId); 4146 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4147 result.add(info); 4148 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4149 neverList.add(info); 4150 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4151 undefinedList.add(info); 4152 } 4153 } 4154 } 4155 // If there is nothing selected, add all candidates and remove the ones that the User 4156 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4157 // also remove any Browser Apps ones. 4158 // If there is still none after this pass, add all undefined one and Browser Apps and 4159 // let the User decide with the Disambiguation dialog if there are several ones. 4160 if (result.size() == 0) { 4161 result.addAll(candidates); 4162 } 4163 result.removeAll(neverList); 4164 result.removeAll(matchAllList); 4165 if (result.size() == 0) { 4166 result.addAll(undefinedList); 4167 if ((flags & MATCH_ALL) != 0) { 4168 result.addAll(matchAllList); 4169 } else { 4170 // Try to add the Default Browser if we can 4171 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4172 UserHandle.myUserId()); 4173 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4174 boolean defaultBrowserFound = false; 4175 final int browserCount = matchAllList.size(); 4176 for (int n=0; n<browserCount; n++) { 4177 ResolveInfo browser = matchAllList.get(n); 4178 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4179 result.add(browser); 4180 defaultBrowserFound = true; 4181 break; 4182 } 4183 } 4184 if (!defaultBrowserFound) { 4185 result.addAll(matchAllList); 4186 } 4187 } else { 4188 result.addAll(matchAllList); 4189 } 4190 } 4191 } 4192 } 4193 if (DEBUG_PREFERRED) { 4194 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4195 result.size()); 4196 } 4197 return result; 4198 } 4199 4200 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4201 int status = ps.getDomainVerificationStatusForUser(userId); 4202 // if none available, get the master status 4203 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4204 if (ps.getIntentFilterVerificationInfo() != null) { 4205 status = ps.getIntentFilterVerificationInfo().getStatus(); 4206 } 4207 } 4208 return status; 4209 } 4210 4211 private ResolveInfo querySkipCurrentProfileIntents( 4212 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4213 int flags, int sourceUserId) { 4214 if (matchingFilters != null) { 4215 int size = matchingFilters.size(); 4216 for (int i = 0; i < size; i ++) { 4217 CrossProfileIntentFilter filter = matchingFilters.get(i); 4218 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4219 // Checking if there are activities in the target user that can handle the 4220 // intent. 4221 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4222 flags, sourceUserId); 4223 if (resolveInfo != null) { 4224 return resolveInfo; 4225 } 4226 } 4227 } 4228 } 4229 return null; 4230 } 4231 4232 // Return matching ResolveInfo if any for skip current profile intent filters. 4233 private ResolveInfo queryCrossProfileIntents( 4234 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4235 int flags, int sourceUserId) { 4236 if (matchingFilters != null) { 4237 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4238 // match the same intent. For performance reasons, it is better not to 4239 // run queryIntent twice for the same userId 4240 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4241 int size = matchingFilters.size(); 4242 for (int i = 0; i < size; i++) { 4243 CrossProfileIntentFilter filter = matchingFilters.get(i); 4244 int targetUserId = filter.getTargetUserId(); 4245 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4246 && !alreadyTriedUserIds.get(targetUserId)) { 4247 // Checking if there are activities in the target user that can handle the 4248 // intent. 4249 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4250 flags, sourceUserId); 4251 if (resolveInfo != null) return resolveInfo; 4252 alreadyTriedUserIds.put(targetUserId, true); 4253 } 4254 } 4255 } 4256 return null; 4257 } 4258 4259 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4260 String resolvedType, int flags, int sourceUserId) { 4261 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4262 resolvedType, flags, filter.getTargetUserId()); 4263 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4264 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4265 } 4266 return null; 4267 } 4268 4269 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4270 int sourceUserId, int targetUserId) { 4271 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4272 String className; 4273 if (targetUserId == UserHandle.USER_OWNER) { 4274 className = FORWARD_INTENT_TO_USER_OWNER; 4275 } else { 4276 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4277 } 4278 ComponentName forwardingActivityComponentName = new ComponentName( 4279 mAndroidApplication.packageName, className); 4280 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4281 sourceUserId); 4282 if (targetUserId == UserHandle.USER_OWNER) { 4283 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4284 forwardingResolveInfo.noResourceId = true; 4285 } 4286 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4287 forwardingResolveInfo.priority = 0; 4288 forwardingResolveInfo.preferredOrder = 0; 4289 forwardingResolveInfo.match = 0; 4290 forwardingResolveInfo.isDefault = true; 4291 forwardingResolveInfo.filter = filter; 4292 forwardingResolveInfo.targetUserId = targetUserId; 4293 return forwardingResolveInfo; 4294 } 4295 4296 @Override 4297 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4298 Intent[] specifics, String[] specificTypes, Intent intent, 4299 String resolvedType, int flags, int userId) { 4300 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4301 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4302 false, "query intent activity options"); 4303 final String resultsAction = intent.getAction(); 4304 4305 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4306 | PackageManager.GET_RESOLVED_FILTER, userId); 4307 4308 if (DEBUG_INTENT_MATCHING) { 4309 Log.v(TAG, "Query " + intent + ": " + results); 4310 } 4311 4312 int specificsPos = 0; 4313 int N; 4314 4315 // todo: note that the algorithm used here is O(N^2). This 4316 // isn't a problem in our current environment, but if we start running 4317 // into situations where we have more than 5 or 10 matches then this 4318 // should probably be changed to something smarter... 4319 4320 // First we go through and resolve each of the specific items 4321 // that were supplied, taking care of removing any corresponding 4322 // duplicate items in the generic resolve list. 4323 if (specifics != null) { 4324 for (int i=0; i<specifics.length; i++) { 4325 final Intent sintent = specifics[i]; 4326 if (sintent == null) { 4327 continue; 4328 } 4329 4330 if (DEBUG_INTENT_MATCHING) { 4331 Log.v(TAG, "Specific #" + i + ": " + sintent); 4332 } 4333 4334 String action = sintent.getAction(); 4335 if (resultsAction != null && resultsAction.equals(action)) { 4336 // If this action was explicitly requested, then don't 4337 // remove things that have it. 4338 action = null; 4339 } 4340 4341 ResolveInfo ri = null; 4342 ActivityInfo ai = null; 4343 4344 ComponentName comp = sintent.getComponent(); 4345 if (comp == null) { 4346 ri = resolveIntent( 4347 sintent, 4348 specificTypes != null ? specificTypes[i] : null, 4349 flags, userId); 4350 if (ri == null) { 4351 continue; 4352 } 4353 if (ri == mResolveInfo) { 4354 // ACK! Must do something better with this. 4355 } 4356 ai = ri.activityInfo; 4357 comp = new ComponentName(ai.applicationInfo.packageName, 4358 ai.name); 4359 } else { 4360 ai = getActivityInfo(comp, flags, userId); 4361 if (ai == null) { 4362 continue; 4363 } 4364 } 4365 4366 // Look for any generic query activities that are duplicates 4367 // of this specific one, and remove them from the results. 4368 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4369 N = results.size(); 4370 int j; 4371 for (j=specificsPos; j<N; j++) { 4372 ResolveInfo sri = results.get(j); 4373 if ((sri.activityInfo.name.equals(comp.getClassName()) 4374 && sri.activityInfo.applicationInfo.packageName.equals( 4375 comp.getPackageName())) 4376 || (action != null && sri.filter.matchAction(action))) { 4377 results.remove(j); 4378 if (DEBUG_INTENT_MATCHING) Log.v( 4379 TAG, "Removing duplicate item from " + j 4380 + " due to specific " + specificsPos); 4381 if (ri == null) { 4382 ri = sri; 4383 } 4384 j--; 4385 N--; 4386 } 4387 } 4388 4389 // Add this specific item to its proper place. 4390 if (ri == null) { 4391 ri = new ResolveInfo(); 4392 ri.activityInfo = ai; 4393 } 4394 results.add(specificsPos, ri); 4395 ri.specificIndex = i; 4396 specificsPos++; 4397 } 4398 } 4399 4400 // Now we go through the remaining generic results and remove any 4401 // duplicate actions that are found here. 4402 N = results.size(); 4403 for (int i=specificsPos; i<N-1; i++) { 4404 final ResolveInfo rii = results.get(i); 4405 if (rii.filter == null) { 4406 continue; 4407 } 4408 4409 // Iterate over all of the actions of this result's intent 4410 // filter... typically this should be just one. 4411 final Iterator<String> it = rii.filter.actionsIterator(); 4412 if (it == null) { 4413 continue; 4414 } 4415 while (it.hasNext()) { 4416 final String action = it.next(); 4417 if (resultsAction != null && resultsAction.equals(action)) { 4418 // If this action was explicitly requested, then don't 4419 // remove things that have it. 4420 continue; 4421 } 4422 for (int j=i+1; j<N; j++) { 4423 final ResolveInfo rij = results.get(j); 4424 if (rij.filter != null && rij.filter.hasAction(action)) { 4425 results.remove(j); 4426 if (DEBUG_INTENT_MATCHING) Log.v( 4427 TAG, "Removing duplicate item from " + j 4428 + " due to action " + action + " at " + i); 4429 j--; 4430 N--; 4431 } 4432 } 4433 } 4434 4435 // If the caller didn't request filter information, drop it now 4436 // so we don't have to marshall/unmarshall it. 4437 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4438 rii.filter = null; 4439 } 4440 } 4441 4442 // Filter out the caller activity if so requested. 4443 if (caller != null) { 4444 N = results.size(); 4445 for (int i=0; i<N; i++) { 4446 ActivityInfo ainfo = results.get(i).activityInfo; 4447 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4448 && caller.getClassName().equals(ainfo.name)) { 4449 results.remove(i); 4450 break; 4451 } 4452 } 4453 } 4454 4455 // If the caller didn't request filter information, 4456 // drop them now so we don't have to 4457 // marshall/unmarshall it. 4458 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4459 N = results.size(); 4460 for (int i=0; i<N; i++) { 4461 results.get(i).filter = null; 4462 } 4463 } 4464 4465 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4466 return results; 4467 } 4468 4469 @Override 4470 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4471 int userId) { 4472 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4473 ComponentName comp = intent.getComponent(); 4474 if (comp == null) { 4475 if (intent.getSelector() != null) { 4476 intent = intent.getSelector(); 4477 comp = intent.getComponent(); 4478 } 4479 } 4480 if (comp != null) { 4481 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4482 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4483 if (ai != null) { 4484 ResolveInfo ri = new ResolveInfo(); 4485 ri.activityInfo = ai; 4486 list.add(ri); 4487 } 4488 return list; 4489 } 4490 4491 // reader 4492 synchronized (mPackages) { 4493 String pkgName = intent.getPackage(); 4494 if (pkgName == null) { 4495 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4496 } 4497 final PackageParser.Package pkg = mPackages.get(pkgName); 4498 if (pkg != null) { 4499 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4500 userId); 4501 } 4502 return null; 4503 } 4504 } 4505 4506 @Override 4507 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4508 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4509 if (!sUserManager.exists(userId)) return null; 4510 if (query != null) { 4511 if (query.size() >= 1) { 4512 // If there is more than one service with the same priority, 4513 // just arbitrarily pick the first one. 4514 return query.get(0); 4515 } 4516 } 4517 return null; 4518 } 4519 4520 @Override 4521 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4522 int userId) { 4523 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4524 ComponentName comp = intent.getComponent(); 4525 if (comp == null) { 4526 if (intent.getSelector() != null) { 4527 intent = intent.getSelector(); 4528 comp = intent.getComponent(); 4529 } 4530 } 4531 if (comp != null) { 4532 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4533 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4534 if (si != null) { 4535 final ResolveInfo ri = new ResolveInfo(); 4536 ri.serviceInfo = si; 4537 list.add(ri); 4538 } 4539 return list; 4540 } 4541 4542 // reader 4543 synchronized (mPackages) { 4544 String pkgName = intent.getPackage(); 4545 if (pkgName == null) { 4546 return mServices.queryIntent(intent, resolvedType, flags, userId); 4547 } 4548 final PackageParser.Package pkg = mPackages.get(pkgName); 4549 if (pkg != null) { 4550 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4551 userId); 4552 } 4553 return null; 4554 } 4555 } 4556 4557 @Override 4558 public List<ResolveInfo> queryIntentContentProviders( 4559 Intent intent, String resolvedType, int flags, int userId) { 4560 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4561 ComponentName comp = intent.getComponent(); 4562 if (comp == null) { 4563 if (intent.getSelector() != null) { 4564 intent = intent.getSelector(); 4565 comp = intent.getComponent(); 4566 } 4567 } 4568 if (comp != null) { 4569 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4570 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4571 if (pi != null) { 4572 final ResolveInfo ri = new ResolveInfo(); 4573 ri.providerInfo = pi; 4574 list.add(ri); 4575 } 4576 return list; 4577 } 4578 4579 // reader 4580 synchronized (mPackages) { 4581 String pkgName = intent.getPackage(); 4582 if (pkgName == null) { 4583 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4584 } 4585 final PackageParser.Package pkg = mPackages.get(pkgName); 4586 if (pkg != null) { 4587 return mProviders.queryIntentForPackage( 4588 intent, resolvedType, flags, pkg.providers, userId); 4589 } 4590 return null; 4591 } 4592 } 4593 4594 @Override 4595 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4596 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4597 4598 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4599 4600 // writer 4601 synchronized (mPackages) { 4602 ArrayList<PackageInfo> list; 4603 if (listUninstalled) { 4604 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4605 for (PackageSetting ps : mSettings.mPackages.values()) { 4606 PackageInfo pi; 4607 if (ps.pkg != null) { 4608 pi = generatePackageInfo(ps.pkg, flags, userId); 4609 } else { 4610 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4611 } 4612 if (pi != null) { 4613 list.add(pi); 4614 } 4615 } 4616 } else { 4617 list = new ArrayList<PackageInfo>(mPackages.size()); 4618 for (PackageParser.Package p : mPackages.values()) { 4619 PackageInfo pi = generatePackageInfo(p, flags, userId); 4620 if (pi != null) { 4621 list.add(pi); 4622 } 4623 } 4624 } 4625 4626 return new ParceledListSlice<PackageInfo>(list); 4627 } 4628 } 4629 4630 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4631 String[] permissions, boolean[] tmp, int flags, int userId) { 4632 int numMatch = 0; 4633 final PermissionsState permissionsState = ps.getPermissionsState(); 4634 for (int i=0; i<permissions.length; i++) { 4635 final String permission = permissions[i]; 4636 if (permissionsState.hasPermission(permission, userId)) { 4637 tmp[i] = true; 4638 numMatch++; 4639 } else { 4640 tmp[i] = false; 4641 } 4642 } 4643 if (numMatch == 0) { 4644 return; 4645 } 4646 PackageInfo pi; 4647 if (ps.pkg != null) { 4648 pi = generatePackageInfo(ps.pkg, flags, userId); 4649 } else { 4650 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4651 } 4652 // The above might return null in cases of uninstalled apps or install-state 4653 // skew across users/profiles. 4654 if (pi != null) { 4655 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4656 if (numMatch == permissions.length) { 4657 pi.requestedPermissions = permissions; 4658 } else { 4659 pi.requestedPermissions = new String[numMatch]; 4660 numMatch = 0; 4661 for (int i=0; i<permissions.length; i++) { 4662 if (tmp[i]) { 4663 pi.requestedPermissions[numMatch] = permissions[i]; 4664 numMatch++; 4665 } 4666 } 4667 } 4668 } 4669 list.add(pi); 4670 } 4671 } 4672 4673 @Override 4674 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4675 String[] permissions, int flags, int userId) { 4676 if (!sUserManager.exists(userId)) return null; 4677 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4678 4679 // writer 4680 synchronized (mPackages) { 4681 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4682 boolean[] tmpBools = new boolean[permissions.length]; 4683 if (listUninstalled) { 4684 for (PackageSetting ps : mSettings.mPackages.values()) { 4685 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4686 } 4687 } else { 4688 for (PackageParser.Package pkg : mPackages.values()) { 4689 PackageSetting ps = (PackageSetting)pkg.mExtras; 4690 if (ps != null) { 4691 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4692 userId); 4693 } 4694 } 4695 } 4696 4697 return new ParceledListSlice<PackageInfo>(list); 4698 } 4699 } 4700 4701 @Override 4702 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4703 if (!sUserManager.exists(userId)) return null; 4704 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4705 4706 // writer 4707 synchronized (mPackages) { 4708 ArrayList<ApplicationInfo> list; 4709 if (listUninstalled) { 4710 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4711 for (PackageSetting ps : mSettings.mPackages.values()) { 4712 ApplicationInfo ai; 4713 if (ps.pkg != null) { 4714 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4715 ps.readUserState(userId), userId); 4716 } else { 4717 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4718 } 4719 if (ai != null) { 4720 list.add(ai); 4721 } 4722 } 4723 } else { 4724 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4725 for (PackageParser.Package p : mPackages.values()) { 4726 if (p.mExtras != null) { 4727 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4728 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4729 if (ai != null) { 4730 list.add(ai); 4731 } 4732 } 4733 } 4734 } 4735 4736 return new ParceledListSlice<ApplicationInfo>(list); 4737 } 4738 } 4739 4740 public List<ApplicationInfo> getPersistentApplications(int flags) { 4741 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4742 4743 // reader 4744 synchronized (mPackages) { 4745 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4746 final int userId = UserHandle.getCallingUserId(); 4747 while (i.hasNext()) { 4748 final PackageParser.Package p = i.next(); 4749 if (p.applicationInfo != null 4750 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4751 && (!mSafeMode || isSystemApp(p))) { 4752 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4753 if (ps != null) { 4754 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4755 ps.readUserState(userId), userId); 4756 if (ai != null) { 4757 finalList.add(ai); 4758 } 4759 } 4760 } 4761 } 4762 } 4763 4764 return finalList; 4765 } 4766 4767 @Override 4768 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4769 if (!sUserManager.exists(userId)) return null; 4770 // reader 4771 synchronized (mPackages) { 4772 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4773 PackageSetting ps = provider != null 4774 ? mSettings.mPackages.get(provider.owner.packageName) 4775 : null; 4776 return ps != null 4777 && mSettings.isEnabledLPr(provider.info, flags, userId) 4778 && (!mSafeMode || (provider.info.applicationInfo.flags 4779 &ApplicationInfo.FLAG_SYSTEM) != 0) 4780 ? PackageParser.generateProviderInfo(provider, flags, 4781 ps.readUserState(userId), userId) 4782 : null; 4783 } 4784 } 4785 4786 /** 4787 * @deprecated 4788 */ 4789 @Deprecated 4790 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4791 // reader 4792 synchronized (mPackages) { 4793 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4794 .entrySet().iterator(); 4795 final int userId = UserHandle.getCallingUserId(); 4796 while (i.hasNext()) { 4797 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4798 PackageParser.Provider p = entry.getValue(); 4799 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4800 4801 if (ps != null && p.syncable 4802 && (!mSafeMode || (p.info.applicationInfo.flags 4803 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4804 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4805 ps.readUserState(userId), userId); 4806 if (info != null) { 4807 outNames.add(entry.getKey()); 4808 outInfo.add(info); 4809 } 4810 } 4811 } 4812 } 4813 } 4814 4815 @Override 4816 public List<ProviderInfo> queryContentProviders(String processName, 4817 int uid, int flags) { 4818 ArrayList<ProviderInfo> finalList = null; 4819 // reader 4820 synchronized (mPackages) { 4821 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4822 final int userId = processName != null ? 4823 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4824 while (i.hasNext()) { 4825 final PackageParser.Provider p = i.next(); 4826 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4827 if (ps != null && p.info.authority != null 4828 && (processName == null 4829 || (p.info.processName.equals(processName) 4830 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4831 && mSettings.isEnabledLPr(p.info, flags, userId) 4832 && (!mSafeMode 4833 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4834 if (finalList == null) { 4835 finalList = new ArrayList<ProviderInfo>(3); 4836 } 4837 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4838 ps.readUserState(userId), userId); 4839 if (info != null) { 4840 finalList.add(info); 4841 } 4842 } 4843 } 4844 } 4845 4846 if (finalList != null) { 4847 Collections.sort(finalList, mProviderInitOrderSorter); 4848 } 4849 4850 return finalList; 4851 } 4852 4853 @Override 4854 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4855 int flags) { 4856 // reader 4857 synchronized (mPackages) { 4858 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4859 return PackageParser.generateInstrumentationInfo(i, flags); 4860 } 4861 } 4862 4863 @Override 4864 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4865 int flags) { 4866 ArrayList<InstrumentationInfo> finalList = 4867 new ArrayList<InstrumentationInfo>(); 4868 4869 // reader 4870 synchronized (mPackages) { 4871 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4872 while (i.hasNext()) { 4873 final PackageParser.Instrumentation p = i.next(); 4874 if (targetPackage == null 4875 || targetPackage.equals(p.info.targetPackage)) { 4876 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4877 flags); 4878 if (ii != null) { 4879 finalList.add(ii); 4880 } 4881 } 4882 } 4883 } 4884 4885 return finalList; 4886 } 4887 4888 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4889 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4890 if (overlays == null) { 4891 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4892 return; 4893 } 4894 for (PackageParser.Package opkg : overlays.values()) { 4895 // Not much to do if idmap fails: we already logged the error 4896 // and we certainly don't want to abort installation of pkg simply 4897 // because an overlay didn't fit properly. For these reasons, 4898 // ignore the return value of createIdmapForPackagePairLI. 4899 createIdmapForPackagePairLI(pkg, opkg); 4900 } 4901 } 4902 4903 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4904 PackageParser.Package opkg) { 4905 if (!opkg.mTrustedOverlay) { 4906 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4907 opkg.baseCodePath + ": overlay not trusted"); 4908 return false; 4909 } 4910 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4911 if (overlaySet == null) { 4912 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4913 opkg.baseCodePath + " but target package has no known overlays"); 4914 return false; 4915 } 4916 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4917 // TODO: generate idmap for split APKs 4918 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4919 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4920 + opkg.baseCodePath); 4921 return false; 4922 } 4923 PackageParser.Package[] overlayArray = 4924 overlaySet.values().toArray(new PackageParser.Package[0]); 4925 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4926 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4927 return p1.mOverlayPriority - p2.mOverlayPriority; 4928 } 4929 }; 4930 Arrays.sort(overlayArray, cmp); 4931 4932 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4933 int i = 0; 4934 for (PackageParser.Package p : overlayArray) { 4935 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4936 } 4937 return true; 4938 } 4939 4940 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4941 final File[] files = dir.listFiles(); 4942 if (ArrayUtils.isEmpty(files)) { 4943 Log.d(TAG, "No files in app dir " + dir); 4944 return; 4945 } 4946 4947 if (DEBUG_PACKAGE_SCANNING) { 4948 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4949 + " flags=0x" + Integer.toHexString(parseFlags)); 4950 } 4951 4952 for (File file : files) { 4953 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4954 && !PackageInstallerService.isStageName(file.getName()); 4955 if (!isPackage) { 4956 // Ignore entries which are not packages 4957 continue; 4958 } 4959 try { 4960 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4961 scanFlags, currentTime, null); 4962 } catch (PackageManagerException e) { 4963 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4964 4965 // Delete invalid userdata apps 4966 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4967 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4968 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4969 if (file.isDirectory()) { 4970 mInstaller.rmPackageDir(file.getAbsolutePath()); 4971 } else { 4972 file.delete(); 4973 } 4974 } 4975 } 4976 } 4977 } 4978 4979 private static File getSettingsProblemFile() { 4980 File dataDir = Environment.getDataDirectory(); 4981 File systemDir = new File(dataDir, "system"); 4982 File fname = new File(systemDir, "uiderrors.txt"); 4983 return fname; 4984 } 4985 4986 static void reportSettingsProblem(int priority, String msg) { 4987 logCriticalInfo(priority, msg); 4988 } 4989 4990 static void logCriticalInfo(int priority, String msg) { 4991 Slog.println(priority, TAG, msg); 4992 EventLogTags.writePmCriticalInfo(msg); 4993 try { 4994 File fname = getSettingsProblemFile(); 4995 FileOutputStream out = new FileOutputStream(fname, true); 4996 PrintWriter pw = new FastPrintWriter(out); 4997 SimpleDateFormat formatter = new SimpleDateFormat(); 4998 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4999 pw.println(dateString + ": " + msg); 5000 pw.close(); 5001 FileUtils.setPermissions( 5002 fname.toString(), 5003 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5004 -1, -1); 5005 } catch (java.io.IOException e) { 5006 } 5007 } 5008 5009 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5010 PackageParser.Package pkg, File srcFile, int parseFlags) 5011 throws PackageManagerException { 5012 if (ps != null 5013 && ps.codePath.equals(srcFile) 5014 && ps.timeStamp == srcFile.lastModified() 5015 && !isCompatSignatureUpdateNeeded(pkg) 5016 && !isRecoverSignatureUpdateNeeded(pkg)) { 5017 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5018 if (ps.signatures.mSignatures != null 5019 && ps.signatures.mSignatures.length != 0 5020 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5021 // Optimization: reuse the existing cached certificates 5022 // if the package appears to be unchanged. 5023 pkg.mSignatures = ps.signatures.mSignatures; 5024 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5025 synchronized (mPackages) { 5026 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5027 } 5028 return; 5029 } 5030 5031 Slog.w(TAG, "PackageSetting for " + ps.name 5032 + " is missing signatures. Collecting certs again to recover them."); 5033 } else { 5034 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5035 } 5036 5037 try { 5038 pp.collectCertificates(pkg, parseFlags); 5039 pp.collectManifestDigest(pkg); 5040 } catch (PackageParserException e) { 5041 throw PackageManagerException.from(e); 5042 } 5043 } 5044 5045 /* 5046 * Scan a package and return the newly parsed package. 5047 * Returns null in case of errors and the error code is stored in mLastScanError 5048 */ 5049 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5050 long currentTime, UserHandle user) throws PackageManagerException { 5051 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5052 parseFlags |= mDefParseFlags; 5053 PackageParser pp = new PackageParser(); 5054 pp.setSeparateProcesses(mSeparateProcesses); 5055 pp.setOnlyCoreApps(mOnlyCore); 5056 pp.setDisplayMetrics(mMetrics); 5057 5058 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5059 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5060 } 5061 5062 final PackageParser.Package pkg; 5063 try { 5064 pkg = pp.parsePackage(scanFile, parseFlags); 5065 } catch (PackageParserException e) { 5066 throw PackageManagerException.from(e); 5067 } 5068 5069 PackageSetting ps = null; 5070 PackageSetting updatedPkg; 5071 // reader 5072 synchronized (mPackages) { 5073 // Look to see if we already know about this package. 5074 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5075 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5076 // This package has been renamed to its original name. Let's 5077 // use that. 5078 ps = mSettings.peekPackageLPr(oldName); 5079 } 5080 // If there was no original package, see one for the real package name. 5081 if (ps == null) { 5082 ps = mSettings.peekPackageLPr(pkg.packageName); 5083 } 5084 // Check to see if this package could be hiding/updating a system 5085 // package. Must look for it either under the original or real 5086 // package name depending on our state. 5087 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5088 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5089 } 5090 boolean updatedPkgBetter = false; 5091 // First check if this is a system package that may involve an update 5092 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5093 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5094 // it needs to drop FLAG_PRIVILEGED. 5095 if (locationIsPrivileged(scanFile)) { 5096 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5097 } else { 5098 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5099 } 5100 5101 if (ps != null && !ps.codePath.equals(scanFile)) { 5102 // The path has changed from what was last scanned... check the 5103 // version of the new path against what we have stored to determine 5104 // what to do. 5105 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5106 if (pkg.mVersionCode <= ps.versionCode) { 5107 // The system package has been updated and the code path does not match 5108 // Ignore entry. Skip it. 5109 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5110 + " ignored: updated version " + ps.versionCode 5111 + " better than this " + pkg.mVersionCode); 5112 if (!updatedPkg.codePath.equals(scanFile)) { 5113 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5114 + ps.name + " changing from " + updatedPkg.codePathString 5115 + " to " + scanFile); 5116 updatedPkg.codePath = scanFile; 5117 updatedPkg.codePathString = scanFile.toString(); 5118 updatedPkg.resourcePath = scanFile; 5119 updatedPkg.resourcePathString = scanFile.toString(); 5120 } 5121 updatedPkg.pkg = pkg; 5122 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5123 } else { 5124 // The current app on the system partition is better than 5125 // what we have updated to on the data partition; switch 5126 // back to the system partition version. 5127 // At this point, its safely assumed that package installation for 5128 // apps in system partition will go through. If not there won't be a working 5129 // version of the app 5130 // writer 5131 synchronized (mPackages) { 5132 // Just remove the loaded entries from package lists. 5133 mPackages.remove(ps.name); 5134 } 5135 5136 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5137 + " reverting from " + ps.codePathString 5138 + ": new version " + pkg.mVersionCode 5139 + " better than installed " + ps.versionCode); 5140 5141 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5142 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5143 synchronized (mInstallLock) { 5144 args.cleanUpResourcesLI(); 5145 } 5146 synchronized (mPackages) { 5147 mSettings.enableSystemPackageLPw(ps.name); 5148 } 5149 updatedPkgBetter = true; 5150 } 5151 } 5152 } 5153 5154 if (updatedPkg != null) { 5155 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5156 // initially 5157 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5158 5159 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5160 // flag set initially 5161 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5162 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5163 } 5164 } 5165 5166 // Verify certificates against what was last scanned 5167 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5168 5169 /* 5170 * A new system app appeared, but we already had a non-system one of the 5171 * same name installed earlier. 5172 */ 5173 boolean shouldHideSystemApp = false; 5174 if (updatedPkg == null && ps != null 5175 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5176 /* 5177 * Check to make sure the signatures match first. If they don't, 5178 * wipe the installed application and its data. 5179 */ 5180 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5181 != PackageManager.SIGNATURE_MATCH) { 5182 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5183 + " signatures don't match existing userdata copy; removing"); 5184 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5185 ps = null; 5186 } else { 5187 /* 5188 * If the newly-added system app is an older version than the 5189 * already installed version, hide it. It will be scanned later 5190 * and re-added like an update. 5191 */ 5192 if (pkg.mVersionCode <= ps.versionCode) { 5193 shouldHideSystemApp = true; 5194 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5195 + " but new version " + pkg.mVersionCode + " better than installed " 5196 + ps.versionCode + "; hiding system"); 5197 } else { 5198 /* 5199 * The newly found system app is a newer version that the 5200 * one previously installed. Simply remove the 5201 * already-installed application and replace it with our own 5202 * while keeping the application data. 5203 */ 5204 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5205 + " reverting from " + ps.codePathString + ": new version " 5206 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5207 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5208 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5209 synchronized (mInstallLock) { 5210 args.cleanUpResourcesLI(); 5211 } 5212 } 5213 } 5214 } 5215 5216 // The apk is forward locked (not public) if its code and resources 5217 // are kept in different files. (except for app in either system or 5218 // vendor path). 5219 // TODO grab this value from PackageSettings 5220 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5221 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5222 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5223 } 5224 } 5225 5226 // TODO: extend to support forward-locked splits 5227 String resourcePath = null; 5228 String baseResourcePath = null; 5229 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5230 if (ps != null && ps.resourcePathString != null) { 5231 resourcePath = ps.resourcePathString; 5232 baseResourcePath = ps.resourcePathString; 5233 } else { 5234 // Should not happen at all. Just log an error. 5235 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5236 } 5237 } else { 5238 resourcePath = pkg.codePath; 5239 baseResourcePath = pkg.baseCodePath; 5240 } 5241 5242 // Set application objects path explicitly. 5243 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5244 pkg.applicationInfo.setCodePath(pkg.codePath); 5245 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5246 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5247 pkg.applicationInfo.setResourcePath(resourcePath); 5248 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5249 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5250 5251 // Note that we invoke the following method only if we are about to unpack an application 5252 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5253 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5254 5255 /* 5256 * If the system app should be overridden by a previously installed 5257 * data, hide the system app now and let the /data/app scan pick it up 5258 * again. 5259 */ 5260 if (shouldHideSystemApp) { 5261 synchronized (mPackages) { 5262 /* 5263 * We have to grant systems permissions before we hide, because 5264 * grantPermissions will assume the package update is trying to 5265 * expand its permissions. 5266 */ 5267 grantPermissionsLPw(pkg, true, pkg.packageName); 5268 mSettings.disableSystemPackageLPw(pkg.packageName); 5269 } 5270 } 5271 5272 return scannedPkg; 5273 } 5274 5275 private static String fixProcessName(String defProcessName, 5276 String processName, int uid) { 5277 if (processName == null) { 5278 return defProcessName; 5279 } 5280 return processName; 5281 } 5282 5283 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5284 throws PackageManagerException { 5285 if (pkgSetting.signatures.mSignatures != null) { 5286 // Already existing package. Make sure signatures match 5287 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5288 == PackageManager.SIGNATURE_MATCH; 5289 if (!match) { 5290 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5291 == PackageManager.SIGNATURE_MATCH; 5292 } 5293 if (!match) { 5294 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5295 == PackageManager.SIGNATURE_MATCH; 5296 } 5297 if (!match) { 5298 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5299 + pkg.packageName + " signatures do not match the " 5300 + "previously installed version; ignoring!"); 5301 } 5302 } 5303 5304 // Check for shared user signatures 5305 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5306 // Already existing package. Make sure signatures match 5307 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5308 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5309 if (!match) { 5310 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5311 == PackageManager.SIGNATURE_MATCH; 5312 } 5313 if (!match) { 5314 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5315 == PackageManager.SIGNATURE_MATCH; 5316 } 5317 if (!match) { 5318 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5319 "Package " + pkg.packageName 5320 + " has no signatures that match those in shared user " 5321 + pkgSetting.sharedUser.name + "; ignoring!"); 5322 } 5323 } 5324 } 5325 5326 /** 5327 * Enforces that only the system UID or root's UID can call a method exposed 5328 * via Binder. 5329 * 5330 * @param message used as message if SecurityException is thrown 5331 * @throws SecurityException if the caller is not system or root 5332 */ 5333 private static final void enforceSystemOrRoot(String message) { 5334 final int uid = Binder.getCallingUid(); 5335 if (uid != Process.SYSTEM_UID && uid != 0) { 5336 throw new SecurityException(message); 5337 } 5338 } 5339 5340 @Override 5341 public void performBootDexOpt() { 5342 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5343 5344 // Before everything else, see whether we need to fstrim. 5345 try { 5346 IMountService ms = PackageHelper.getMountService(); 5347 if (ms != null) { 5348 final boolean isUpgrade = isUpgrade(); 5349 boolean doTrim = isUpgrade; 5350 if (doTrim) { 5351 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5352 } else { 5353 final long interval = android.provider.Settings.Global.getLong( 5354 mContext.getContentResolver(), 5355 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5356 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5357 if (interval > 0) { 5358 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5359 if (timeSinceLast > interval) { 5360 doTrim = true; 5361 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5362 + "; running immediately"); 5363 } 5364 } 5365 } 5366 if (doTrim) { 5367 if (!isFirstBoot()) { 5368 try { 5369 ActivityManagerNative.getDefault().showBootMessage( 5370 mContext.getResources().getString( 5371 R.string.android_upgrading_fstrim), true); 5372 } catch (RemoteException e) { 5373 } 5374 } 5375 ms.runMaintenance(); 5376 } 5377 } else { 5378 Slog.e(TAG, "Mount service unavailable!"); 5379 } 5380 } catch (RemoteException e) { 5381 // Can't happen; MountService is local 5382 } 5383 5384 final ArraySet<PackageParser.Package> pkgs; 5385 synchronized (mPackages) { 5386 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5387 } 5388 5389 if (pkgs != null) { 5390 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5391 // in case the device runs out of space. 5392 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5393 // Give priority to core apps. 5394 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5395 PackageParser.Package pkg = it.next(); 5396 if (pkg.coreApp) { 5397 if (DEBUG_DEXOPT) { 5398 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5399 } 5400 sortedPkgs.add(pkg); 5401 it.remove(); 5402 } 5403 } 5404 // Give priority to system apps that listen for pre boot complete. 5405 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5406 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5407 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5408 PackageParser.Package pkg = it.next(); 5409 if (pkgNames.contains(pkg.packageName)) { 5410 if (DEBUG_DEXOPT) { 5411 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5412 } 5413 sortedPkgs.add(pkg); 5414 it.remove(); 5415 } 5416 } 5417 // Give priority to system apps. 5418 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5419 PackageParser.Package pkg = it.next(); 5420 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5421 if (DEBUG_DEXOPT) { 5422 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5423 } 5424 sortedPkgs.add(pkg); 5425 it.remove(); 5426 } 5427 } 5428 // Give priority to updated system apps. 5429 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5430 PackageParser.Package pkg = it.next(); 5431 if (pkg.isUpdatedSystemApp()) { 5432 if (DEBUG_DEXOPT) { 5433 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5434 } 5435 sortedPkgs.add(pkg); 5436 it.remove(); 5437 } 5438 } 5439 // Give priority to apps that listen for boot complete. 5440 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5441 pkgNames = getPackageNamesForIntent(intent); 5442 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5443 PackageParser.Package pkg = it.next(); 5444 if (pkgNames.contains(pkg.packageName)) { 5445 if (DEBUG_DEXOPT) { 5446 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5447 } 5448 sortedPkgs.add(pkg); 5449 it.remove(); 5450 } 5451 } 5452 // Filter out packages that aren't recently used. 5453 filterRecentlyUsedApps(pkgs); 5454 // Add all remaining apps. 5455 for (PackageParser.Package pkg : pkgs) { 5456 if (DEBUG_DEXOPT) { 5457 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5458 } 5459 sortedPkgs.add(pkg); 5460 } 5461 5462 // If we want to be lazy, filter everything that wasn't recently used. 5463 if (mLazyDexOpt) { 5464 filterRecentlyUsedApps(sortedPkgs); 5465 } 5466 5467 int i = 0; 5468 int total = sortedPkgs.size(); 5469 File dataDir = Environment.getDataDirectory(); 5470 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5471 if (lowThreshold == 0) { 5472 throw new IllegalStateException("Invalid low memory threshold"); 5473 } 5474 for (PackageParser.Package pkg : sortedPkgs) { 5475 long usableSpace = dataDir.getUsableSpace(); 5476 if (usableSpace < lowThreshold) { 5477 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5478 break; 5479 } 5480 performBootDexOpt(pkg, ++i, total); 5481 } 5482 } 5483 } 5484 5485 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5486 // Filter out packages that aren't recently used. 5487 // 5488 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5489 // should do a full dexopt. 5490 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5491 int total = pkgs.size(); 5492 int skipped = 0; 5493 long now = System.currentTimeMillis(); 5494 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5495 PackageParser.Package pkg = i.next(); 5496 long then = pkg.mLastPackageUsageTimeInMills; 5497 if (then + mDexOptLRUThresholdInMills < now) { 5498 if (DEBUG_DEXOPT) { 5499 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5500 ((then == 0) ? "never" : new Date(then))); 5501 } 5502 i.remove(); 5503 skipped++; 5504 } 5505 } 5506 if (DEBUG_DEXOPT) { 5507 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5508 } 5509 } 5510 } 5511 5512 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5513 List<ResolveInfo> ris = null; 5514 try { 5515 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5516 intent, null, 0, UserHandle.USER_OWNER); 5517 } catch (RemoteException e) { 5518 } 5519 ArraySet<String> pkgNames = new ArraySet<String>(); 5520 if (ris != null) { 5521 for (ResolveInfo ri : ris) { 5522 pkgNames.add(ri.activityInfo.packageName); 5523 } 5524 } 5525 return pkgNames; 5526 } 5527 5528 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5529 if (DEBUG_DEXOPT) { 5530 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5531 } 5532 if (!isFirstBoot()) { 5533 try { 5534 ActivityManagerNative.getDefault().showBootMessage( 5535 mContext.getResources().getString(R.string.android_upgrading_apk, 5536 curr, total), true); 5537 } catch (RemoteException e) { 5538 } 5539 } 5540 PackageParser.Package p = pkg; 5541 synchronized (mInstallLock) { 5542 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5543 false /* force dex */, false /* defer */, true /* include dependencies */); 5544 } 5545 } 5546 5547 @Override 5548 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5549 return performDexOpt(packageName, instructionSet, false); 5550 } 5551 5552 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5553 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5554 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5555 if (!dexopt && !updateUsage) { 5556 // We aren't going to dexopt or update usage, so bail early. 5557 return false; 5558 } 5559 PackageParser.Package p; 5560 final String targetInstructionSet; 5561 synchronized (mPackages) { 5562 p = mPackages.get(packageName); 5563 if (p == null) { 5564 return false; 5565 } 5566 if (updateUsage) { 5567 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5568 } 5569 mPackageUsage.write(false); 5570 if (!dexopt) { 5571 // We aren't going to dexopt, so bail early. 5572 return false; 5573 } 5574 5575 targetInstructionSet = instructionSet != null ? instructionSet : 5576 getPrimaryInstructionSet(p.applicationInfo); 5577 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5578 return false; 5579 } 5580 } 5581 5582 synchronized (mInstallLock) { 5583 final String[] instructionSets = new String[] { targetInstructionSet }; 5584 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5585 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5586 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5587 } 5588 } 5589 5590 public ArraySet<String> getPackagesThatNeedDexOpt() { 5591 ArraySet<String> pkgs = null; 5592 synchronized (mPackages) { 5593 for (PackageParser.Package p : mPackages.values()) { 5594 if (DEBUG_DEXOPT) { 5595 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5596 } 5597 if (!p.mDexOptPerformed.isEmpty()) { 5598 continue; 5599 } 5600 if (pkgs == null) { 5601 pkgs = new ArraySet<String>(); 5602 } 5603 pkgs.add(p.packageName); 5604 } 5605 } 5606 return pkgs; 5607 } 5608 5609 public void shutdown() { 5610 mPackageUsage.write(true); 5611 } 5612 5613 @Override 5614 public void forceDexOpt(String packageName) { 5615 enforceSystemOrRoot("forceDexOpt"); 5616 5617 PackageParser.Package pkg; 5618 synchronized (mPackages) { 5619 pkg = mPackages.get(packageName); 5620 if (pkg == null) { 5621 throw new IllegalArgumentException("Missing package: " + packageName); 5622 } 5623 } 5624 5625 synchronized (mInstallLock) { 5626 final String[] instructionSets = new String[] { 5627 getPrimaryInstructionSet(pkg.applicationInfo) }; 5628 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5629 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5630 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5631 throw new IllegalStateException("Failed to dexopt: " + res); 5632 } 5633 } 5634 } 5635 5636 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5637 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5638 Slog.w(TAG, "Unable to update from " + oldPkg.name 5639 + " to " + newPkg.packageName 5640 + ": old package not in system partition"); 5641 return false; 5642 } else if (mPackages.get(oldPkg.name) != null) { 5643 Slog.w(TAG, "Unable to update from " + oldPkg.name 5644 + " to " + newPkg.packageName 5645 + ": old package still exists"); 5646 return false; 5647 } 5648 return true; 5649 } 5650 5651 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5652 int[] users = sUserManager.getUserIds(); 5653 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5654 if (res < 0) { 5655 return res; 5656 } 5657 for (int user : users) { 5658 if (user != 0) { 5659 res = mInstaller.createUserData(volumeUuid, packageName, 5660 UserHandle.getUid(user, uid), user, seinfo); 5661 if (res < 0) { 5662 return res; 5663 } 5664 } 5665 } 5666 return res; 5667 } 5668 5669 private int removeDataDirsLI(String volumeUuid, String packageName) { 5670 int[] users = sUserManager.getUserIds(); 5671 int res = 0; 5672 for (int user : users) { 5673 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5674 if (resInner < 0) { 5675 res = resInner; 5676 } 5677 } 5678 5679 return res; 5680 } 5681 5682 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5683 int[] users = sUserManager.getUserIds(); 5684 int res = 0; 5685 for (int user : users) { 5686 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5687 if (resInner < 0) { 5688 res = resInner; 5689 } 5690 } 5691 return res; 5692 } 5693 5694 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5695 PackageParser.Package changingLib) { 5696 if (file.path != null) { 5697 usesLibraryFiles.add(file.path); 5698 return; 5699 } 5700 PackageParser.Package p = mPackages.get(file.apk); 5701 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5702 // If we are doing this while in the middle of updating a library apk, 5703 // then we need to make sure to use that new apk for determining the 5704 // dependencies here. (We haven't yet finished committing the new apk 5705 // to the package manager state.) 5706 if (p == null || p.packageName.equals(changingLib.packageName)) { 5707 p = changingLib; 5708 } 5709 } 5710 if (p != null) { 5711 usesLibraryFiles.addAll(p.getAllCodePaths()); 5712 } 5713 } 5714 5715 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5716 PackageParser.Package changingLib) throws PackageManagerException { 5717 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5718 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5719 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5720 for (int i=0; i<N; i++) { 5721 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5722 if (file == null) { 5723 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5724 "Package " + pkg.packageName + " requires unavailable shared library " 5725 + pkg.usesLibraries.get(i) + "; failing!"); 5726 } 5727 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5728 } 5729 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5730 for (int i=0; i<N; i++) { 5731 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5732 if (file == null) { 5733 Slog.w(TAG, "Package " + pkg.packageName 5734 + " desires unavailable shared library " 5735 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5736 } else { 5737 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5738 } 5739 } 5740 N = usesLibraryFiles.size(); 5741 if (N > 0) { 5742 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5743 } else { 5744 pkg.usesLibraryFiles = null; 5745 } 5746 } 5747 } 5748 5749 private static boolean hasString(List<String> list, List<String> which) { 5750 if (list == null) { 5751 return false; 5752 } 5753 for (int i=list.size()-1; i>=0; i--) { 5754 for (int j=which.size()-1; j>=0; j--) { 5755 if (which.get(j).equals(list.get(i))) { 5756 return true; 5757 } 5758 } 5759 } 5760 return false; 5761 } 5762 5763 private void updateAllSharedLibrariesLPw() { 5764 for (PackageParser.Package pkg : mPackages.values()) { 5765 try { 5766 updateSharedLibrariesLPw(pkg, null); 5767 } catch (PackageManagerException e) { 5768 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5769 } 5770 } 5771 } 5772 5773 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5774 PackageParser.Package changingPkg) { 5775 ArrayList<PackageParser.Package> res = null; 5776 for (PackageParser.Package pkg : mPackages.values()) { 5777 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5778 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5779 if (res == null) { 5780 res = new ArrayList<PackageParser.Package>(); 5781 } 5782 res.add(pkg); 5783 try { 5784 updateSharedLibrariesLPw(pkg, changingPkg); 5785 } catch (PackageManagerException e) { 5786 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5787 } 5788 } 5789 } 5790 return res; 5791 } 5792 5793 /** 5794 * Derive the value of the {@code cpuAbiOverride} based on the provided 5795 * value and an optional stored value from the package settings. 5796 */ 5797 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5798 String cpuAbiOverride = null; 5799 5800 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5801 cpuAbiOverride = null; 5802 } else if (abiOverride != null) { 5803 cpuAbiOverride = abiOverride; 5804 } else if (settings != null) { 5805 cpuAbiOverride = settings.cpuAbiOverrideString; 5806 } 5807 5808 return cpuAbiOverride; 5809 } 5810 5811 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5812 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5813 boolean success = false; 5814 try { 5815 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5816 currentTime, user); 5817 success = true; 5818 return res; 5819 } finally { 5820 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5821 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5822 } 5823 } 5824 } 5825 5826 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5827 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5828 final File scanFile = new File(pkg.codePath); 5829 if (pkg.applicationInfo.getCodePath() == null || 5830 pkg.applicationInfo.getResourcePath() == null) { 5831 // Bail out. The resource and code paths haven't been set. 5832 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5833 "Code and resource paths haven't been set correctly"); 5834 } 5835 5836 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5837 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5838 } else { 5839 // Only allow system apps to be flagged as core apps. 5840 pkg.coreApp = false; 5841 } 5842 5843 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5844 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5845 } 5846 5847 if (mCustomResolverComponentName != null && 5848 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5849 setUpCustomResolverActivity(pkg); 5850 } 5851 5852 if (pkg.packageName.equals("android")) { 5853 synchronized (mPackages) { 5854 if (mAndroidApplication != null) { 5855 Slog.w(TAG, "*************************************************"); 5856 Slog.w(TAG, "Core android package being redefined. Skipping."); 5857 Slog.w(TAG, " file=" + scanFile); 5858 Slog.w(TAG, "*************************************************"); 5859 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5860 "Core android package being redefined. Skipping."); 5861 } 5862 5863 // Set up information for our fall-back user intent resolution activity. 5864 mPlatformPackage = pkg; 5865 pkg.mVersionCode = mSdkVersion; 5866 mAndroidApplication = pkg.applicationInfo; 5867 5868 if (!mResolverReplaced) { 5869 mResolveActivity.applicationInfo = mAndroidApplication; 5870 mResolveActivity.name = ResolverActivity.class.getName(); 5871 mResolveActivity.packageName = mAndroidApplication.packageName; 5872 mResolveActivity.processName = "system:ui"; 5873 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5874 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5875 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5876 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5877 mResolveActivity.exported = true; 5878 mResolveActivity.enabled = true; 5879 mResolveInfo.activityInfo = mResolveActivity; 5880 mResolveInfo.priority = 0; 5881 mResolveInfo.preferredOrder = 0; 5882 mResolveInfo.match = 0; 5883 mResolveComponentName = new ComponentName( 5884 mAndroidApplication.packageName, mResolveActivity.name); 5885 } 5886 } 5887 } 5888 5889 if (DEBUG_PACKAGE_SCANNING) { 5890 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5891 Log.d(TAG, "Scanning package " + pkg.packageName); 5892 } 5893 5894 if (mPackages.containsKey(pkg.packageName) 5895 || mSharedLibraries.containsKey(pkg.packageName)) { 5896 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5897 "Application package " + pkg.packageName 5898 + " already installed. Skipping duplicate."); 5899 } 5900 5901 // If we're only installing presumed-existing packages, require that the 5902 // scanned APK is both already known and at the path previously established 5903 // for it. Previously unknown packages we pick up normally, but if we have an 5904 // a priori expectation about this package's install presence, enforce it. 5905 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5906 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5907 if (known != null) { 5908 if (DEBUG_PACKAGE_SCANNING) { 5909 Log.d(TAG, "Examining " + pkg.codePath 5910 + " and requiring known paths " + known.codePathString 5911 + " & " + known.resourcePathString); 5912 } 5913 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5914 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5915 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5916 "Application package " + pkg.packageName 5917 + " found at " + pkg.applicationInfo.getCodePath() 5918 + " but expected at " + known.codePathString + "; ignoring."); 5919 } 5920 } 5921 } 5922 5923 // Initialize package source and resource directories 5924 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5925 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5926 5927 SharedUserSetting suid = null; 5928 PackageSetting pkgSetting = null; 5929 5930 if (!isSystemApp(pkg)) { 5931 // Only system apps can use these features. 5932 pkg.mOriginalPackages = null; 5933 pkg.mRealPackage = null; 5934 pkg.mAdoptPermissions = null; 5935 } 5936 5937 // writer 5938 synchronized (mPackages) { 5939 if (pkg.mSharedUserId != null) { 5940 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5941 if (suid == null) { 5942 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5943 "Creating application package " + pkg.packageName 5944 + " for shared user failed"); 5945 } 5946 if (DEBUG_PACKAGE_SCANNING) { 5947 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5948 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5949 + "): packages=" + suid.packages); 5950 } 5951 } 5952 5953 // Check if we are renaming from an original package name. 5954 PackageSetting origPackage = null; 5955 String realName = null; 5956 if (pkg.mOriginalPackages != null) { 5957 // This package may need to be renamed to a previously 5958 // installed name. Let's check on that... 5959 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5960 if (pkg.mOriginalPackages.contains(renamed)) { 5961 // This package had originally been installed as the 5962 // original name, and we have already taken care of 5963 // transitioning to the new one. Just update the new 5964 // one to continue using the old name. 5965 realName = pkg.mRealPackage; 5966 if (!pkg.packageName.equals(renamed)) { 5967 // Callers into this function may have already taken 5968 // care of renaming the package; only do it here if 5969 // it is not already done. 5970 pkg.setPackageName(renamed); 5971 } 5972 5973 } else { 5974 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5975 if ((origPackage = mSettings.peekPackageLPr( 5976 pkg.mOriginalPackages.get(i))) != null) { 5977 // We do have the package already installed under its 5978 // original name... should we use it? 5979 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5980 // New package is not compatible with original. 5981 origPackage = null; 5982 continue; 5983 } else if (origPackage.sharedUser != null) { 5984 // Make sure uid is compatible between packages. 5985 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5986 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5987 + " to " + pkg.packageName + ": old uid " 5988 + origPackage.sharedUser.name 5989 + " differs from " + pkg.mSharedUserId); 5990 origPackage = null; 5991 continue; 5992 } 5993 } else { 5994 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5995 + pkg.packageName + " to old name " + origPackage.name); 5996 } 5997 break; 5998 } 5999 } 6000 } 6001 } 6002 6003 if (mTransferedPackages.contains(pkg.packageName)) { 6004 Slog.w(TAG, "Package " + pkg.packageName 6005 + " was transferred to another, but its .apk remains"); 6006 } 6007 6008 // Just create the setting, don't add it yet. For already existing packages 6009 // the PkgSetting exists already and doesn't have to be created. 6010 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6011 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6012 pkg.applicationInfo.primaryCpuAbi, 6013 pkg.applicationInfo.secondaryCpuAbi, 6014 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6015 user, false); 6016 if (pkgSetting == null) { 6017 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6018 "Creating application package " + pkg.packageName + " failed"); 6019 } 6020 6021 if (pkgSetting.origPackage != null) { 6022 // If we are first transitioning from an original package, 6023 // fix up the new package's name now. We need to do this after 6024 // looking up the package under its new name, so getPackageLP 6025 // can take care of fiddling things correctly. 6026 pkg.setPackageName(origPackage.name); 6027 6028 // File a report about this. 6029 String msg = "New package " + pkgSetting.realName 6030 + " renamed to replace old package " + pkgSetting.name; 6031 reportSettingsProblem(Log.WARN, msg); 6032 6033 // Make a note of it. 6034 mTransferedPackages.add(origPackage.name); 6035 6036 // No longer need to retain this. 6037 pkgSetting.origPackage = null; 6038 } 6039 6040 if (realName != null) { 6041 // Make a note of it. 6042 mTransferedPackages.add(pkg.packageName); 6043 } 6044 6045 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6047 } 6048 6049 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6050 // Check all shared libraries and map to their actual file path. 6051 // We only do this here for apps not on a system dir, because those 6052 // are the only ones that can fail an install due to this. We 6053 // will take care of the system apps by updating all of their 6054 // library paths after the scan is done. 6055 updateSharedLibrariesLPw(pkg, null); 6056 } 6057 6058 if (mFoundPolicyFile) { 6059 SELinuxMMAC.assignSeinfoValue(pkg); 6060 } 6061 6062 pkg.applicationInfo.uid = pkgSetting.appId; 6063 pkg.mExtras = pkgSetting; 6064 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 6065 try { 6066 verifySignaturesLP(pkgSetting, pkg); 6067 // We just determined the app is signed correctly, so bring 6068 // over the latest parsed certs. 6069 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6070 } catch (PackageManagerException e) { 6071 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6072 throw e; 6073 } 6074 // The signature has changed, but this package is in the system 6075 // image... let's recover! 6076 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6077 // However... if this package is part of a shared user, but it 6078 // doesn't match the signature of the shared user, let's fail. 6079 // What this means is that you can't change the signatures 6080 // associated with an overall shared user, which doesn't seem all 6081 // that unreasonable. 6082 if (pkgSetting.sharedUser != null) { 6083 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6084 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6085 throw new PackageManagerException( 6086 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6087 "Signature mismatch for shared user : " 6088 + pkgSetting.sharedUser); 6089 } 6090 } 6091 // File a report about this. 6092 String msg = "System package " + pkg.packageName 6093 + " signature changed; retaining data."; 6094 reportSettingsProblem(Log.WARN, msg); 6095 } 6096 } else { 6097 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6098 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6099 + pkg.packageName + " upgrade keys do not match the " 6100 + "previously installed version"); 6101 } else { 6102 // We just determined the app is signed correctly, so bring 6103 // over the latest parsed certs. 6104 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6105 } 6106 } 6107 // Verify that this new package doesn't have any content providers 6108 // that conflict with existing packages. Only do this if the 6109 // package isn't already installed, since we don't want to break 6110 // things that are installed. 6111 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6112 final int N = pkg.providers.size(); 6113 int i; 6114 for (i=0; i<N; i++) { 6115 PackageParser.Provider p = pkg.providers.get(i); 6116 if (p.info.authority != null) { 6117 String names[] = p.info.authority.split(";"); 6118 for (int j = 0; j < names.length; j++) { 6119 if (mProvidersByAuthority.containsKey(names[j])) { 6120 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6121 final String otherPackageName = 6122 ((other != null && other.getComponentName() != null) ? 6123 other.getComponentName().getPackageName() : "?"); 6124 throw new PackageManagerException( 6125 INSTALL_FAILED_CONFLICTING_PROVIDER, 6126 "Can't install because provider name " + names[j] 6127 + " (in package " + pkg.applicationInfo.packageName 6128 + ") is already used by " + otherPackageName); 6129 } 6130 } 6131 } 6132 } 6133 } 6134 6135 if (pkg.mAdoptPermissions != null) { 6136 // This package wants to adopt ownership of permissions from 6137 // another package. 6138 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6139 final String origName = pkg.mAdoptPermissions.get(i); 6140 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6141 if (orig != null) { 6142 if (verifyPackageUpdateLPr(orig, pkg)) { 6143 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6144 + pkg.packageName); 6145 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6146 } 6147 } 6148 } 6149 } 6150 } 6151 6152 final String pkgName = pkg.packageName; 6153 6154 final long scanFileTime = scanFile.lastModified(); 6155 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6156 pkg.applicationInfo.processName = fixProcessName( 6157 pkg.applicationInfo.packageName, 6158 pkg.applicationInfo.processName, 6159 pkg.applicationInfo.uid); 6160 6161 File dataPath; 6162 if (mPlatformPackage == pkg) { 6163 // The system package is special. 6164 dataPath = new File(Environment.getDataDirectory(), "system"); 6165 6166 pkg.applicationInfo.dataDir = dataPath.getPath(); 6167 6168 } else { 6169 // This is a normal package, need to make its data directory. 6170 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6171 UserHandle.USER_OWNER); 6172 6173 boolean uidError = false; 6174 if (dataPath.exists()) { 6175 int currentUid = 0; 6176 try { 6177 StructStat stat = Os.stat(dataPath.getPath()); 6178 currentUid = stat.st_uid; 6179 } catch (ErrnoException e) { 6180 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6181 } 6182 6183 // If we have mismatched owners for the data path, we have a problem. 6184 if (currentUid != pkg.applicationInfo.uid) { 6185 boolean recovered = false; 6186 if (currentUid == 0) { 6187 // The directory somehow became owned by root. Wow. 6188 // This is probably because the system was stopped while 6189 // installd was in the middle of messing with its libs 6190 // directory. Ask installd to fix that. 6191 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6192 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6193 if (ret >= 0) { 6194 recovered = true; 6195 String msg = "Package " + pkg.packageName 6196 + " unexpectedly changed to uid 0; recovered to " + 6197 + pkg.applicationInfo.uid; 6198 reportSettingsProblem(Log.WARN, msg); 6199 } 6200 } 6201 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6202 || (scanFlags&SCAN_BOOTING) != 0)) { 6203 // If this is a system app, we can at least delete its 6204 // current data so the application will still work. 6205 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6206 if (ret >= 0) { 6207 // TODO: Kill the processes first 6208 // Old data gone! 6209 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6210 ? "System package " : "Third party package "; 6211 String msg = prefix + pkg.packageName 6212 + " has changed from uid: " 6213 + currentUid + " to " 6214 + pkg.applicationInfo.uid + "; old data erased"; 6215 reportSettingsProblem(Log.WARN, msg); 6216 recovered = true; 6217 6218 // And now re-install the app. 6219 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6220 pkg.applicationInfo.seinfo); 6221 if (ret == -1) { 6222 // Ack should not happen! 6223 msg = prefix + pkg.packageName 6224 + " could not have data directory re-created after delete."; 6225 reportSettingsProblem(Log.WARN, msg); 6226 throw new PackageManagerException( 6227 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6228 } 6229 } 6230 if (!recovered) { 6231 mHasSystemUidErrors = true; 6232 } 6233 } else if (!recovered) { 6234 // If we allow this install to proceed, we will be broken. 6235 // Abort, abort! 6236 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6237 "scanPackageLI"); 6238 } 6239 if (!recovered) { 6240 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6241 + pkg.applicationInfo.uid + "/fs_" 6242 + currentUid; 6243 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6244 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6245 String msg = "Package " + pkg.packageName 6246 + " has mismatched uid: " 6247 + currentUid + " on disk, " 6248 + pkg.applicationInfo.uid + " in settings"; 6249 // writer 6250 synchronized (mPackages) { 6251 mSettings.mReadMessages.append(msg); 6252 mSettings.mReadMessages.append('\n'); 6253 uidError = true; 6254 if (!pkgSetting.uidError) { 6255 reportSettingsProblem(Log.ERROR, msg); 6256 } 6257 } 6258 } 6259 } 6260 pkg.applicationInfo.dataDir = dataPath.getPath(); 6261 if (mShouldRestoreconData) { 6262 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6263 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6264 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6265 } 6266 } else { 6267 if (DEBUG_PACKAGE_SCANNING) { 6268 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6269 Log.v(TAG, "Want this data dir: " + dataPath); 6270 } 6271 //invoke installer to do the actual installation 6272 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6273 pkg.applicationInfo.seinfo); 6274 if (ret < 0) { 6275 // Error from installer 6276 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6277 "Unable to create data dirs [errorCode=" + ret + "]"); 6278 } 6279 6280 if (dataPath.exists()) { 6281 pkg.applicationInfo.dataDir = dataPath.getPath(); 6282 } else { 6283 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6284 pkg.applicationInfo.dataDir = null; 6285 } 6286 } 6287 6288 pkgSetting.uidError = uidError; 6289 } 6290 6291 final String path = scanFile.getPath(); 6292 final String codePath = pkg.applicationInfo.getCodePath(); 6293 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6294 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6295 setBundledAppAbisAndRoots(pkg, pkgSetting); 6296 6297 // If we haven't found any native libraries for the app, check if it has 6298 // renderscript code. We'll need to force the app to 32 bit if it has 6299 // renderscript bitcode. 6300 if (pkg.applicationInfo.primaryCpuAbi == null 6301 && pkg.applicationInfo.secondaryCpuAbi == null 6302 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6303 NativeLibraryHelper.Handle handle = null; 6304 try { 6305 handle = NativeLibraryHelper.Handle.create(scanFile); 6306 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6307 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6308 } 6309 } catch (IOException ioe) { 6310 Slog.w(TAG, "Error scanning system app : " + ioe); 6311 } finally { 6312 IoUtils.closeQuietly(handle); 6313 } 6314 } 6315 6316 setNativeLibraryPaths(pkg); 6317 } else { 6318 // TODO: We can probably be smarter about this stuff. For installed apps, 6319 // we can calculate this information at install time once and for all. For 6320 // system apps, we can probably assume that this information doesn't change 6321 // after the first boot scan. As things stand, we do lots of unnecessary work. 6322 6323 // Give ourselves some initial paths; we'll come back for another 6324 // pass once we've determined ABI below. 6325 setNativeLibraryPaths(pkg); 6326 6327 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6328 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6329 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6330 6331 NativeLibraryHelper.Handle handle = null; 6332 try { 6333 handle = NativeLibraryHelper.Handle.create(scanFile); 6334 // TODO(multiArch): This can be null for apps that didn't go through the 6335 // usual installation process. We can calculate it again, like we 6336 // do during install time. 6337 // 6338 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6339 // unnecessary. 6340 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6341 6342 // Null out the abis so that they can be recalculated. 6343 pkg.applicationInfo.primaryCpuAbi = null; 6344 pkg.applicationInfo.secondaryCpuAbi = null; 6345 if (isMultiArch(pkg.applicationInfo)) { 6346 // Warn if we've set an abiOverride for multi-lib packages.. 6347 // By definition, we need to copy both 32 and 64 bit libraries for 6348 // such packages. 6349 if (pkg.cpuAbiOverride != null 6350 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6351 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6352 } 6353 6354 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6355 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6356 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6357 if (isAsec) { 6358 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6359 } else { 6360 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6361 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6362 useIsaSpecificSubdirs); 6363 } 6364 } 6365 6366 maybeThrowExceptionForMultiArchCopy( 6367 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6368 6369 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6370 if (isAsec) { 6371 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6372 } else { 6373 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6374 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6375 useIsaSpecificSubdirs); 6376 } 6377 } 6378 6379 maybeThrowExceptionForMultiArchCopy( 6380 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6381 6382 if (abi64 >= 0) { 6383 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6384 } 6385 6386 if (abi32 >= 0) { 6387 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6388 if (abi64 >= 0) { 6389 pkg.applicationInfo.secondaryCpuAbi = abi; 6390 } else { 6391 pkg.applicationInfo.primaryCpuAbi = abi; 6392 } 6393 } 6394 } else { 6395 String[] abiList = (cpuAbiOverride != null) ? 6396 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6397 6398 // Enable gross and lame hacks for apps that are built with old 6399 // SDK tools. We must scan their APKs for renderscript bitcode and 6400 // not launch them if it's present. Don't bother checking on devices 6401 // that don't have 64 bit support. 6402 boolean needsRenderScriptOverride = false; 6403 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6404 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6405 abiList = Build.SUPPORTED_32_BIT_ABIS; 6406 needsRenderScriptOverride = true; 6407 } 6408 6409 final int copyRet; 6410 if (isAsec) { 6411 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6412 } else { 6413 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6414 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6415 } 6416 6417 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6418 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6419 "Error unpackaging native libs for app, errorCode=" + copyRet); 6420 } 6421 6422 if (copyRet >= 0) { 6423 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6424 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6425 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6426 } else if (needsRenderScriptOverride) { 6427 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6428 } 6429 } 6430 } catch (IOException ioe) { 6431 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6432 } finally { 6433 IoUtils.closeQuietly(handle); 6434 } 6435 6436 // Now that we've calculated the ABIs and determined if it's an internal app, 6437 // we will go ahead and populate the nativeLibraryPath. 6438 setNativeLibraryPaths(pkg); 6439 6440 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6441 final int[] userIds = sUserManager.getUserIds(); 6442 synchronized (mInstallLock) { 6443 // Create a native library symlink only if we have native libraries 6444 // and if the native libraries are 32 bit libraries. We do not provide 6445 // this symlink for 64 bit libraries. 6446 if (pkg.applicationInfo.primaryCpuAbi != null && 6447 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6448 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6449 for (int userId : userIds) { 6450 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6451 nativeLibPath, userId) < 0) { 6452 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6453 "Failed linking native library dir (user=" + userId + ")"); 6454 } 6455 } 6456 } 6457 } 6458 } 6459 6460 // This is a special case for the "system" package, where the ABI is 6461 // dictated by the zygote configuration (and init.rc). We should keep track 6462 // of this ABI so that we can deal with "normal" applications that run under 6463 // the same UID correctly. 6464 if (mPlatformPackage == pkg) { 6465 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6466 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6467 } 6468 6469 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6470 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6471 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6472 // Copy the derived override back to the parsed package, so that we can 6473 // update the package settings accordingly. 6474 pkg.cpuAbiOverride = cpuAbiOverride; 6475 6476 if (DEBUG_ABI_SELECTION) { 6477 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6478 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6479 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6480 } 6481 6482 // Push the derived path down into PackageSettings so we know what to 6483 // clean up at uninstall time. 6484 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6485 6486 if (DEBUG_ABI_SELECTION) { 6487 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6488 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6489 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6490 } 6491 6492 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6493 // We don't do this here during boot because we can do it all 6494 // at once after scanning all existing packages. 6495 // 6496 // We also do this *before* we perform dexopt on this package, so that 6497 // we can avoid redundant dexopts, and also to make sure we've got the 6498 // code and package path correct. 6499 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6500 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6501 } 6502 6503 if ((scanFlags & SCAN_NO_DEX) == 0) { 6504 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6505 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6506 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6507 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6508 } 6509 } 6510 if (mFactoryTest && pkg.requestedPermissions.contains( 6511 android.Manifest.permission.FACTORY_TEST)) { 6512 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6513 } 6514 6515 ArrayList<PackageParser.Package> clientLibPkgs = null; 6516 6517 // writer 6518 synchronized (mPackages) { 6519 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6520 // Only system apps can add new shared libraries. 6521 if (pkg.libraryNames != null) { 6522 for (int i=0; i<pkg.libraryNames.size(); i++) { 6523 String name = pkg.libraryNames.get(i); 6524 boolean allowed = false; 6525 if (pkg.isUpdatedSystemApp()) { 6526 // New library entries can only be added through the 6527 // system image. This is important to get rid of a lot 6528 // of nasty edge cases: for example if we allowed a non- 6529 // system update of the app to add a library, then uninstalling 6530 // the update would make the library go away, and assumptions 6531 // we made such as through app install filtering would now 6532 // have allowed apps on the device which aren't compatible 6533 // with it. Better to just have the restriction here, be 6534 // conservative, and create many fewer cases that can negatively 6535 // impact the user experience. 6536 final PackageSetting sysPs = mSettings 6537 .getDisabledSystemPkgLPr(pkg.packageName); 6538 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6539 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6540 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6541 allowed = true; 6542 allowed = true; 6543 break; 6544 } 6545 } 6546 } 6547 } else { 6548 allowed = true; 6549 } 6550 if (allowed) { 6551 if (!mSharedLibraries.containsKey(name)) { 6552 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6553 } else if (!name.equals(pkg.packageName)) { 6554 Slog.w(TAG, "Package " + pkg.packageName + " library " 6555 + name + " already exists; skipping"); 6556 } 6557 } else { 6558 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6559 + name + " that is not declared on system image; skipping"); 6560 } 6561 } 6562 if ((scanFlags&SCAN_BOOTING) == 0) { 6563 // If we are not booting, we need to update any applications 6564 // that are clients of our shared library. If we are booting, 6565 // this will all be done once the scan is complete. 6566 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6567 } 6568 } 6569 } 6570 } 6571 6572 // We also need to dexopt any apps that are dependent on this library. Note that 6573 // if these fail, we should abort the install since installing the library will 6574 // result in some apps being broken. 6575 if (clientLibPkgs != null) { 6576 if ((scanFlags & SCAN_NO_DEX) == 0) { 6577 for (int i = 0; i < clientLibPkgs.size(); i++) { 6578 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6579 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6580 null /* instruction sets */, forceDex, 6581 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6582 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6583 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6584 "scanPackageLI failed to dexopt clientLibPkgs"); 6585 } 6586 } 6587 } 6588 } 6589 6590 // Also need to kill any apps that are dependent on the library. 6591 if (clientLibPkgs != null) { 6592 for (int i=0; i<clientLibPkgs.size(); i++) { 6593 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6594 killApplication(clientPkg.applicationInfo.packageName, 6595 clientPkg.applicationInfo.uid, "update lib"); 6596 } 6597 } 6598 6599 // writer 6600 synchronized (mPackages) { 6601 // We don't expect installation to fail beyond this point 6602 6603 // Add the new setting to mSettings 6604 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6605 // Add the new setting to mPackages 6606 mPackages.put(pkg.applicationInfo.packageName, pkg); 6607 // Make sure we don't accidentally delete its data. 6608 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6609 while (iter.hasNext()) { 6610 PackageCleanItem item = iter.next(); 6611 if (pkgName.equals(item.packageName)) { 6612 iter.remove(); 6613 } 6614 } 6615 6616 // Take care of first install / last update times. 6617 if (currentTime != 0) { 6618 if (pkgSetting.firstInstallTime == 0) { 6619 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6620 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6621 pkgSetting.lastUpdateTime = currentTime; 6622 } 6623 } else if (pkgSetting.firstInstallTime == 0) { 6624 // We need *something*. Take time time stamp of the file. 6625 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6626 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6627 if (scanFileTime != pkgSetting.timeStamp) { 6628 // A package on the system image has changed; consider this 6629 // to be an update. 6630 pkgSetting.lastUpdateTime = scanFileTime; 6631 } 6632 } 6633 6634 // Add the package's KeySets to the global KeySetManagerService 6635 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6636 try { 6637 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6638 if (pkg.mKeySetMapping != null) { 6639 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6640 if (pkg.mUpgradeKeySets != null) { 6641 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6642 } 6643 } 6644 } catch (NullPointerException e) { 6645 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6646 } catch (IllegalArgumentException e) { 6647 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6648 } 6649 6650 int N = pkg.providers.size(); 6651 StringBuilder r = null; 6652 int i; 6653 for (i=0; i<N; i++) { 6654 PackageParser.Provider p = pkg.providers.get(i); 6655 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6656 p.info.processName, pkg.applicationInfo.uid); 6657 mProviders.addProvider(p); 6658 p.syncable = p.info.isSyncable; 6659 if (p.info.authority != null) { 6660 String names[] = p.info.authority.split(";"); 6661 p.info.authority = null; 6662 for (int j = 0; j < names.length; j++) { 6663 if (j == 1 && p.syncable) { 6664 // We only want the first authority for a provider to possibly be 6665 // syncable, so if we already added this provider using a different 6666 // authority clear the syncable flag. We copy the provider before 6667 // changing it because the mProviders object contains a reference 6668 // to a provider that we don't want to change. 6669 // Only do this for the second authority since the resulting provider 6670 // object can be the same for all future authorities for this provider. 6671 p = new PackageParser.Provider(p); 6672 p.syncable = false; 6673 } 6674 if (!mProvidersByAuthority.containsKey(names[j])) { 6675 mProvidersByAuthority.put(names[j], p); 6676 if (p.info.authority == null) { 6677 p.info.authority = names[j]; 6678 } else { 6679 p.info.authority = p.info.authority + ";" + names[j]; 6680 } 6681 if (DEBUG_PACKAGE_SCANNING) { 6682 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6683 Log.d(TAG, "Registered content provider: " + names[j] 6684 + ", className = " + p.info.name + ", isSyncable = " 6685 + p.info.isSyncable); 6686 } 6687 } else { 6688 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6689 Slog.w(TAG, "Skipping provider name " + names[j] + 6690 " (in package " + pkg.applicationInfo.packageName + 6691 "): name already used by " 6692 + ((other != null && other.getComponentName() != null) 6693 ? other.getComponentName().getPackageName() : "?")); 6694 } 6695 } 6696 } 6697 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6698 if (r == null) { 6699 r = new StringBuilder(256); 6700 } else { 6701 r.append(' '); 6702 } 6703 r.append(p.info.name); 6704 } 6705 } 6706 if (r != null) { 6707 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6708 } 6709 6710 N = pkg.services.size(); 6711 r = null; 6712 for (i=0; i<N; i++) { 6713 PackageParser.Service s = pkg.services.get(i); 6714 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6715 s.info.processName, pkg.applicationInfo.uid); 6716 mServices.addService(s); 6717 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6718 if (r == null) { 6719 r = new StringBuilder(256); 6720 } else { 6721 r.append(' '); 6722 } 6723 r.append(s.info.name); 6724 } 6725 } 6726 if (r != null) { 6727 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6728 } 6729 6730 N = pkg.receivers.size(); 6731 r = null; 6732 for (i=0; i<N; i++) { 6733 PackageParser.Activity a = pkg.receivers.get(i); 6734 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6735 a.info.processName, pkg.applicationInfo.uid); 6736 mReceivers.addActivity(a, "receiver"); 6737 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6738 if (r == null) { 6739 r = new StringBuilder(256); 6740 } else { 6741 r.append(' '); 6742 } 6743 r.append(a.info.name); 6744 } 6745 } 6746 if (r != null) { 6747 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6748 } 6749 6750 N = pkg.activities.size(); 6751 r = null; 6752 for (i=0; i<N; i++) { 6753 PackageParser.Activity a = pkg.activities.get(i); 6754 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6755 a.info.processName, pkg.applicationInfo.uid); 6756 mActivities.addActivity(a, "activity"); 6757 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6758 if (r == null) { 6759 r = new StringBuilder(256); 6760 } else { 6761 r.append(' '); 6762 } 6763 r.append(a.info.name); 6764 } 6765 } 6766 if (r != null) { 6767 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6768 } 6769 6770 N = pkg.permissionGroups.size(); 6771 r = null; 6772 for (i=0; i<N; i++) { 6773 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6774 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6775 if (cur == null) { 6776 mPermissionGroups.put(pg.info.name, pg); 6777 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6778 if (r == null) { 6779 r = new StringBuilder(256); 6780 } else { 6781 r.append(' '); 6782 } 6783 r.append(pg.info.name); 6784 } 6785 } else { 6786 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6787 + pg.info.packageName + " ignored: original from " 6788 + cur.info.packageName); 6789 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6790 if (r == null) { 6791 r = new StringBuilder(256); 6792 } else { 6793 r.append(' '); 6794 } 6795 r.append("DUP:"); 6796 r.append(pg.info.name); 6797 } 6798 } 6799 } 6800 if (r != null) { 6801 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6802 } 6803 6804 N = pkg.permissions.size(); 6805 r = null; 6806 for (i=0; i<N; i++) { 6807 PackageParser.Permission p = pkg.permissions.get(i); 6808 6809 // Now that permission groups have a special meaning, we ignore permission 6810 // groups for legacy apps to prevent unexpected behavior. In particular, 6811 // permissions for one app being granted to someone just becuase they happen 6812 // to be in a group defined by another app (before this had no implications). 6813 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6814 p.group = mPermissionGroups.get(p.info.group); 6815 // Warn for a permission in an unknown group. 6816 if (p.info.group != null && p.group == null) { 6817 Slog.w(TAG, "Permission " + p.info.name + " from package " 6818 + p.info.packageName + " in an unknown group " + p.info.group); 6819 } 6820 } 6821 6822 ArrayMap<String, BasePermission> permissionMap = 6823 p.tree ? mSettings.mPermissionTrees 6824 : mSettings.mPermissions; 6825 BasePermission bp = permissionMap.get(p.info.name); 6826 6827 // Allow system apps to redefine non-system permissions 6828 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6829 final boolean currentOwnerIsSystem = (bp.perm != null 6830 && isSystemApp(bp.perm.owner)); 6831 if (isSystemApp(p.owner)) { 6832 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6833 // It's a built-in permission and no owner, take ownership now 6834 bp.packageSetting = pkgSetting; 6835 bp.perm = p; 6836 bp.uid = pkg.applicationInfo.uid; 6837 bp.sourcePackage = p.info.packageName; 6838 } else if (!currentOwnerIsSystem) { 6839 String msg = "New decl " + p.owner + " of permission " 6840 + p.info.name + " is system; overriding " + bp.sourcePackage; 6841 reportSettingsProblem(Log.WARN, msg); 6842 bp = null; 6843 } 6844 } 6845 } 6846 6847 if (bp == null) { 6848 bp = new BasePermission(p.info.name, p.info.packageName, 6849 BasePermission.TYPE_NORMAL); 6850 permissionMap.put(p.info.name, bp); 6851 } 6852 6853 if (bp.perm == null) { 6854 if (bp.sourcePackage == null 6855 || bp.sourcePackage.equals(p.info.packageName)) { 6856 BasePermission tree = findPermissionTreeLP(p.info.name); 6857 if (tree == null 6858 || tree.sourcePackage.equals(p.info.packageName)) { 6859 bp.packageSetting = pkgSetting; 6860 bp.perm = p; 6861 bp.uid = pkg.applicationInfo.uid; 6862 bp.sourcePackage = p.info.packageName; 6863 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6864 if (r == null) { 6865 r = new StringBuilder(256); 6866 } else { 6867 r.append(' '); 6868 } 6869 r.append(p.info.name); 6870 } 6871 } else { 6872 Slog.w(TAG, "Permission " + p.info.name + " from package " 6873 + p.info.packageName + " ignored: base tree " 6874 + tree.name + " is from package " 6875 + tree.sourcePackage); 6876 } 6877 } else { 6878 Slog.w(TAG, "Permission " + p.info.name + " from package " 6879 + p.info.packageName + " ignored: original from " 6880 + bp.sourcePackage); 6881 } 6882 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6883 if (r == null) { 6884 r = new StringBuilder(256); 6885 } else { 6886 r.append(' '); 6887 } 6888 r.append("DUP:"); 6889 r.append(p.info.name); 6890 } 6891 if (bp.perm == p) { 6892 bp.protectionLevel = p.info.protectionLevel; 6893 } 6894 } 6895 6896 if (r != null) { 6897 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6898 } 6899 6900 N = pkg.instrumentation.size(); 6901 r = null; 6902 for (i=0; i<N; i++) { 6903 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6904 a.info.packageName = pkg.applicationInfo.packageName; 6905 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6906 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6907 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6908 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6909 a.info.dataDir = pkg.applicationInfo.dataDir; 6910 6911 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6912 // need other information about the application, like the ABI and what not ? 6913 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6914 mInstrumentation.put(a.getComponentName(), a); 6915 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6916 if (r == null) { 6917 r = new StringBuilder(256); 6918 } else { 6919 r.append(' '); 6920 } 6921 r.append(a.info.name); 6922 } 6923 } 6924 if (r != null) { 6925 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6926 } 6927 6928 if (pkg.protectedBroadcasts != null) { 6929 N = pkg.protectedBroadcasts.size(); 6930 for (i=0; i<N; i++) { 6931 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6932 } 6933 } 6934 6935 pkgSetting.setTimeStamp(scanFileTime); 6936 6937 // Create idmap files for pairs of (packages, overlay packages). 6938 // Note: "android", ie framework-res.apk, is handled by native layers. 6939 if (pkg.mOverlayTarget != null) { 6940 // This is an overlay package. 6941 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6942 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6943 mOverlays.put(pkg.mOverlayTarget, 6944 new ArrayMap<String, PackageParser.Package>()); 6945 } 6946 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6947 map.put(pkg.packageName, pkg); 6948 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6949 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6950 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6951 "scanPackageLI failed to createIdmap"); 6952 } 6953 } 6954 } else if (mOverlays.containsKey(pkg.packageName) && 6955 !pkg.packageName.equals("android")) { 6956 // This is a regular package, with one or more known overlay packages. 6957 createIdmapsForPackageLI(pkg); 6958 } 6959 } 6960 6961 return pkg; 6962 } 6963 6964 /** 6965 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6966 * i.e, so that all packages can be run inside a single process if required. 6967 * 6968 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6969 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6970 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6971 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6972 * updating a package that belongs to a shared user. 6973 * 6974 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6975 * adds unnecessary complexity. 6976 */ 6977 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6978 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6979 String requiredInstructionSet = null; 6980 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6981 requiredInstructionSet = VMRuntime.getInstructionSet( 6982 scannedPackage.applicationInfo.primaryCpuAbi); 6983 } 6984 6985 PackageSetting requirer = null; 6986 for (PackageSetting ps : packagesForUser) { 6987 // If packagesForUser contains scannedPackage, we skip it. This will happen 6988 // when scannedPackage is an update of an existing package. Without this check, 6989 // we will never be able to change the ABI of any package belonging to a shared 6990 // user, even if it's compatible with other packages. 6991 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6992 if (ps.primaryCpuAbiString == null) { 6993 continue; 6994 } 6995 6996 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6997 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6998 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6999 // this but there's not much we can do. 7000 String errorMessage = "Instruction set mismatch, " 7001 + ((requirer == null) ? "[caller]" : requirer) 7002 + " requires " + requiredInstructionSet + " whereas " + ps 7003 + " requires " + instructionSet; 7004 Slog.w(TAG, errorMessage); 7005 } 7006 7007 if (requiredInstructionSet == null) { 7008 requiredInstructionSet = instructionSet; 7009 requirer = ps; 7010 } 7011 } 7012 } 7013 7014 if (requiredInstructionSet != null) { 7015 String adjustedAbi; 7016 if (requirer != null) { 7017 // requirer != null implies that either scannedPackage was null or that scannedPackage 7018 // did not require an ABI, in which case we have to adjust scannedPackage to match 7019 // the ABI of the set (which is the same as requirer's ABI) 7020 adjustedAbi = requirer.primaryCpuAbiString; 7021 if (scannedPackage != null) { 7022 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7023 } 7024 } else { 7025 // requirer == null implies that we're updating all ABIs in the set to 7026 // match scannedPackage. 7027 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7028 } 7029 7030 for (PackageSetting ps : packagesForUser) { 7031 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7032 if (ps.primaryCpuAbiString != null) { 7033 continue; 7034 } 7035 7036 ps.primaryCpuAbiString = adjustedAbi; 7037 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7038 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7039 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7040 7041 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7042 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7043 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7044 ps.primaryCpuAbiString = null; 7045 ps.pkg.applicationInfo.primaryCpuAbi = null; 7046 return; 7047 } else { 7048 mInstaller.rmdex(ps.codePathString, 7049 getDexCodeInstructionSet(getPreferredInstructionSet())); 7050 } 7051 } 7052 } 7053 } 7054 } 7055 } 7056 7057 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7058 synchronized (mPackages) { 7059 mResolverReplaced = true; 7060 // Set up information for custom user intent resolution activity. 7061 mResolveActivity.applicationInfo = pkg.applicationInfo; 7062 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7063 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7064 mResolveActivity.processName = pkg.applicationInfo.packageName; 7065 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7066 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7067 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7068 mResolveActivity.theme = 0; 7069 mResolveActivity.exported = true; 7070 mResolveActivity.enabled = true; 7071 mResolveInfo.activityInfo = mResolveActivity; 7072 mResolveInfo.priority = 0; 7073 mResolveInfo.preferredOrder = 0; 7074 mResolveInfo.match = 0; 7075 mResolveComponentName = mCustomResolverComponentName; 7076 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7077 mResolveComponentName); 7078 } 7079 } 7080 7081 private static String calculateBundledApkRoot(final String codePathString) { 7082 final File codePath = new File(codePathString); 7083 final File codeRoot; 7084 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7085 codeRoot = Environment.getRootDirectory(); 7086 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7087 codeRoot = Environment.getOemDirectory(); 7088 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7089 codeRoot = Environment.getVendorDirectory(); 7090 } else { 7091 // Unrecognized code path; take its top real segment as the apk root: 7092 // e.g. /something/app/blah.apk => /something 7093 try { 7094 File f = codePath.getCanonicalFile(); 7095 File parent = f.getParentFile(); // non-null because codePath is a file 7096 File tmp; 7097 while ((tmp = parent.getParentFile()) != null) { 7098 f = parent; 7099 parent = tmp; 7100 } 7101 codeRoot = f; 7102 Slog.w(TAG, "Unrecognized code path " 7103 + codePath + " - using " + codeRoot); 7104 } catch (IOException e) { 7105 // Can't canonicalize the code path -- shenanigans? 7106 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7107 return Environment.getRootDirectory().getPath(); 7108 } 7109 } 7110 return codeRoot.getPath(); 7111 } 7112 7113 /** 7114 * Derive and set the location of native libraries for the given package, 7115 * which varies depending on where and how the package was installed. 7116 */ 7117 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7118 final ApplicationInfo info = pkg.applicationInfo; 7119 final String codePath = pkg.codePath; 7120 final File codeFile = new File(codePath); 7121 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7122 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7123 7124 info.nativeLibraryRootDir = null; 7125 info.nativeLibraryRootRequiresIsa = false; 7126 info.nativeLibraryDir = null; 7127 info.secondaryNativeLibraryDir = null; 7128 7129 if (isApkFile(codeFile)) { 7130 // Monolithic install 7131 if (bundledApp) { 7132 // If "/system/lib64/apkname" exists, assume that is the per-package 7133 // native library directory to use; otherwise use "/system/lib/apkname". 7134 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7135 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7136 getPrimaryInstructionSet(info)); 7137 7138 // This is a bundled system app so choose the path based on the ABI. 7139 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7140 // is just the default path. 7141 final String apkName = deriveCodePathName(codePath); 7142 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7143 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7144 apkName).getAbsolutePath(); 7145 7146 if (info.secondaryCpuAbi != null) { 7147 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7148 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7149 secondaryLibDir, apkName).getAbsolutePath(); 7150 } 7151 } else if (asecApp) { 7152 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7153 .getAbsolutePath(); 7154 } else { 7155 final String apkName = deriveCodePathName(codePath); 7156 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7157 .getAbsolutePath(); 7158 } 7159 7160 info.nativeLibraryRootRequiresIsa = false; 7161 info.nativeLibraryDir = info.nativeLibraryRootDir; 7162 } else { 7163 // Cluster install 7164 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7165 info.nativeLibraryRootRequiresIsa = true; 7166 7167 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7168 getPrimaryInstructionSet(info)).getAbsolutePath(); 7169 7170 if (info.secondaryCpuAbi != null) { 7171 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7172 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7173 } 7174 } 7175 } 7176 7177 /** 7178 * Calculate the abis and roots for a bundled app. These can uniquely 7179 * be determined from the contents of the system partition, i.e whether 7180 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7181 * of this information, and instead assume that the system was built 7182 * sensibly. 7183 */ 7184 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7185 PackageSetting pkgSetting) { 7186 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7187 7188 // If "/system/lib64/apkname" exists, assume that is the per-package 7189 // native library directory to use; otherwise use "/system/lib/apkname". 7190 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7191 setBundledAppAbi(pkg, apkRoot, apkName); 7192 // pkgSetting might be null during rescan following uninstall of updates 7193 // to a bundled app, so accommodate that possibility. The settings in 7194 // that case will be established later from the parsed package. 7195 // 7196 // If the settings aren't null, sync them up with what we've just derived. 7197 // note that apkRoot isn't stored in the package settings. 7198 if (pkgSetting != null) { 7199 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7200 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7201 } 7202 } 7203 7204 /** 7205 * Deduces the ABI of a bundled app and sets the relevant fields on the 7206 * parsed pkg object. 7207 * 7208 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7209 * under which system libraries are installed. 7210 * @param apkName the name of the installed package. 7211 */ 7212 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7213 final File codeFile = new File(pkg.codePath); 7214 7215 final boolean has64BitLibs; 7216 final boolean has32BitLibs; 7217 if (isApkFile(codeFile)) { 7218 // Monolithic install 7219 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7220 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7221 } else { 7222 // Cluster install 7223 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7224 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7225 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7226 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7227 has64BitLibs = (new File(rootDir, isa)).exists(); 7228 } else { 7229 has64BitLibs = false; 7230 } 7231 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7232 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7233 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7234 has32BitLibs = (new File(rootDir, isa)).exists(); 7235 } else { 7236 has32BitLibs = false; 7237 } 7238 } 7239 7240 if (has64BitLibs && !has32BitLibs) { 7241 // The package has 64 bit libs, but not 32 bit libs. Its primary 7242 // ABI should be 64 bit. We can safely assume here that the bundled 7243 // native libraries correspond to the most preferred ABI in the list. 7244 7245 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7246 pkg.applicationInfo.secondaryCpuAbi = null; 7247 } else if (has32BitLibs && !has64BitLibs) { 7248 // The package has 32 bit libs but not 64 bit libs. Its primary 7249 // ABI should be 32 bit. 7250 7251 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7252 pkg.applicationInfo.secondaryCpuAbi = null; 7253 } else if (has32BitLibs && has64BitLibs) { 7254 // The application has both 64 and 32 bit bundled libraries. We check 7255 // here that the app declares multiArch support, and warn if it doesn't. 7256 // 7257 // We will be lenient here and record both ABIs. The primary will be the 7258 // ABI that's higher on the list, i.e, a device that's configured to prefer 7259 // 64 bit apps will see a 64 bit primary ABI, 7260 7261 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7262 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7263 } 7264 7265 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7266 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7267 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7268 } else { 7269 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7270 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7271 } 7272 } else { 7273 pkg.applicationInfo.primaryCpuAbi = null; 7274 pkg.applicationInfo.secondaryCpuAbi = null; 7275 } 7276 } 7277 7278 private void killApplication(String pkgName, int appId, String reason) { 7279 // Request the ActivityManager to kill the process(only for existing packages) 7280 // so that we do not end up in a confused state while the user is still using the older 7281 // version of the application while the new one gets installed. 7282 IActivityManager am = ActivityManagerNative.getDefault(); 7283 if (am != null) { 7284 try { 7285 am.killApplicationWithAppId(pkgName, appId, reason); 7286 } catch (RemoteException e) { 7287 } 7288 } 7289 } 7290 7291 void removePackageLI(PackageSetting ps, boolean chatty) { 7292 if (DEBUG_INSTALL) { 7293 if (chatty) 7294 Log.d(TAG, "Removing package " + ps.name); 7295 } 7296 7297 // writer 7298 synchronized (mPackages) { 7299 mPackages.remove(ps.name); 7300 final PackageParser.Package pkg = ps.pkg; 7301 if (pkg != null) { 7302 cleanPackageDataStructuresLILPw(pkg, chatty); 7303 } 7304 } 7305 } 7306 7307 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7308 if (DEBUG_INSTALL) { 7309 if (chatty) 7310 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7311 } 7312 7313 // writer 7314 synchronized (mPackages) { 7315 mPackages.remove(pkg.applicationInfo.packageName); 7316 cleanPackageDataStructuresLILPw(pkg, chatty); 7317 } 7318 } 7319 7320 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7321 int N = pkg.providers.size(); 7322 StringBuilder r = null; 7323 int i; 7324 for (i=0; i<N; i++) { 7325 PackageParser.Provider p = pkg.providers.get(i); 7326 mProviders.removeProvider(p); 7327 if (p.info.authority == null) { 7328 7329 /* There was another ContentProvider with this authority when 7330 * this app was installed so this authority is null, 7331 * Ignore it as we don't have to unregister the provider. 7332 */ 7333 continue; 7334 } 7335 String names[] = p.info.authority.split(";"); 7336 for (int j = 0; j < names.length; j++) { 7337 if (mProvidersByAuthority.get(names[j]) == p) { 7338 mProvidersByAuthority.remove(names[j]); 7339 if (DEBUG_REMOVE) { 7340 if (chatty) 7341 Log.d(TAG, "Unregistered content provider: " + names[j] 7342 + ", className = " + p.info.name + ", isSyncable = " 7343 + p.info.isSyncable); 7344 } 7345 } 7346 } 7347 if (DEBUG_REMOVE && chatty) { 7348 if (r == null) { 7349 r = new StringBuilder(256); 7350 } else { 7351 r.append(' '); 7352 } 7353 r.append(p.info.name); 7354 } 7355 } 7356 if (r != null) { 7357 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7358 } 7359 7360 N = pkg.services.size(); 7361 r = null; 7362 for (i=0; i<N; i++) { 7363 PackageParser.Service s = pkg.services.get(i); 7364 mServices.removeService(s); 7365 if (chatty) { 7366 if (r == null) { 7367 r = new StringBuilder(256); 7368 } else { 7369 r.append(' '); 7370 } 7371 r.append(s.info.name); 7372 } 7373 } 7374 if (r != null) { 7375 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7376 } 7377 7378 N = pkg.receivers.size(); 7379 r = null; 7380 for (i=0; i<N; i++) { 7381 PackageParser.Activity a = pkg.receivers.get(i); 7382 mReceivers.removeActivity(a, "receiver"); 7383 if (DEBUG_REMOVE && chatty) { 7384 if (r == null) { 7385 r = new StringBuilder(256); 7386 } else { 7387 r.append(' '); 7388 } 7389 r.append(a.info.name); 7390 } 7391 } 7392 if (r != null) { 7393 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7394 } 7395 7396 N = pkg.activities.size(); 7397 r = null; 7398 for (i=0; i<N; i++) { 7399 PackageParser.Activity a = pkg.activities.get(i); 7400 mActivities.removeActivity(a, "activity"); 7401 if (DEBUG_REMOVE && chatty) { 7402 if (r == null) { 7403 r = new StringBuilder(256); 7404 } else { 7405 r.append(' '); 7406 } 7407 r.append(a.info.name); 7408 } 7409 } 7410 if (r != null) { 7411 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7412 } 7413 7414 N = pkg.permissions.size(); 7415 r = null; 7416 for (i=0; i<N; i++) { 7417 PackageParser.Permission p = pkg.permissions.get(i); 7418 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7419 if (bp == null) { 7420 bp = mSettings.mPermissionTrees.get(p.info.name); 7421 } 7422 if (bp != null && bp.perm == p) { 7423 bp.perm = null; 7424 if (DEBUG_REMOVE && chatty) { 7425 if (r == null) { 7426 r = new StringBuilder(256); 7427 } else { 7428 r.append(' '); 7429 } 7430 r.append(p.info.name); 7431 } 7432 } 7433 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7434 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7435 if (appOpPerms != null) { 7436 appOpPerms.remove(pkg.packageName); 7437 } 7438 } 7439 } 7440 if (r != null) { 7441 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7442 } 7443 7444 N = pkg.requestedPermissions.size(); 7445 r = null; 7446 for (i=0; i<N; i++) { 7447 String perm = pkg.requestedPermissions.get(i); 7448 BasePermission bp = mSettings.mPermissions.get(perm); 7449 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7450 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7451 if (appOpPerms != null) { 7452 appOpPerms.remove(pkg.packageName); 7453 if (appOpPerms.isEmpty()) { 7454 mAppOpPermissionPackages.remove(perm); 7455 } 7456 } 7457 } 7458 } 7459 if (r != null) { 7460 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7461 } 7462 7463 N = pkg.instrumentation.size(); 7464 r = null; 7465 for (i=0; i<N; i++) { 7466 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7467 mInstrumentation.remove(a.getComponentName()); 7468 if (DEBUG_REMOVE && chatty) { 7469 if (r == null) { 7470 r = new StringBuilder(256); 7471 } else { 7472 r.append(' '); 7473 } 7474 r.append(a.info.name); 7475 } 7476 } 7477 if (r != null) { 7478 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7479 } 7480 7481 r = null; 7482 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7483 // Only system apps can hold shared libraries. 7484 if (pkg.libraryNames != null) { 7485 for (i=0; i<pkg.libraryNames.size(); i++) { 7486 String name = pkg.libraryNames.get(i); 7487 SharedLibraryEntry cur = mSharedLibraries.get(name); 7488 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7489 mSharedLibraries.remove(name); 7490 if (DEBUG_REMOVE && chatty) { 7491 if (r == null) { 7492 r = new StringBuilder(256); 7493 } else { 7494 r.append(' '); 7495 } 7496 r.append(name); 7497 } 7498 } 7499 } 7500 } 7501 } 7502 if (r != null) { 7503 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7504 } 7505 } 7506 7507 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7508 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7509 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7510 return true; 7511 } 7512 } 7513 return false; 7514 } 7515 7516 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7517 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7518 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7519 7520 private void updatePermissionsLPw(String changingPkg, 7521 PackageParser.Package pkgInfo, int flags) { 7522 // Make sure there are no dangling permission trees. 7523 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7524 while (it.hasNext()) { 7525 final BasePermission bp = it.next(); 7526 if (bp.packageSetting == null) { 7527 // We may not yet have parsed the package, so just see if 7528 // we still know about its settings. 7529 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7530 } 7531 if (bp.packageSetting == null) { 7532 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7533 + " from package " + bp.sourcePackage); 7534 it.remove(); 7535 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7536 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7537 Slog.i(TAG, "Removing old permission tree: " + bp.name 7538 + " from package " + bp.sourcePackage); 7539 flags |= UPDATE_PERMISSIONS_ALL; 7540 it.remove(); 7541 } 7542 } 7543 } 7544 7545 // Make sure all dynamic permissions have been assigned to a package, 7546 // and make sure there are no dangling permissions. 7547 it = mSettings.mPermissions.values().iterator(); 7548 while (it.hasNext()) { 7549 final BasePermission bp = it.next(); 7550 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7551 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7552 + bp.name + " pkg=" + bp.sourcePackage 7553 + " info=" + bp.pendingInfo); 7554 if (bp.packageSetting == null && bp.pendingInfo != null) { 7555 final BasePermission tree = findPermissionTreeLP(bp.name); 7556 if (tree != null && tree.perm != null) { 7557 bp.packageSetting = tree.packageSetting; 7558 bp.perm = new PackageParser.Permission(tree.perm.owner, 7559 new PermissionInfo(bp.pendingInfo)); 7560 bp.perm.info.packageName = tree.perm.info.packageName; 7561 bp.perm.info.name = bp.name; 7562 bp.uid = tree.uid; 7563 } 7564 } 7565 } 7566 if (bp.packageSetting == null) { 7567 // We may not yet have parsed the package, so just see if 7568 // we still know about its settings. 7569 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7570 } 7571 if (bp.packageSetting == null) { 7572 Slog.w(TAG, "Removing dangling permission: " + bp.name 7573 + " from package " + bp.sourcePackage); 7574 it.remove(); 7575 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7576 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7577 Slog.i(TAG, "Removing old permission: " + bp.name 7578 + " from package " + bp.sourcePackage); 7579 flags |= UPDATE_PERMISSIONS_ALL; 7580 it.remove(); 7581 } 7582 } 7583 } 7584 7585 // Now update the permissions for all packages, in particular 7586 // replace the granted permissions of the system packages. 7587 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7588 for (PackageParser.Package pkg : mPackages.values()) { 7589 if (pkg != pkgInfo) { 7590 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7591 changingPkg); 7592 } 7593 } 7594 } 7595 7596 if (pkgInfo != null) { 7597 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7598 } 7599 } 7600 7601 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7602 String packageOfInterest) { 7603 // IMPORTANT: There are two types of permissions: install and runtime. 7604 // Install time permissions are granted when the app is installed to 7605 // all device users and users added in the future. Runtime permissions 7606 // are granted at runtime explicitly to specific users. Normal and signature 7607 // protected permissions are install time permissions. Dangerous permissions 7608 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7609 // otherwise they are runtime permissions. This function does not manage 7610 // runtime permissions except for the case an app targeting Lollipop MR1 7611 // being upgraded to target a newer SDK, in which case dangerous permissions 7612 // are transformed from install time to runtime ones. 7613 7614 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7615 if (ps == null) { 7616 return; 7617 } 7618 7619 PermissionsState permissionsState = ps.getPermissionsState(); 7620 PermissionsState origPermissions = permissionsState; 7621 7622 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7623 7624 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7625 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7626 7627 boolean changedInstallPermission = false; 7628 7629 if (replace) { 7630 ps.installPermissionsFixed = false; 7631 if (!ps.isSharedUser()) { 7632 origPermissions = new PermissionsState(permissionsState); 7633 permissionsState.reset(); 7634 } 7635 } 7636 7637 permissionsState.setGlobalGids(mGlobalGids); 7638 7639 final int N = pkg.requestedPermissions.size(); 7640 for (int i=0; i<N; i++) { 7641 final String name = pkg.requestedPermissions.get(i); 7642 final BasePermission bp = mSettings.mPermissions.get(name); 7643 7644 if (DEBUG_INSTALL) { 7645 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7646 } 7647 7648 if (bp == null || bp.packageSetting == null) { 7649 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7650 Slog.w(TAG, "Unknown permission " + name 7651 + " in package " + pkg.packageName); 7652 } 7653 continue; 7654 } 7655 7656 final String perm = bp.name; 7657 boolean allowedSig = false; 7658 int grant = GRANT_DENIED; 7659 7660 // Keep track of app op permissions. 7661 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7662 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7663 if (pkgs == null) { 7664 pkgs = new ArraySet<>(); 7665 mAppOpPermissionPackages.put(bp.name, pkgs); 7666 } 7667 pkgs.add(pkg.packageName); 7668 } 7669 7670 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7671 switch (level) { 7672 case PermissionInfo.PROTECTION_NORMAL: { 7673 // For all apps normal permissions are install time ones. 7674 grant = GRANT_INSTALL; 7675 } break; 7676 7677 case PermissionInfo.PROTECTION_DANGEROUS: { 7678 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7679 // For legacy apps dangerous permissions are install time ones. 7680 grant = GRANT_INSTALL; 7681 } else if (ps.isSystem()) { 7682 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7683 if (origPermissions.hasInstallPermission(bp.name)) { 7684 // If a system app had an install permission, then the app was 7685 // upgraded and we grant the permissions as runtime to all users. 7686 grant = GRANT_UPGRADE; 7687 upgradeUserIds = currentUserIds; 7688 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7689 // If users changed since the last permissions update for a 7690 // system app, we grant the permission as runtime to the new users. 7691 grant = GRANT_UPGRADE; 7692 upgradeUserIds = currentUserIds; 7693 for (int userId : updatedUserIds) { 7694 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7695 } 7696 } else { 7697 // Otherwise, we grant the permission as runtime if the app 7698 // already had it, i.e. we preserve runtime permissions. 7699 grant = GRANT_RUNTIME; 7700 } 7701 } else if (origPermissions.hasInstallPermission(bp.name)) { 7702 // For legacy apps that became modern, install becomes runtime. 7703 grant = GRANT_UPGRADE; 7704 upgradeUserIds = currentUserIds; 7705 } else if (replace) { 7706 // For upgraded modern apps keep runtime permissions unchanged. 7707 grant = GRANT_RUNTIME; 7708 } 7709 } break; 7710 7711 case PermissionInfo.PROTECTION_SIGNATURE: { 7712 // For all apps signature permissions are install time ones. 7713 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7714 if (allowedSig) { 7715 grant = GRANT_INSTALL; 7716 } 7717 } break; 7718 } 7719 7720 if (DEBUG_INSTALL) { 7721 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7722 } 7723 7724 if (grant != GRANT_DENIED) { 7725 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7726 // If this is an existing, non-system package, then 7727 // we can't add any new permissions to it. 7728 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7729 // Except... if this is a permission that was added 7730 // to the platform (note: need to only do this when 7731 // updating the platform). 7732 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7733 grant = GRANT_DENIED; 7734 } 7735 } 7736 } 7737 7738 switch (grant) { 7739 case GRANT_INSTALL: { 7740 // Grant an install permission. 7741 if (permissionsState.grantInstallPermission(bp) != 7742 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7743 changedInstallPermission = true; 7744 } 7745 } break; 7746 7747 case GRANT_RUNTIME: { 7748 // Grant previously granted runtime permissions. 7749 for (int userId : UserManagerService.getInstance().getUserIds()) { 7750 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7751 PermissionState permissionState = origPermissions 7752 .getRuntimePermissionState(bp.name, userId); 7753 final int flags = permissionState.getFlags(); 7754 if (permissionsState.grantRuntimePermission(bp, userId) == 7755 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7756 // If we cannot put the permission as it was, we have to write. 7757 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7758 changedRuntimePermissionUserIds, userId); 7759 } else { 7760 // Propagate the permission flags. 7761 permissionsState.updatePermissionFlags(bp, userId, 7762 flags, flags); 7763 } 7764 } 7765 } 7766 } break; 7767 7768 case GRANT_UPGRADE: { 7769 // Grant runtime permissions for a previously held install permission. 7770 PermissionState permissionState = origPermissions 7771 .getInstallPermissionState(bp.name); 7772 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7773 7774 origPermissions.revokeInstallPermission(bp); 7775 // We will be transferring the permission flags, so clear them. 7776 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7777 PackageManager.MASK_PERMISSION_FLAGS, 0); 7778 7779 // If the permission is not to be promoted to runtime we ignore it and 7780 // also its other flags as they are not applicable to install permissions. 7781 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7782 for (int userId : upgradeUserIds) { 7783 if (permissionsState.grantRuntimePermission(bp, userId) != 7784 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7785 // Transfer the permission flags. 7786 permissionsState.updatePermissionFlags(bp, userId, 7787 flags, flags); 7788 // If we granted the permission, we have to write. 7789 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7790 changedRuntimePermissionUserIds, userId); 7791 } 7792 } 7793 } 7794 } break; 7795 7796 default: { 7797 if (packageOfInterest == null 7798 || packageOfInterest.equals(pkg.packageName)) { 7799 Slog.w(TAG, "Not granting permission " + perm 7800 + " to package " + pkg.packageName 7801 + " because it was previously installed without"); 7802 } 7803 } break; 7804 } 7805 } else { 7806 if (permissionsState.revokeInstallPermission(bp) != 7807 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7808 // Also drop the permission flags. 7809 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7810 PackageManager.MASK_PERMISSION_FLAGS, 0); 7811 changedInstallPermission = true; 7812 Slog.i(TAG, "Un-granting permission " + perm 7813 + " from package " + pkg.packageName 7814 + " (protectionLevel=" + bp.protectionLevel 7815 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7816 + ")"); 7817 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7818 // Don't print warning for app op permissions, since it is fine for them 7819 // not to be granted, there is a UI for the user to decide. 7820 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7821 Slog.w(TAG, "Not granting permission " + perm 7822 + " to package " + pkg.packageName 7823 + " (protectionLevel=" + bp.protectionLevel 7824 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7825 + ")"); 7826 } 7827 } 7828 } 7829 } 7830 7831 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7832 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7833 // This is the first that we have heard about this package, so the 7834 // permissions we have now selected are fixed until explicitly 7835 // changed. 7836 ps.installPermissionsFixed = true; 7837 } 7838 7839 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7840 7841 // Persist the runtime permissions state for users with changes. 7842 for (int userId : changedRuntimePermissionUserIds) { 7843 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7844 } 7845 } 7846 7847 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7848 boolean allowed = false; 7849 final int NP = PackageParser.NEW_PERMISSIONS.length; 7850 for (int ip=0; ip<NP; ip++) { 7851 final PackageParser.NewPermissionInfo npi 7852 = PackageParser.NEW_PERMISSIONS[ip]; 7853 if (npi.name.equals(perm) 7854 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7855 allowed = true; 7856 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7857 + pkg.packageName); 7858 break; 7859 } 7860 } 7861 return allowed; 7862 } 7863 7864 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7865 BasePermission bp, PermissionsState origPermissions) { 7866 boolean allowed; 7867 allowed = (compareSignatures( 7868 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7869 == PackageManager.SIGNATURE_MATCH) 7870 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7871 == PackageManager.SIGNATURE_MATCH); 7872 if (!allowed && (bp.protectionLevel 7873 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7874 if (isSystemApp(pkg)) { 7875 // For updated system applications, a system permission 7876 // is granted only if it had been defined by the original application. 7877 if (pkg.isUpdatedSystemApp()) { 7878 final PackageSetting sysPs = mSettings 7879 .getDisabledSystemPkgLPr(pkg.packageName); 7880 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7881 // If the original was granted this permission, we take 7882 // that grant decision as read and propagate it to the 7883 // update. 7884 if (sysPs.isPrivileged()) { 7885 allowed = true; 7886 } 7887 } else { 7888 // The system apk may have been updated with an older 7889 // version of the one on the data partition, but which 7890 // granted a new system permission that it didn't have 7891 // before. In this case we do want to allow the app to 7892 // now get the new permission if the ancestral apk is 7893 // privileged to get it. 7894 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7895 for (int j=0; 7896 j<sysPs.pkg.requestedPermissions.size(); j++) { 7897 if (perm.equals( 7898 sysPs.pkg.requestedPermissions.get(j))) { 7899 allowed = true; 7900 break; 7901 } 7902 } 7903 } 7904 } 7905 } else { 7906 allowed = isPrivilegedApp(pkg); 7907 } 7908 } 7909 } 7910 if (!allowed && (bp.protectionLevel 7911 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7912 // For development permissions, a development permission 7913 // is granted only if it was already granted. 7914 allowed = origPermissions.hasInstallPermission(perm); 7915 } 7916 return allowed; 7917 } 7918 7919 final class ActivityIntentResolver 7920 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7921 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7922 boolean defaultOnly, int userId) { 7923 if (!sUserManager.exists(userId)) return null; 7924 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7925 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7926 } 7927 7928 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7929 int userId) { 7930 if (!sUserManager.exists(userId)) return null; 7931 mFlags = flags; 7932 return super.queryIntent(intent, resolvedType, 7933 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7934 } 7935 7936 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7937 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7938 if (!sUserManager.exists(userId)) return null; 7939 if (packageActivities == null) { 7940 return null; 7941 } 7942 mFlags = flags; 7943 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7944 final int N = packageActivities.size(); 7945 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7946 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7947 7948 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7949 for (int i = 0; i < N; ++i) { 7950 intentFilters = packageActivities.get(i).intents; 7951 if (intentFilters != null && intentFilters.size() > 0) { 7952 PackageParser.ActivityIntentInfo[] array = 7953 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7954 intentFilters.toArray(array); 7955 listCut.add(array); 7956 } 7957 } 7958 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7959 } 7960 7961 public final void addActivity(PackageParser.Activity a, String type) { 7962 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7963 mActivities.put(a.getComponentName(), a); 7964 if (DEBUG_SHOW_INFO) 7965 Log.v( 7966 TAG, " " + type + " " + 7967 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7968 if (DEBUG_SHOW_INFO) 7969 Log.v(TAG, " Class=" + a.info.name); 7970 final int NI = a.intents.size(); 7971 for (int j=0; j<NI; j++) { 7972 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7973 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7974 intent.setPriority(0); 7975 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7976 + a.className + " with priority > 0, forcing to 0"); 7977 } 7978 if (DEBUG_SHOW_INFO) { 7979 Log.v(TAG, " IntentFilter:"); 7980 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7981 } 7982 if (!intent.debugCheck()) { 7983 Log.w(TAG, "==> For Activity " + a.info.name); 7984 } 7985 addFilter(intent); 7986 } 7987 } 7988 7989 public final void removeActivity(PackageParser.Activity a, String type) { 7990 mActivities.remove(a.getComponentName()); 7991 if (DEBUG_SHOW_INFO) { 7992 Log.v(TAG, " " + type + " " 7993 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7994 : a.info.name) + ":"); 7995 Log.v(TAG, " Class=" + a.info.name); 7996 } 7997 final int NI = a.intents.size(); 7998 for (int j=0; j<NI; j++) { 7999 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8000 if (DEBUG_SHOW_INFO) { 8001 Log.v(TAG, " IntentFilter:"); 8002 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8003 } 8004 removeFilter(intent); 8005 } 8006 } 8007 8008 @Override 8009 protected boolean allowFilterResult( 8010 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8011 ActivityInfo filterAi = filter.activity.info; 8012 for (int i=dest.size()-1; i>=0; i--) { 8013 ActivityInfo destAi = dest.get(i).activityInfo; 8014 if (destAi.name == filterAi.name 8015 && destAi.packageName == filterAi.packageName) { 8016 return false; 8017 } 8018 } 8019 return true; 8020 } 8021 8022 @Override 8023 protected ActivityIntentInfo[] newArray(int size) { 8024 return new ActivityIntentInfo[size]; 8025 } 8026 8027 @Override 8028 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8029 if (!sUserManager.exists(userId)) return true; 8030 PackageParser.Package p = filter.activity.owner; 8031 if (p != null) { 8032 PackageSetting ps = (PackageSetting)p.mExtras; 8033 if (ps != null) { 8034 // System apps are never considered stopped for purposes of 8035 // filtering, because there may be no way for the user to 8036 // actually re-launch them. 8037 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8038 && ps.getStopped(userId); 8039 } 8040 } 8041 return false; 8042 } 8043 8044 @Override 8045 protected boolean isPackageForFilter(String packageName, 8046 PackageParser.ActivityIntentInfo info) { 8047 return packageName.equals(info.activity.owner.packageName); 8048 } 8049 8050 @Override 8051 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8052 int match, int userId) { 8053 if (!sUserManager.exists(userId)) return null; 8054 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8055 return null; 8056 } 8057 final PackageParser.Activity activity = info.activity; 8058 if (mSafeMode && (activity.info.applicationInfo.flags 8059 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8060 return null; 8061 } 8062 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8063 if (ps == null) { 8064 return null; 8065 } 8066 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8067 ps.readUserState(userId), userId); 8068 if (ai == null) { 8069 return null; 8070 } 8071 final ResolveInfo res = new ResolveInfo(); 8072 res.activityInfo = ai; 8073 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8074 res.filter = info; 8075 } 8076 if (info != null) { 8077 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8078 } 8079 res.priority = info.getPriority(); 8080 res.preferredOrder = activity.owner.mPreferredOrder; 8081 //System.out.println("Result: " + res.activityInfo.className + 8082 // " = " + res.priority); 8083 res.match = match; 8084 res.isDefault = info.hasDefault; 8085 res.labelRes = info.labelRes; 8086 res.nonLocalizedLabel = info.nonLocalizedLabel; 8087 if (userNeedsBadging(userId)) { 8088 res.noResourceId = true; 8089 } else { 8090 res.icon = info.icon; 8091 } 8092 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8093 return res; 8094 } 8095 8096 @Override 8097 protected void sortResults(List<ResolveInfo> results) { 8098 Collections.sort(results, mResolvePrioritySorter); 8099 } 8100 8101 @Override 8102 protected void dumpFilter(PrintWriter out, String prefix, 8103 PackageParser.ActivityIntentInfo filter) { 8104 out.print(prefix); out.print( 8105 Integer.toHexString(System.identityHashCode(filter.activity))); 8106 out.print(' '); 8107 filter.activity.printComponentShortName(out); 8108 out.print(" filter "); 8109 out.println(Integer.toHexString(System.identityHashCode(filter))); 8110 } 8111 8112 @Override 8113 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8114 return filter.activity; 8115 } 8116 8117 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8118 PackageParser.Activity activity = (PackageParser.Activity)label; 8119 out.print(prefix); out.print( 8120 Integer.toHexString(System.identityHashCode(activity))); 8121 out.print(' '); 8122 activity.printComponentShortName(out); 8123 if (count > 1) { 8124 out.print(" ("); out.print(count); out.print(" filters)"); 8125 } 8126 out.println(); 8127 } 8128 8129// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8130// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8131// final List<ResolveInfo> retList = Lists.newArrayList(); 8132// while (i.hasNext()) { 8133// final ResolveInfo resolveInfo = i.next(); 8134// if (isEnabledLP(resolveInfo.activityInfo)) { 8135// retList.add(resolveInfo); 8136// } 8137// } 8138// return retList; 8139// } 8140 8141 // Keys are String (activity class name), values are Activity. 8142 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8143 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8144 private int mFlags; 8145 } 8146 8147 private final class ServiceIntentResolver 8148 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8149 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8150 boolean defaultOnly, int userId) { 8151 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8152 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8153 } 8154 8155 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8156 int userId) { 8157 if (!sUserManager.exists(userId)) return null; 8158 mFlags = flags; 8159 return super.queryIntent(intent, resolvedType, 8160 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8161 } 8162 8163 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8164 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8165 if (!sUserManager.exists(userId)) return null; 8166 if (packageServices == null) { 8167 return null; 8168 } 8169 mFlags = flags; 8170 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8171 final int N = packageServices.size(); 8172 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8173 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8174 8175 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8176 for (int i = 0; i < N; ++i) { 8177 intentFilters = packageServices.get(i).intents; 8178 if (intentFilters != null && intentFilters.size() > 0) { 8179 PackageParser.ServiceIntentInfo[] array = 8180 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8181 intentFilters.toArray(array); 8182 listCut.add(array); 8183 } 8184 } 8185 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8186 } 8187 8188 public final void addService(PackageParser.Service s) { 8189 mServices.put(s.getComponentName(), s); 8190 if (DEBUG_SHOW_INFO) { 8191 Log.v(TAG, " " 8192 + (s.info.nonLocalizedLabel != null 8193 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8194 Log.v(TAG, " Class=" + s.info.name); 8195 } 8196 final int NI = s.intents.size(); 8197 int j; 8198 for (j=0; j<NI; j++) { 8199 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8200 if (DEBUG_SHOW_INFO) { 8201 Log.v(TAG, " IntentFilter:"); 8202 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8203 } 8204 if (!intent.debugCheck()) { 8205 Log.w(TAG, "==> For Service " + s.info.name); 8206 } 8207 addFilter(intent); 8208 } 8209 } 8210 8211 public final void removeService(PackageParser.Service s) { 8212 mServices.remove(s.getComponentName()); 8213 if (DEBUG_SHOW_INFO) { 8214 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8215 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8216 Log.v(TAG, " Class=" + s.info.name); 8217 } 8218 final int NI = s.intents.size(); 8219 int j; 8220 for (j=0; j<NI; j++) { 8221 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8222 if (DEBUG_SHOW_INFO) { 8223 Log.v(TAG, " IntentFilter:"); 8224 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8225 } 8226 removeFilter(intent); 8227 } 8228 } 8229 8230 @Override 8231 protected boolean allowFilterResult( 8232 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8233 ServiceInfo filterSi = filter.service.info; 8234 for (int i=dest.size()-1; i>=0; i--) { 8235 ServiceInfo destAi = dest.get(i).serviceInfo; 8236 if (destAi.name == filterSi.name 8237 && destAi.packageName == filterSi.packageName) { 8238 return false; 8239 } 8240 } 8241 return true; 8242 } 8243 8244 @Override 8245 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8246 return new PackageParser.ServiceIntentInfo[size]; 8247 } 8248 8249 @Override 8250 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8251 if (!sUserManager.exists(userId)) return true; 8252 PackageParser.Package p = filter.service.owner; 8253 if (p != null) { 8254 PackageSetting ps = (PackageSetting)p.mExtras; 8255 if (ps != null) { 8256 // System apps are never considered stopped for purposes of 8257 // filtering, because there may be no way for the user to 8258 // actually re-launch them. 8259 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8260 && ps.getStopped(userId); 8261 } 8262 } 8263 return false; 8264 } 8265 8266 @Override 8267 protected boolean isPackageForFilter(String packageName, 8268 PackageParser.ServiceIntentInfo info) { 8269 return packageName.equals(info.service.owner.packageName); 8270 } 8271 8272 @Override 8273 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8274 int match, int userId) { 8275 if (!sUserManager.exists(userId)) return null; 8276 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8277 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8278 return null; 8279 } 8280 final PackageParser.Service service = info.service; 8281 if (mSafeMode && (service.info.applicationInfo.flags 8282 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8283 return null; 8284 } 8285 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8286 if (ps == null) { 8287 return null; 8288 } 8289 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8290 ps.readUserState(userId), userId); 8291 if (si == null) { 8292 return null; 8293 } 8294 final ResolveInfo res = new ResolveInfo(); 8295 res.serviceInfo = si; 8296 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8297 res.filter = filter; 8298 } 8299 res.priority = info.getPriority(); 8300 res.preferredOrder = service.owner.mPreferredOrder; 8301 res.match = match; 8302 res.isDefault = info.hasDefault; 8303 res.labelRes = info.labelRes; 8304 res.nonLocalizedLabel = info.nonLocalizedLabel; 8305 res.icon = info.icon; 8306 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8307 return res; 8308 } 8309 8310 @Override 8311 protected void sortResults(List<ResolveInfo> results) { 8312 Collections.sort(results, mResolvePrioritySorter); 8313 } 8314 8315 @Override 8316 protected void dumpFilter(PrintWriter out, String prefix, 8317 PackageParser.ServiceIntentInfo filter) { 8318 out.print(prefix); out.print( 8319 Integer.toHexString(System.identityHashCode(filter.service))); 8320 out.print(' '); 8321 filter.service.printComponentShortName(out); 8322 out.print(" filter "); 8323 out.println(Integer.toHexString(System.identityHashCode(filter))); 8324 } 8325 8326 @Override 8327 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8328 return filter.service; 8329 } 8330 8331 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8332 PackageParser.Service service = (PackageParser.Service)label; 8333 out.print(prefix); out.print( 8334 Integer.toHexString(System.identityHashCode(service))); 8335 out.print(' '); 8336 service.printComponentShortName(out); 8337 if (count > 1) { 8338 out.print(" ("); out.print(count); out.print(" filters)"); 8339 } 8340 out.println(); 8341 } 8342 8343// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8344// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8345// final List<ResolveInfo> retList = Lists.newArrayList(); 8346// while (i.hasNext()) { 8347// final ResolveInfo resolveInfo = (ResolveInfo) i; 8348// if (isEnabledLP(resolveInfo.serviceInfo)) { 8349// retList.add(resolveInfo); 8350// } 8351// } 8352// return retList; 8353// } 8354 8355 // Keys are String (activity class name), values are Activity. 8356 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8357 = new ArrayMap<ComponentName, PackageParser.Service>(); 8358 private int mFlags; 8359 }; 8360 8361 private final class ProviderIntentResolver 8362 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8363 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8364 boolean defaultOnly, int userId) { 8365 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8366 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8367 } 8368 8369 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8370 int userId) { 8371 if (!sUserManager.exists(userId)) 8372 return null; 8373 mFlags = flags; 8374 return super.queryIntent(intent, resolvedType, 8375 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8376 } 8377 8378 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8379 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8380 if (!sUserManager.exists(userId)) 8381 return null; 8382 if (packageProviders == null) { 8383 return null; 8384 } 8385 mFlags = flags; 8386 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8387 final int N = packageProviders.size(); 8388 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8389 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8390 8391 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8392 for (int i = 0; i < N; ++i) { 8393 intentFilters = packageProviders.get(i).intents; 8394 if (intentFilters != null && intentFilters.size() > 0) { 8395 PackageParser.ProviderIntentInfo[] array = 8396 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8397 intentFilters.toArray(array); 8398 listCut.add(array); 8399 } 8400 } 8401 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8402 } 8403 8404 public final void addProvider(PackageParser.Provider p) { 8405 if (mProviders.containsKey(p.getComponentName())) { 8406 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8407 return; 8408 } 8409 8410 mProviders.put(p.getComponentName(), p); 8411 if (DEBUG_SHOW_INFO) { 8412 Log.v(TAG, " " 8413 + (p.info.nonLocalizedLabel != null 8414 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8415 Log.v(TAG, " Class=" + p.info.name); 8416 } 8417 final int NI = p.intents.size(); 8418 int j; 8419 for (j = 0; j < NI; j++) { 8420 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8421 if (DEBUG_SHOW_INFO) { 8422 Log.v(TAG, " IntentFilter:"); 8423 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8424 } 8425 if (!intent.debugCheck()) { 8426 Log.w(TAG, "==> For Provider " + p.info.name); 8427 } 8428 addFilter(intent); 8429 } 8430 } 8431 8432 public final void removeProvider(PackageParser.Provider p) { 8433 mProviders.remove(p.getComponentName()); 8434 if (DEBUG_SHOW_INFO) { 8435 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8436 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8437 Log.v(TAG, " Class=" + p.info.name); 8438 } 8439 final int NI = p.intents.size(); 8440 int j; 8441 for (j = 0; j < NI; j++) { 8442 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8443 if (DEBUG_SHOW_INFO) { 8444 Log.v(TAG, " IntentFilter:"); 8445 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8446 } 8447 removeFilter(intent); 8448 } 8449 } 8450 8451 @Override 8452 protected boolean allowFilterResult( 8453 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8454 ProviderInfo filterPi = filter.provider.info; 8455 for (int i = dest.size() - 1; i >= 0; i--) { 8456 ProviderInfo destPi = dest.get(i).providerInfo; 8457 if (destPi.name == filterPi.name 8458 && destPi.packageName == filterPi.packageName) { 8459 return false; 8460 } 8461 } 8462 return true; 8463 } 8464 8465 @Override 8466 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8467 return new PackageParser.ProviderIntentInfo[size]; 8468 } 8469 8470 @Override 8471 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8472 if (!sUserManager.exists(userId)) 8473 return true; 8474 PackageParser.Package p = filter.provider.owner; 8475 if (p != null) { 8476 PackageSetting ps = (PackageSetting) p.mExtras; 8477 if (ps != null) { 8478 // System apps are never considered stopped for purposes of 8479 // filtering, because there may be no way for the user to 8480 // actually re-launch them. 8481 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8482 && ps.getStopped(userId); 8483 } 8484 } 8485 return false; 8486 } 8487 8488 @Override 8489 protected boolean isPackageForFilter(String packageName, 8490 PackageParser.ProviderIntentInfo info) { 8491 return packageName.equals(info.provider.owner.packageName); 8492 } 8493 8494 @Override 8495 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8496 int match, int userId) { 8497 if (!sUserManager.exists(userId)) 8498 return null; 8499 final PackageParser.ProviderIntentInfo info = filter; 8500 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8501 return null; 8502 } 8503 final PackageParser.Provider provider = info.provider; 8504 if (mSafeMode && (provider.info.applicationInfo.flags 8505 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8506 return null; 8507 } 8508 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8509 if (ps == null) { 8510 return null; 8511 } 8512 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8513 ps.readUserState(userId), userId); 8514 if (pi == null) { 8515 return null; 8516 } 8517 final ResolveInfo res = new ResolveInfo(); 8518 res.providerInfo = pi; 8519 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8520 res.filter = filter; 8521 } 8522 res.priority = info.getPriority(); 8523 res.preferredOrder = provider.owner.mPreferredOrder; 8524 res.match = match; 8525 res.isDefault = info.hasDefault; 8526 res.labelRes = info.labelRes; 8527 res.nonLocalizedLabel = info.nonLocalizedLabel; 8528 res.icon = info.icon; 8529 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8530 return res; 8531 } 8532 8533 @Override 8534 protected void sortResults(List<ResolveInfo> results) { 8535 Collections.sort(results, mResolvePrioritySorter); 8536 } 8537 8538 @Override 8539 protected void dumpFilter(PrintWriter out, String prefix, 8540 PackageParser.ProviderIntentInfo filter) { 8541 out.print(prefix); 8542 out.print( 8543 Integer.toHexString(System.identityHashCode(filter.provider))); 8544 out.print(' '); 8545 filter.provider.printComponentShortName(out); 8546 out.print(" filter "); 8547 out.println(Integer.toHexString(System.identityHashCode(filter))); 8548 } 8549 8550 @Override 8551 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8552 return filter.provider; 8553 } 8554 8555 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8556 PackageParser.Provider provider = (PackageParser.Provider)label; 8557 out.print(prefix); out.print( 8558 Integer.toHexString(System.identityHashCode(provider))); 8559 out.print(' '); 8560 provider.printComponentShortName(out); 8561 if (count > 1) { 8562 out.print(" ("); out.print(count); out.print(" filters)"); 8563 } 8564 out.println(); 8565 } 8566 8567 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8568 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8569 private int mFlags; 8570 }; 8571 8572 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8573 new Comparator<ResolveInfo>() { 8574 public int compare(ResolveInfo r1, ResolveInfo r2) { 8575 int v1 = r1.priority; 8576 int v2 = r2.priority; 8577 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8578 if (v1 != v2) { 8579 return (v1 > v2) ? -1 : 1; 8580 } 8581 v1 = r1.preferredOrder; 8582 v2 = r2.preferredOrder; 8583 if (v1 != v2) { 8584 return (v1 > v2) ? -1 : 1; 8585 } 8586 if (r1.isDefault != r2.isDefault) { 8587 return r1.isDefault ? -1 : 1; 8588 } 8589 v1 = r1.match; 8590 v2 = r2.match; 8591 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8592 if (v1 != v2) { 8593 return (v1 > v2) ? -1 : 1; 8594 } 8595 if (r1.system != r2.system) { 8596 return r1.system ? -1 : 1; 8597 } 8598 return 0; 8599 } 8600 }; 8601 8602 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8603 new Comparator<ProviderInfo>() { 8604 public int compare(ProviderInfo p1, ProviderInfo p2) { 8605 final int v1 = p1.initOrder; 8606 final int v2 = p2.initOrder; 8607 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8608 } 8609 }; 8610 8611 final void sendPackageBroadcast(final String action, final String pkg, 8612 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8613 final int[] userIds) { 8614 mHandler.post(new Runnable() { 8615 @Override 8616 public void run() { 8617 try { 8618 final IActivityManager am = ActivityManagerNative.getDefault(); 8619 if (am == null) return; 8620 final int[] resolvedUserIds; 8621 if (userIds == null) { 8622 resolvedUserIds = am.getRunningUserIds(); 8623 } else { 8624 resolvedUserIds = userIds; 8625 } 8626 for (int id : resolvedUserIds) { 8627 final Intent intent = new Intent(action, 8628 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8629 if (extras != null) { 8630 intent.putExtras(extras); 8631 } 8632 if (targetPkg != null) { 8633 intent.setPackage(targetPkg); 8634 } 8635 // Modify the UID when posting to other users 8636 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8637 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8638 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8639 intent.putExtra(Intent.EXTRA_UID, uid); 8640 } 8641 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8642 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8643 if (DEBUG_BROADCASTS) { 8644 RuntimeException here = new RuntimeException("here"); 8645 here.fillInStackTrace(); 8646 Slog.d(TAG, "Sending to user " + id + ": " 8647 + intent.toShortString(false, true, false, false) 8648 + " " + intent.getExtras(), here); 8649 } 8650 am.broadcastIntent(null, intent, null, finishedReceiver, 8651 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8652 finishedReceiver != null, false, id); 8653 } 8654 } catch (RemoteException ex) { 8655 } 8656 } 8657 }); 8658 } 8659 8660 /** 8661 * Check if the external storage media is available. This is true if there 8662 * is a mounted external storage medium or if the external storage is 8663 * emulated. 8664 */ 8665 private boolean isExternalMediaAvailable() { 8666 return mMediaMounted || Environment.isExternalStorageEmulated(); 8667 } 8668 8669 @Override 8670 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8671 // writer 8672 synchronized (mPackages) { 8673 if (!isExternalMediaAvailable()) { 8674 // If the external storage is no longer mounted at this point, 8675 // the caller may not have been able to delete all of this 8676 // packages files and can not delete any more. Bail. 8677 return null; 8678 } 8679 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8680 if (lastPackage != null) { 8681 pkgs.remove(lastPackage); 8682 } 8683 if (pkgs.size() > 0) { 8684 return pkgs.get(0); 8685 } 8686 } 8687 return null; 8688 } 8689 8690 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8691 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8692 userId, andCode ? 1 : 0, packageName); 8693 if (mSystemReady) { 8694 msg.sendToTarget(); 8695 } else { 8696 if (mPostSystemReadyMessages == null) { 8697 mPostSystemReadyMessages = new ArrayList<>(); 8698 } 8699 mPostSystemReadyMessages.add(msg); 8700 } 8701 } 8702 8703 void startCleaningPackages() { 8704 // reader 8705 synchronized (mPackages) { 8706 if (!isExternalMediaAvailable()) { 8707 return; 8708 } 8709 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8710 return; 8711 } 8712 } 8713 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8714 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8715 IActivityManager am = ActivityManagerNative.getDefault(); 8716 if (am != null) { 8717 try { 8718 am.startService(null, intent, null, UserHandle.USER_OWNER); 8719 } catch (RemoteException e) { 8720 } 8721 } 8722 } 8723 8724 @Override 8725 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8726 int installFlags, String installerPackageName, VerificationParams verificationParams, 8727 String packageAbiOverride) { 8728 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8729 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8730 } 8731 8732 @Override 8733 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8734 int installFlags, String installerPackageName, VerificationParams verificationParams, 8735 String packageAbiOverride, int userId) { 8736 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8737 8738 final int callingUid = Binder.getCallingUid(); 8739 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8740 8741 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8742 try { 8743 if (observer != null) { 8744 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8745 } 8746 } catch (RemoteException re) { 8747 } 8748 return; 8749 } 8750 8751 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8752 installFlags |= PackageManager.INSTALL_FROM_ADB; 8753 8754 } else { 8755 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8756 // about installerPackageName. 8757 8758 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8759 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8760 } 8761 8762 UserHandle user; 8763 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8764 user = UserHandle.ALL; 8765 } else { 8766 user = new UserHandle(userId); 8767 } 8768 8769 // Only system components can circumvent runtime permissions when installing. 8770 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8771 && mContext.checkCallingOrSelfPermission(Manifest.permission 8772 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8773 throw new SecurityException("You need the " 8774 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8775 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8776 } 8777 8778 verificationParams.setInstallerUid(callingUid); 8779 8780 final File originFile = new File(originPath); 8781 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8782 8783 final Message msg = mHandler.obtainMessage(INIT_COPY); 8784 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8785 null, verificationParams, user, packageAbiOverride); 8786 mHandler.sendMessage(msg); 8787 } 8788 8789 void installStage(String packageName, File stagedDir, String stagedCid, 8790 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8791 String installerPackageName, int installerUid, UserHandle user) { 8792 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8793 params.referrerUri, installerUid, null); 8794 8795 final OriginInfo origin; 8796 if (stagedDir != null) { 8797 origin = OriginInfo.fromStagedFile(stagedDir); 8798 } else { 8799 origin = OriginInfo.fromStagedContainer(stagedCid); 8800 } 8801 8802 final Message msg = mHandler.obtainMessage(INIT_COPY); 8803 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8804 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8805 mHandler.sendMessage(msg); 8806 } 8807 8808 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8809 Bundle extras = new Bundle(1); 8810 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8811 8812 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8813 packageName, extras, null, null, new int[] {userId}); 8814 try { 8815 IActivityManager am = ActivityManagerNative.getDefault(); 8816 final boolean isSystem = 8817 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8818 if (isSystem && am.isUserRunning(userId, false)) { 8819 // The just-installed/enabled app is bundled on the system, so presumed 8820 // to be able to run automatically without needing an explicit launch. 8821 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8822 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8823 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8824 .setPackage(packageName); 8825 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8826 android.app.AppOpsManager.OP_NONE, false, false, userId); 8827 } 8828 } catch (RemoteException e) { 8829 // shouldn't happen 8830 Slog.w(TAG, "Unable to bootstrap installed package", e); 8831 } 8832 } 8833 8834 @Override 8835 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8836 int userId) { 8837 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8838 PackageSetting pkgSetting; 8839 final int uid = Binder.getCallingUid(); 8840 enforceCrossUserPermission(uid, userId, true, true, 8841 "setApplicationHiddenSetting for user " + userId); 8842 8843 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8844 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8845 return false; 8846 } 8847 8848 long callingId = Binder.clearCallingIdentity(); 8849 try { 8850 boolean sendAdded = false; 8851 boolean sendRemoved = false; 8852 // writer 8853 synchronized (mPackages) { 8854 pkgSetting = mSettings.mPackages.get(packageName); 8855 if (pkgSetting == null) { 8856 return false; 8857 } 8858 if (pkgSetting.getHidden(userId) != hidden) { 8859 pkgSetting.setHidden(hidden, userId); 8860 mSettings.writePackageRestrictionsLPr(userId); 8861 if (hidden) { 8862 sendRemoved = true; 8863 } else { 8864 sendAdded = true; 8865 } 8866 } 8867 } 8868 if (sendAdded) { 8869 sendPackageAddedForUser(packageName, pkgSetting, userId); 8870 return true; 8871 } 8872 if (sendRemoved) { 8873 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8874 "hiding pkg"); 8875 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8876 } 8877 } finally { 8878 Binder.restoreCallingIdentity(callingId); 8879 } 8880 return false; 8881 } 8882 8883 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8884 int userId) { 8885 final PackageRemovedInfo info = new PackageRemovedInfo(); 8886 info.removedPackage = packageName; 8887 info.removedUsers = new int[] {userId}; 8888 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8889 info.sendBroadcast(false, false, false); 8890 } 8891 8892 /** 8893 * Returns true if application is not found or there was an error. Otherwise it returns 8894 * the hidden state of the package for the given user. 8895 */ 8896 @Override 8897 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8898 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8899 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8900 false, "getApplicationHidden for user " + userId); 8901 PackageSetting pkgSetting; 8902 long callingId = Binder.clearCallingIdentity(); 8903 try { 8904 // writer 8905 synchronized (mPackages) { 8906 pkgSetting = mSettings.mPackages.get(packageName); 8907 if (pkgSetting == null) { 8908 return true; 8909 } 8910 return pkgSetting.getHidden(userId); 8911 } 8912 } finally { 8913 Binder.restoreCallingIdentity(callingId); 8914 } 8915 } 8916 8917 /** 8918 * @hide 8919 */ 8920 @Override 8921 public int installExistingPackageAsUser(String packageName, int userId) { 8922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8923 null); 8924 PackageSetting pkgSetting; 8925 final int uid = Binder.getCallingUid(); 8926 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8927 + userId); 8928 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8929 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8930 } 8931 8932 long callingId = Binder.clearCallingIdentity(); 8933 try { 8934 boolean sendAdded = false; 8935 8936 // writer 8937 synchronized (mPackages) { 8938 pkgSetting = mSettings.mPackages.get(packageName); 8939 if (pkgSetting == null) { 8940 return PackageManager.INSTALL_FAILED_INVALID_URI; 8941 } 8942 if (!pkgSetting.getInstalled(userId)) { 8943 pkgSetting.setInstalled(true, userId); 8944 pkgSetting.setHidden(false, userId); 8945 mSettings.writePackageRestrictionsLPr(userId); 8946 sendAdded = true; 8947 } 8948 } 8949 8950 if (sendAdded) { 8951 sendPackageAddedForUser(packageName, pkgSetting, userId); 8952 } 8953 } finally { 8954 Binder.restoreCallingIdentity(callingId); 8955 } 8956 8957 return PackageManager.INSTALL_SUCCEEDED; 8958 } 8959 8960 boolean isUserRestricted(int userId, String restrictionKey) { 8961 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8962 if (restrictions.getBoolean(restrictionKey, false)) { 8963 Log.w(TAG, "User is restricted: " + restrictionKey); 8964 return true; 8965 } 8966 return false; 8967 } 8968 8969 @Override 8970 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8971 mContext.enforceCallingOrSelfPermission( 8972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8973 "Only package verification agents can verify applications"); 8974 8975 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8976 final PackageVerificationResponse response = new PackageVerificationResponse( 8977 verificationCode, Binder.getCallingUid()); 8978 msg.arg1 = id; 8979 msg.obj = response; 8980 mHandler.sendMessage(msg); 8981 } 8982 8983 @Override 8984 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8985 long millisecondsToDelay) { 8986 mContext.enforceCallingOrSelfPermission( 8987 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8988 "Only package verification agents can extend verification timeouts"); 8989 8990 final PackageVerificationState state = mPendingVerification.get(id); 8991 final PackageVerificationResponse response = new PackageVerificationResponse( 8992 verificationCodeAtTimeout, Binder.getCallingUid()); 8993 8994 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8995 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8996 } 8997 if (millisecondsToDelay < 0) { 8998 millisecondsToDelay = 0; 8999 } 9000 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9001 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9002 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9003 } 9004 9005 if ((state != null) && !state.timeoutExtended()) { 9006 state.extendTimeout(); 9007 9008 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9009 msg.arg1 = id; 9010 msg.obj = response; 9011 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9012 } 9013 } 9014 9015 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9016 int verificationCode, UserHandle user) { 9017 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9018 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9019 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9020 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9021 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9022 9023 mContext.sendBroadcastAsUser(intent, user, 9024 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9025 } 9026 9027 private ComponentName matchComponentForVerifier(String packageName, 9028 List<ResolveInfo> receivers) { 9029 ActivityInfo targetReceiver = null; 9030 9031 final int NR = receivers.size(); 9032 for (int i = 0; i < NR; i++) { 9033 final ResolveInfo info = receivers.get(i); 9034 if (info.activityInfo == null) { 9035 continue; 9036 } 9037 9038 if (packageName.equals(info.activityInfo.packageName)) { 9039 targetReceiver = info.activityInfo; 9040 break; 9041 } 9042 } 9043 9044 if (targetReceiver == null) { 9045 return null; 9046 } 9047 9048 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9049 } 9050 9051 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9052 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9053 if (pkgInfo.verifiers.length == 0) { 9054 return null; 9055 } 9056 9057 final int N = pkgInfo.verifiers.length; 9058 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9059 for (int i = 0; i < N; i++) { 9060 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9061 9062 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9063 receivers); 9064 if (comp == null) { 9065 continue; 9066 } 9067 9068 final int verifierUid = getUidForVerifier(verifierInfo); 9069 if (verifierUid == -1) { 9070 continue; 9071 } 9072 9073 if (DEBUG_VERIFY) { 9074 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9075 + " with the correct signature"); 9076 } 9077 sufficientVerifiers.add(comp); 9078 verificationState.addSufficientVerifier(verifierUid); 9079 } 9080 9081 return sufficientVerifiers; 9082 } 9083 9084 private int getUidForVerifier(VerifierInfo verifierInfo) { 9085 synchronized (mPackages) { 9086 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9087 if (pkg == null) { 9088 return -1; 9089 } else if (pkg.mSignatures.length != 1) { 9090 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9091 + " has more than one signature; ignoring"); 9092 return -1; 9093 } 9094 9095 /* 9096 * If the public key of the package's signature does not match 9097 * our expected public key, then this is a different package and 9098 * we should skip. 9099 */ 9100 9101 final byte[] expectedPublicKey; 9102 try { 9103 final Signature verifierSig = pkg.mSignatures[0]; 9104 final PublicKey publicKey = verifierSig.getPublicKey(); 9105 expectedPublicKey = publicKey.getEncoded(); 9106 } catch (CertificateException e) { 9107 return -1; 9108 } 9109 9110 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9111 9112 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9113 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9114 + " does not have the expected public key; ignoring"); 9115 return -1; 9116 } 9117 9118 return pkg.applicationInfo.uid; 9119 } 9120 } 9121 9122 @Override 9123 public void finishPackageInstall(int token) { 9124 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9125 9126 if (DEBUG_INSTALL) { 9127 Slog.v(TAG, "BM finishing package install for " + token); 9128 } 9129 9130 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9131 mHandler.sendMessage(msg); 9132 } 9133 9134 /** 9135 * Get the verification agent timeout. 9136 * 9137 * @return verification timeout in milliseconds 9138 */ 9139 private long getVerificationTimeout() { 9140 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9141 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9142 DEFAULT_VERIFICATION_TIMEOUT); 9143 } 9144 9145 /** 9146 * Get the default verification agent response code. 9147 * 9148 * @return default verification response code 9149 */ 9150 private int getDefaultVerificationResponse() { 9151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9152 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9153 DEFAULT_VERIFICATION_RESPONSE); 9154 } 9155 9156 /** 9157 * Check whether or not package verification has been enabled. 9158 * 9159 * @return true if verification should be performed 9160 */ 9161 private boolean isVerificationEnabled(int userId, int installFlags) { 9162 if (!DEFAULT_VERIFY_ENABLE) { 9163 return false; 9164 } 9165 9166 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9167 9168 // Check if installing from ADB 9169 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9170 // Do not run verification in a test harness environment 9171 if (ActivityManager.isRunningInTestHarness()) { 9172 return false; 9173 } 9174 if (ensureVerifyAppsEnabled) { 9175 return true; 9176 } 9177 // Check if the developer does not want package verification for ADB installs 9178 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9179 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9180 return false; 9181 } 9182 } 9183 9184 if (ensureVerifyAppsEnabled) { 9185 return true; 9186 } 9187 9188 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9189 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9190 } 9191 9192 @Override 9193 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9194 throws RemoteException { 9195 mContext.enforceCallingOrSelfPermission( 9196 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9197 "Only intentfilter verification agents can verify applications"); 9198 9199 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9200 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9201 Binder.getCallingUid(), verificationCode, failedDomains); 9202 msg.arg1 = id; 9203 msg.obj = response; 9204 mHandler.sendMessage(msg); 9205 } 9206 9207 @Override 9208 public int getIntentVerificationStatus(String packageName, int userId) { 9209 synchronized (mPackages) { 9210 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9211 } 9212 } 9213 9214 @Override 9215 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9216 boolean result = false; 9217 synchronized (mPackages) { 9218 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9219 } 9220 if (result) { 9221 scheduleWritePackageRestrictionsLocked(userId); 9222 } 9223 return result; 9224 } 9225 9226 @Override 9227 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9228 synchronized (mPackages) { 9229 return mSettings.getIntentFilterVerificationsLPr(packageName); 9230 } 9231 } 9232 9233 @Override 9234 public List<IntentFilter> getAllIntentFilters(String packageName) { 9235 if (TextUtils.isEmpty(packageName)) { 9236 return Collections.<IntentFilter>emptyList(); 9237 } 9238 synchronized (mPackages) { 9239 PackageParser.Package pkg = mPackages.get(packageName); 9240 if (pkg == null || pkg.activities == null) { 9241 return Collections.<IntentFilter>emptyList(); 9242 } 9243 final int count = pkg.activities.size(); 9244 ArrayList<IntentFilter> result = new ArrayList<>(); 9245 for (int n=0; n<count; n++) { 9246 PackageParser.Activity activity = pkg.activities.get(n); 9247 if (activity.intents != null || activity.intents.size() > 0) { 9248 result.addAll(activity.intents); 9249 } 9250 } 9251 return result; 9252 } 9253 } 9254 9255 @Override 9256 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9257 synchronized (mPackages) { 9258 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9259 if (packageName != null) { 9260 result |= updateIntentVerificationStatus(packageName, 9261 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9262 UserHandle.myUserId()); 9263 } 9264 return result; 9265 } 9266 } 9267 9268 @Override 9269 public String getDefaultBrowserPackageName(int userId) { 9270 synchronized (mPackages) { 9271 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9272 } 9273 } 9274 9275 /** 9276 * Get the "allow unknown sources" setting. 9277 * 9278 * @return the current "allow unknown sources" setting 9279 */ 9280 private int getUnknownSourcesSettings() { 9281 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9282 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9283 -1); 9284 } 9285 9286 @Override 9287 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9288 final int uid = Binder.getCallingUid(); 9289 // writer 9290 synchronized (mPackages) { 9291 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9292 if (targetPackageSetting == null) { 9293 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9294 } 9295 9296 PackageSetting installerPackageSetting; 9297 if (installerPackageName != null) { 9298 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9299 if (installerPackageSetting == null) { 9300 throw new IllegalArgumentException("Unknown installer package: " 9301 + installerPackageName); 9302 } 9303 } else { 9304 installerPackageSetting = null; 9305 } 9306 9307 Signature[] callerSignature; 9308 Object obj = mSettings.getUserIdLPr(uid); 9309 if (obj != null) { 9310 if (obj instanceof SharedUserSetting) { 9311 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9312 } else if (obj instanceof PackageSetting) { 9313 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9314 } else { 9315 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9316 } 9317 } else { 9318 throw new SecurityException("Unknown calling uid " + uid); 9319 } 9320 9321 // Verify: can't set installerPackageName to a package that is 9322 // not signed with the same cert as the caller. 9323 if (installerPackageSetting != null) { 9324 if (compareSignatures(callerSignature, 9325 installerPackageSetting.signatures.mSignatures) 9326 != PackageManager.SIGNATURE_MATCH) { 9327 throw new SecurityException( 9328 "Caller does not have same cert as new installer package " 9329 + installerPackageName); 9330 } 9331 } 9332 9333 // Verify: if target already has an installer package, it must 9334 // be signed with the same cert as the caller. 9335 if (targetPackageSetting.installerPackageName != null) { 9336 PackageSetting setting = mSettings.mPackages.get( 9337 targetPackageSetting.installerPackageName); 9338 // If the currently set package isn't valid, then it's always 9339 // okay to change it. 9340 if (setting != null) { 9341 if (compareSignatures(callerSignature, 9342 setting.signatures.mSignatures) 9343 != PackageManager.SIGNATURE_MATCH) { 9344 throw new SecurityException( 9345 "Caller does not have same cert as old installer package " 9346 + targetPackageSetting.installerPackageName); 9347 } 9348 } 9349 } 9350 9351 // Okay! 9352 targetPackageSetting.installerPackageName = installerPackageName; 9353 scheduleWriteSettingsLocked(); 9354 } 9355 } 9356 9357 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9358 // Queue up an async operation since the package installation may take a little while. 9359 mHandler.post(new Runnable() { 9360 public void run() { 9361 mHandler.removeCallbacks(this); 9362 // Result object to be returned 9363 PackageInstalledInfo res = new PackageInstalledInfo(); 9364 res.returnCode = currentStatus; 9365 res.uid = -1; 9366 res.pkg = null; 9367 res.removedInfo = new PackageRemovedInfo(); 9368 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9369 args.doPreInstall(res.returnCode); 9370 synchronized (mInstallLock) { 9371 installPackageLI(args, res); 9372 } 9373 args.doPostInstall(res.returnCode, res.uid); 9374 } 9375 9376 // A restore should be performed at this point if (a) the install 9377 // succeeded, (b) the operation is not an update, and (c) the new 9378 // package has not opted out of backup participation. 9379 final boolean update = res.removedInfo.removedPackage != null; 9380 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9381 boolean doRestore = !update 9382 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9383 9384 // Set up the post-install work request bookkeeping. This will be used 9385 // and cleaned up by the post-install event handling regardless of whether 9386 // there's a restore pass performed. Token values are >= 1. 9387 int token; 9388 if (mNextInstallToken < 0) mNextInstallToken = 1; 9389 token = mNextInstallToken++; 9390 9391 PostInstallData data = new PostInstallData(args, res); 9392 mRunningInstalls.put(token, data); 9393 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9394 9395 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9396 // Pass responsibility to the Backup Manager. It will perform a 9397 // restore if appropriate, then pass responsibility back to the 9398 // Package Manager to run the post-install observer callbacks 9399 // and broadcasts. 9400 IBackupManager bm = IBackupManager.Stub.asInterface( 9401 ServiceManager.getService(Context.BACKUP_SERVICE)); 9402 if (bm != null) { 9403 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9404 + " to BM for possible restore"); 9405 try { 9406 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9407 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9408 } else { 9409 doRestore = false; 9410 } 9411 } catch (RemoteException e) { 9412 // can't happen; the backup manager is local 9413 } catch (Exception e) { 9414 Slog.e(TAG, "Exception trying to enqueue restore", e); 9415 doRestore = false; 9416 } 9417 } else { 9418 Slog.e(TAG, "Backup Manager not found!"); 9419 doRestore = false; 9420 } 9421 } 9422 9423 if (!doRestore) { 9424 // No restore possible, or the Backup Manager was mysteriously not 9425 // available -- just fire the post-install work request directly. 9426 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9427 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9428 mHandler.sendMessage(msg); 9429 } 9430 } 9431 }); 9432 } 9433 9434 private abstract class HandlerParams { 9435 private static final int MAX_RETRIES = 4; 9436 9437 /** 9438 * Number of times startCopy() has been attempted and had a non-fatal 9439 * error. 9440 */ 9441 private int mRetries = 0; 9442 9443 /** User handle for the user requesting the information or installation. */ 9444 private final UserHandle mUser; 9445 9446 HandlerParams(UserHandle user) { 9447 mUser = user; 9448 } 9449 9450 UserHandle getUser() { 9451 return mUser; 9452 } 9453 9454 final boolean startCopy() { 9455 boolean res; 9456 try { 9457 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9458 9459 if (++mRetries > MAX_RETRIES) { 9460 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9461 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9462 handleServiceError(); 9463 return false; 9464 } else { 9465 handleStartCopy(); 9466 res = true; 9467 } 9468 } catch (RemoteException e) { 9469 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9470 mHandler.sendEmptyMessage(MCS_RECONNECT); 9471 res = false; 9472 } 9473 handleReturnCode(); 9474 return res; 9475 } 9476 9477 final void serviceError() { 9478 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9479 handleServiceError(); 9480 handleReturnCode(); 9481 } 9482 9483 abstract void handleStartCopy() throws RemoteException; 9484 abstract void handleServiceError(); 9485 abstract void handleReturnCode(); 9486 } 9487 9488 class MeasureParams extends HandlerParams { 9489 private final PackageStats mStats; 9490 private boolean mSuccess; 9491 9492 private final IPackageStatsObserver mObserver; 9493 9494 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9495 super(new UserHandle(stats.userHandle)); 9496 mObserver = observer; 9497 mStats = stats; 9498 } 9499 9500 @Override 9501 public String toString() { 9502 return "MeasureParams{" 9503 + Integer.toHexString(System.identityHashCode(this)) 9504 + " " + mStats.packageName + "}"; 9505 } 9506 9507 @Override 9508 void handleStartCopy() throws RemoteException { 9509 synchronized (mInstallLock) { 9510 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9511 } 9512 9513 if (mSuccess) { 9514 final boolean mounted; 9515 if (Environment.isExternalStorageEmulated()) { 9516 mounted = true; 9517 } else { 9518 final String status = Environment.getExternalStorageState(); 9519 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9520 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9521 } 9522 9523 if (mounted) { 9524 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9525 9526 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9527 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9528 9529 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9530 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9531 9532 // Always subtract cache size, since it's a subdirectory 9533 mStats.externalDataSize -= mStats.externalCacheSize; 9534 9535 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9536 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9537 9538 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9539 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9540 } 9541 } 9542 } 9543 9544 @Override 9545 void handleReturnCode() { 9546 if (mObserver != null) { 9547 try { 9548 mObserver.onGetStatsCompleted(mStats, mSuccess); 9549 } catch (RemoteException e) { 9550 Slog.i(TAG, "Observer no longer exists."); 9551 } 9552 } 9553 } 9554 9555 @Override 9556 void handleServiceError() { 9557 Slog.e(TAG, "Could not measure application " + mStats.packageName 9558 + " external storage"); 9559 } 9560 } 9561 9562 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9563 throws RemoteException { 9564 long result = 0; 9565 for (File path : paths) { 9566 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9567 } 9568 return result; 9569 } 9570 9571 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9572 for (File path : paths) { 9573 try { 9574 mcs.clearDirectory(path.getAbsolutePath()); 9575 } catch (RemoteException e) { 9576 } 9577 } 9578 } 9579 9580 static class OriginInfo { 9581 /** 9582 * Location where install is coming from, before it has been 9583 * copied/renamed into place. This could be a single monolithic APK 9584 * file, or a cluster directory. This location may be untrusted. 9585 */ 9586 final File file; 9587 final String cid; 9588 9589 /** 9590 * Flag indicating that {@link #file} or {@link #cid} has already been 9591 * staged, meaning downstream users don't need to defensively copy the 9592 * contents. 9593 */ 9594 final boolean staged; 9595 9596 /** 9597 * Flag indicating that {@link #file} or {@link #cid} is an already 9598 * installed app that is being moved. 9599 */ 9600 final boolean existing; 9601 9602 final String resolvedPath; 9603 final File resolvedFile; 9604 9605 static OriginInfo fromNothing() { 9606 return new OriginInfo(null, null, false, false); 9607 } 9608 9609 static OriginInfo fromUntrustedFile(File file) { 9610 return new OriginInfo(file, null, false, false); 9611 } 9612 9613 static OriginInfo fromExistingFile(File file) { 9614 return new OriginInfo(file, null, false, true); 9615 } 9616 9617 static OriginInfo fromStagedFile(File file) { 9618 return new OriginInfo(file, null, true, false); 9619 } 9620 9621 static OriginInfo fromStagedContainer(String cid) { 9622 return new OriginInfo(null, cid, true, false); 9623 } 9624 9625 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9626 this.file = file; 9627 this.cid = cid; 9628 this.staged = staged; 9629 this.existing = existing; 9630 9631 if (cid != null) { 9632 resolvedPath = PackageHelper.getSdDir(cid); 9633 resolvedFile = new File(resolvedPath); 9634 } else if (file != null) { 9635 resolvedPath = file.getAbsolutePath(); 9636 resolvedFile = file; 9637 } else { 9638 resolvedPath = null; 9639 resolvedFile = null; 9640 } 9641 } 9642 } 9643 9644 class MoveInfo { 9645 final int moveId; 9646 final String fromUuid; 9647 final String toUuid; 9648 final String packageName; 9649 final String dataAppName; 9650 final int appId; 9651 final String seinfo; 9652 9653 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9654 String dataAppName, int appId, String seinfo) { 9655 this.moveId = moveId; 9656 this.fromUuid = fromUuid; 9657 this.toUuid = toUuid; 9658 this.packageName = packageName; 9659 this.dataAppName = dataAppName; 9660 this.appId = appId; 9661 this.seinfo = seinfo; 9662 } 9663 } 9664 9665 class InstallParams extends HandlerParams { 9666 final OriginInfo origin; 9667 final MoveInfo move; 9668 final IPackageInstallObserver2 observer; 9669 int installFlags; 9670 final String installerPackageName; 9671 final String volumeUuid; 9672 final VerificationParams verificationParams; 9673 private InstallArgs mArgs; 9674 private int mRet; 9675 final String packageAbiOverride; 9676 9677 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9678 int installFlags, String installerPackageName, String volumeUuid, 9679 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9680 super(user); 9681 this.origin = origin; 9682 this.move = move; 9683 this.observer = observer; 9684 this.installFlags = installFlags; 9685 this.installerPackageName = installerPackageName; 9686 this.volumeUuid = volumeUuid; 9687 this.verificationParams = verificationParams; 9688 this.packageAbiOverride = packageAbiOverride; 9689 } 9690 9691 @Override 9692 public String toString() { 9693 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9694 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9695 } 9696 9697 public ManifestDigest getManifestDigest() { 9698 if (verificationParams == null) { 9699 return null; 9700 } 9701 return verificationParams.getManifestDigest(); 9702 } 9703 9704 private int installLocationPolicy(PackageInfoLite pkgLite) { 9705 String packageName = pkgLite.packageName; 9706 int installLocation = pkgLite.installLocation; 9707 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9708 // reader 9709 synchronized (mPackages) { 9710 PackageParser.Package pkg = mPackages.get(packageName); 9711 if (pkg != null) { 9712 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9713 // Check for downgrading. 9714 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9715 try { 9716 checkDowngrade(pkg, pkgLite); 9717 } catch (PackageManagerException e) { 9718 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9719 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9720 } 9721 } 9722 // Check for updated system application. 9723 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9724 if (onSd) { 9725 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9726 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9727 } 9728 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9729 } else { 9730 if (onSd) { 9731 // Install flag overrides everything. 9732 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9733 } 9734 // If current upgrade specifies particular preference 9735 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9736 // Application explicitly specified internal. 9737 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9738 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9739 // App explictly prefers external. Let policy decide 9740 } else { 9741 // Prefer previous location 9742 if (isExternal(pkg)) { 9743 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9744 } 9745 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9746 } 9747 } 9748 } else { 9749 // Invalid install. Return error code 9750 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9751 } 9752 } 9753 } 9754 // All the special cases have been taken care of. 9755 // Return result based on recommended install location. 9756 if (onSd) { 9757 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9758 } 9759 return pkgLite.recommendedInstallLocation; 9760 } 9761 9762 /* 9763 * Invoke remote method to get package information and install 9764 * location values. Override install location based on default 9765 * policy if needed and then create install arguments based 9766 * on the install location. 9767 */ 9768 public void handleStartCopy() throws RemoteException { 9769 int ret = PackageManager.INSTALL_SUCCEEDED; 9770 9771 // If we're already staged, we've firmly committed to an install location 9772 if (origin.staged) { 9773 if (origin.file != null) { 9774 installFlags |= PackageManager.INSTALL_INTERNAL; 9775 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9776 } else if (origin.cid != null) { 9777 installFlags |= PackageManager.INSTALL_EXTERNAL; 9778 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9779 } else { 9780 throw new IllegalStateException("Invalid stage location"); 9781 } 9782 } 9783 9784 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9785 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9786 9787 PackageInfoLite pkgLite = null; 9788 9789 if (onInt && onSd) { 9790 // Check if both bits are set. 9791 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9792 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9793 } else { 9794 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9795 packageAbiOverride); 9796 9797 /* 9798 * If we have too little free space, try to free cache 9799 * before giving up. 9800 */ 9801 if (!origin.staged && pkgLite.recommendedInstallLocation 9802 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9803 // TODO: focus freeing disk space on the target device 9804 final StorageManager storage = StorageManager.from(mContext); 9805 final long lowThreshold = storage.getStorageLowBytes( 9806 Environment.getDataDirectory()); 9807 9808 final long sizeBytes = mContainerService.calculateInstalledSize( 9809 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9810 9811 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9812 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9813 installFlags, packageAbiOverride); 9814 } 9815 9816 /* 9817 * The cache free must have deleted the file we 9818 * downloaded to install. 9819 * 9820 * TODO: fix the "freeCache" call to not delete 9821 * the file we care about. 9822 */ 9823 if (pkgLite.recommendedInstallLocation 9824 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9825 pkgLite.recommendedInstallLocation 9826 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9827 } 9828 } 9829 } 9830 9831 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9832 int loc = pkgLite.recommendedInstallLocation; 9833 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9834 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9835 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9836 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9837 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9838 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9839 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9840 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9841 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9842 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9843 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9844 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9845 } else { 9846 // Override with defaults if needed. 9847 loc = installLocationPolicy(pkgLite); 9848 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9849 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9850 } else if (!onSd && !onInt) { 9851 // Override install location with flags 9852 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9853 // Set the flag to install on external media. 9854 installFlags |= PackageManager.INSTALL_EXTERNAL; 9855 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9856 } else { 9857 // Make sure the flag for installing on external 9858 // media is unset 9859 installFlags |= PackageManager.INSTALL_INTERNAL; 9860 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9861 } 9862 } 9863 } 9864 } 9865 9866 final InstallArgs args = createInstallArgs(this); 9867 mArgs = args; 9868 9869 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9870 /* 9871 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9872 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9873 */ 9874 int userIdentifier = getUser().getIdentifier(); 9875 if (userIdentifier == UserHandle.USER_ALL 9876 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9877 userIdentifier = UserHandle.USER_OWNER; 9878 } 9879 9880 /* 9881 * Determine if we have any installed package verifiers. If we 9882 * do, then we'll defer to them to verify the packages. 9883 */ 9884 final int requiredUid = mRequiredVerifierPackage == null ? -1 9885 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9886 if (!origin.existing && requiredUid != -1 9887 && isVerificationEnabled(userIdentifier, installFlags)) { 9888 final Intent verification = new Intent( 9889 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9890 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9891 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9892 PACKAGE_MIME_TYPE); 9893 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9894 9895 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9896 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9897 0 /* TODO: Which userId? */); 9898 9899 if (DEBUG_VERIFY) { 9900 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9901 + verification.toString() + " with " + pkgLite.verifiers.length 9902 + " optional verifiers"); 9903 } 9904 9905 final int verificationId = mPendingVerificationToken++; 9906 9907 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9908 9909 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9910 installerPackageName); 9911 9912 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9913 installFlags); 9914 9915 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9916 pkgLite.packageName); 9917 9918 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9919 pkgLite.versionCode); 9920 9921 if (verificationParams != null) { 9922 if (verificationParams.getVerificationURI() != null) { 9923 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9924 verificationParams.getVerificationURI()); 9925 } 9926 if (verificationParams.getOriginatingURI() != null) { 9927 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9928 verificationParams.getOriginatingURI()); 9929 } 9930 if (verificationParams.getReferrer() != null) { 9931 verification.putExtra(Intent.EXTRA_REFERRER, 9932 verificationParams.getReferrer()); 9933 } 9934 if (verificationParams.getOriginatingUid() >= 0) { 9935 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9936 verificationParams.getOriginatingUid()); 9937 } 9938 if (verificationParams.getInstallerUid() >= 0) { 9939 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9940 verificationParams.getInstallerUid()); 9941 } 9942 } 9943 9944 final PackageVerificationState verificationState = new PackageVerificationState( 9945 requiredUid, args); 9946 9947 mPendingVerification.append(verificationId, verificationState); 9948 9949 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9950 receivers, verificationState); 9951 9952 /* 9953 * If any sufficient verifiers were listed in the package 9954 * manifest, attempt to ask them. 9955 */ 9956 if (sufficientVerifiers != null) { 9957 final int N = sufficientVerifiers.size(); 9958 if (N == 0) { 9959 Slog.i(TAG, "Additional verifiers required, but none installed."); 9960 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9961 } else { 9962 for (int i = 0; i < N; i++) { 9963 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9964 9965 final Intent sufficientIntent = new Intent(verification); 9966 sufficientIntent.setComponent(verifierComponent); 9967 9968 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9969 } 9970 } 9971 } 9972 9973 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9974 mRequiredVerifierPackage, receivers); 9975 if (ret == PackageManager.INSTALL_SUCCEEDED 9976 && mRequiredVerifierPackage != null) { 9977 /* 9978 * Send the intent to the required verification agent, 9979 * but only start the verification timeout after the 9980 * target BroadcastReceivers have run. 9981 */ 9982 verification.setComponent(requiredVerifierComponent); 9983 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9984 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9985 new BroadcastReceiver() { 9986 @Override 9987 public void onReceive(Context context, Intent intent) { 9988 final Message msg = mHandler 9989 .obtainMessage(CHECK_PENDING_VERIFICATION); 9990 msg.arg1 = verificationId; 9991 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9992 } 9993 }, null, 0, null, null); 9994 9995 /* 9996 * We don't want the copy to proceed until verification 9997 * succeeds, so null out this field. 9998 */ 9999 mArgs = null; 10000 } 10001 } else { 10002 /* 10003 * No package verification is enabled, so immediately start 10004 * the remote call to initiate copy using temporary file. 10005 */ 10006 ret = args.copyApk(mContainerService, true); 10007 } 10008 } 10009 10010 mRet = ret; 10011 } 10012 10013 @Override 10014 void handleReturnCode() { 10015 // If mArgs is null, then MCS couldn't be reached. When it 10016 // reconnects, it will try again to install. At that point, this 10017 // will succeed. 10018 if (mArgs != null) { 10019 processPendingInstall(mArgs, mRet); 10020 } 10021 } 10022 10023 @Override 10024 void handleServiceError() { 10025 mArgs = createInstallArgs(this); 10026 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10027 } 10028 10029 public boolean isForwardLocked() { 10030 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10031 } 10032 } 10033 10034 /** 10035 * Used during creation of InstallArgs 10036 * 10037 * @param installFlags package installation flags 10038 * @return true if should be installed on external storage 10039 */ 10040 private static boolean installOnExternalAsec(int installFlags) { 10041 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10042 return false; 10043 } 10044 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10045 return true; 10046 } 10047 return false; 10048 } 10049 10050 /** 10051 * Used during creation of InstallArgs 10052 * 10053 * @param installFlags package installation flags 10054 * @return true if should be installed as forward locked 10055 */ 10056 private static boolean installForwardLocked(int installFlags) { 10057 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10058 } 10059 10060 private InstallArgs createInstallArgs(InstallParams params) { 10061 if (params.move != null) { 10062 return new MoveInstallArgs(params); 10063 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10064 return new AsecInstallArgs(params); 10065 } else { 10066 return new FileInstallArgs(params); 10067 } 10068 } 10069 10070 /** 10071 * Create args that describe an existing installed package. Typically used 10072 * when cleaning up old installs, or used as a move source. 10073 */ 10074 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10075 String resourcePath, String[] instructionSets) { 10076 final boolean isInAsec; 10077 if (installOnExternalAsec(installFlags)) { 10078 /* Apps on SD card are always in ASEC containers. */ 10079 isInAsec = true; 10080 } else if (installForwardLocked(installFlags) 10081 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10082 /* 10083 * Forward-locked apps are only in ASEC containers if they're the 10084 * new style 10085 */ 10086 isInAsec = true; 10087 } else { 10088 isInAsec = false; 10089 } 10090 10091 if (isInAsec) { 10092 return new AsecInstallArgs(codePath, instructionSets, 10093 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10094 } else { 10095 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10096 } 10097 } 10098 10099 static abstract class InstallArgs { 10100 /** @see InstallParams#origin */ 10101 final OriginInfo origin; 10102 /** @see InstallParams#move */ 10103 final MoveInfo move; 10104 10105 final IPackageInstallObserver2 observer; 10106 // Always refers to PackageManager flags only 10107 final int installFlags; 10108 final String installerPackageName; 10109 final String volumeUuid; 10110 final ManifestDigest manifestDigest; 10111 final UserHandle user; 10112 final String abiOverride; 10113 10114 // The list of instruction sets supported by this app. This is currently 10115 // only used during the rmdex() phase to clean up resources. We can get rid of this 10116 // if we move dex files under the common app path. 10117 /* nullable */ String[] instructionSets; 10118 10119 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10120 int installFlags, String installerPackageName, String volumeUuid, 10121 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10122 String abiOverride) { 10123 this.origin = origin; 10124 this.move = move; 10125 this.installFlags = installFlags; 10126 this.observer = observer; 10127 this.installerPackageName = installerPackageName; 10128 this.volumeUuid = volumeUuid; 10129 this.manifestDigest = manifestDigest; 10130 this.user = user; 10131 this.instructionSets = instructionSets; 10132 this.abiOverride = abiOverride; 10133 } 10134 10135 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10136 abstract int doPreInstall(int status); 10137 10138 /** 10139 * Rename package into final resting place. All paths on the given 10140 * scanned package should be updated to reflect the rename. 10141 */ 10142 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10143 abstract int doPostInstall(int status, int uid); 10144 10145 /** @see PackageSettingBase#codePathString */ 10146 abstract String getCodePath(); 10147 /** @see PackageSettingBase#resourcePathString */ 10148 abstract String getResourcePath(); 10149 10150 // Need installer lock especially for dex file removal. 10151 abstract void cleanUpResourcesLI(); 10152 abstract boolean doPostDeleteLI(boolean delete); 10153 10154 /** 10155 * Called before the source arguments are copied. This is used mostly 10156 * for MoveParams when it needs to read the source file to put it in the 10157 * destination. 10158 */ 10159 int doPreCopy() { 10160 return PackageManager.INSTALL_SUCCEEDED; 10161 } 10162 10163 /** 10164 * Called after the source arguments are copied. This is used mostly for 10165 * MoveParams when it needs to read the source file to put it in the 10166 * destination. 10167 * 10168 * @return 10169 */ 10170 int doPostCopy(int uid) { 10171 return PackageManager.INSTALL_SUCCEEDED; 10172 } 10173 10174 protected boolean isFwdLocked() { 10175 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10176 } 10177 10178 protected boolean isExternalAsec() { 10179 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10180 } 10181 10182 UserHandle getUser() { 10183 return user; 10184 } 10185 } 10186 10187 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10188 if (!allCodePaths.isEmpty()) { 10189 if (instructionSets == null) { 10190 throw new IllegalStateException("instructionSet == null"); 10191 } 10192 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10193 for (String codePath : allCodePaths) { 10194 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10195 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10196 if (retCode < 0) { 10197 Slog.w(TAG, "Couldn't remove dex file for package: " 10198 + " at location " + codePath + ", retcode=" + retCode); 10199 // we don't consider this to be a failure of the core package deletion 10200 } 10201 } 10202 } 10203 } 10204 } 10205 10206 /** 10207 * Logic to handle installation of non-ASEC applications, including copying 10208 * and renaming logic. 10209 */ 10210 class FileInstallArgs extends InstallArgs { 10211 private File codeFile; 10212 private File resourceFile; 10213 10214 // Example topology: 10215 // /data/app/com.example/base.apk 10216 // /data/app/com.example/split_foo.apk 10217 // /data/app/com.example/lib/arm/libfoo.so 10218 // /data/app/com.example/lib/arm64/libfoo.so 10219 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10220 10221 /** New install */ 10222 FileInstallArgs(InstallParams params) { 10223 super(params.origin, params.move, params.observer, params.installFlags, 10224 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10225 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10226 if (isFwdLocked()) { 10227 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10228 } 10229 } 10230 10231 /** Existing install */ 10232 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10233 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10234 null); 10235 this.codeFile = (codePath != null) ? new File(codePath) : null; 10236 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10237 } 10238 10239 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10240 if (origin.staged) { 10241 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10242 codeFile = origin.file; 10243 resourceFile = origin.file; 10244 return PackageManager.INSTALL_SUCCEEDED; 10245 } 10246 10247 try { 10248 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10249 codeFile = tempDir; 10250 resourceFile = tempDir; 10251 } catch (IOException e) { 10252 Slog.w(TAG, "Failed to create copy file: " + e); 10253 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10254 } 10255 10256 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10257 @Override 10258 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10259 if (!FileUtils.isValidExtFilename(name)) { 10260 throw new IllegalArgumentException("Invalid filename: " + name); 10261 } 10262 try { 10263 final File file = new File(codeFile, name); 10264 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10265 O_RDWR | O_CREAT, 0644); 10266 Os.chmod(file.getAbsolutePath(), 0644); 10267 return new ParcelFileDescriptor(fd); 10268 } catch (ErrnoException e) { 10269 throw new RemoteException("Failed to open: " + e.getMessage()); 10270 } 10271 } 10272 }; 10273 10274 int ret = PackageManager.INSTALL_SUCCEEDED; 10275 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10276 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10277 Slog.e(TAG, "Failed to copy package"); 10278 return ret; 10279 } 10280 10281 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10282 NativeLibraryHelper.Handle handle = null; 10283 try { 10284 handle = NativeLibraryHelper.Handle.create(codeFile); 10285 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10286 abiOverride); 10287 } catch (IOException e) { 10288 Slog.e(TAG, "Copying native libraries failed", e); 10289 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10290 } finally { 10291 IoUtils.closeQuietly(handle); 10292 } 10293 10294 return ret; 10295 } 10296 10297 int doPreInstall(int status) { 10298 if (status != PackageManager.INSTALL_SUCCEEDED) { 10299 cleanUp(); 10300 } 10301 return status; 10302 } 10303 10304 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10305 if (status != PackageManager.INSTALL_SUCCEEDED) { 10306 cleanUp(); 10307 return false; 10308 } 10309 10310 final File targetDir = codeFile.getParentFile(); 10311 final File beforeCodeFile = codeFile; 10312 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10313 10314 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10315 try { 10316 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10317 } catch (ErrnoException e) { 10318 Slog.d(TAG, "Failed to rename", e); 10319 return false; 10320 } 10321 10322 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10323 Slog.d(TAG, "Failed to restorecon"); 10324 return false; 10325 } 10326 10327 // Reflect the rename internally 10328 codeFile = afterCodeFile; 10329 resourceFile = afterCodeFile; 10330 10331 // Reflect the rename in scanned details 10332 pkg.codePath = afterCodeFile.getAbsolutePath(); 10333 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10334 pkg.baseCodePath); 10335 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10336 pkg.splitCodePaths); 10337 10338 // Reflect the rename in app info 10339 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10340 pkg.applicationInfo.setCodePath(pkg.codePath); 10341 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10342 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10343 pkg.applicationInfo.setResourcePath(pkg.codePath); 10344 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10345 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10346 10347 return true; 10348 } 10349 10350 int doPostInstall(int status, int uid) { 10351 if (status != PackageManager.INSTALL_SUCCEEDED) { 10352 cleanUp(); 10353 } 10354 return status; 10355 } 10356 10357 @Override 10358 String getCodePath() { 10359 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10360 } 10361 10362 @Override 10363 String getResourcePath() { 10364 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10365 } 10366 10367 private boolean cleanUp() { 10368 if (codeFile == null || !codeFile.exists()) { 10369 return false; 10370 } 10371 10372 if (codeFile.isDirectory()) { 10373 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10374 } else { 10375 codeFile.delete(); 10376 } 10377 10378 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10379 resourceFile.delete(); 10380 } 10381 10382 return true; 10383 } 10384 10385 void cleanUpResourcesLI() { 10386 // Try enumerating all code paths before deleting 10387 List<String> allCodePaths = Collections.EMPTY_LIST; 10388 if (codeFile != null && codeFile.exists()) { 10389 try { 10390 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10391 allCodePaths = pkg.getAllCodePaths(); 10392 } catch (PackageParserException e) { 10393 // Ignored; we tried our best 10394 } 10395 } 10396 10397 cleanUp(); 10398 removeDexFiles(allCodePaths, instructionSets); 10399 } 10400 10401 boolean doPostDeleteLI(boolean delete) { 10402 // XXX err, shouldn't we respect the delete flag? 10403 cleanUpResourcesLI(); 10404 return true; 10405 } 10406 } 10407 10408 private boolean isAsecExternal(String cid) { 10409 final String asecPath = PackageHelper.getSdFilesystem(cid); 10410 return !asecPath.startsWith(mAsecInternalPath); 10411 } 10412 10413 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10414 PackageManagerException { 10415 if (copyRet < 0) { 10416 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10417 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10418 throw new PackageManagerException(copyRet, message); 10419 } 10420 } 10421 } 10422 10423 /** 10424 * Extract the MountService "container ID" from the full code path of an 10425 * .apk. 10426 */ 10427 static String cidFromCodePath(String fullCodePath) { 10428 int eidx = fullCodePath.lastIndexOf("/"); 10429 String subStr1 = fullCodePath.substring(0, eidx); 10430 int sidx = subStr1.lastIndexOf("/"); 10431 return subStr1.substring(sidx+1, eidx); 10432 } 10433 10434 /** 10435 * Logic to handle installation of ASEC applications, including copying and 10436 * renaming logic. 10437 */ 10438 class AsecInstallArgs extends InstallArgs { 10439 static final String RES_FILE_NAME = "pkg.apk"; 10440 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10441 10442 String cid; 10443 String packagePath; 10444 String resourcePath; 10445 10446 /** New install */ 10447 AsecInstallArgs(InstallParams params) { 10448 super(params.origin, params.move, params.observer, params.installFlags, 10449 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10450 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10451 } 10452 10453 /** Existing install */ 10454 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10455 boolean isExternal, boolean isForwardLocked) { 10456 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10457 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10458 instructionSets, null); 10459 // Hackily pretend we're still looking at a full code path 10460 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10461 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10462 } 10463 10464 // Extract cid from fullCodePath 10465 int eidx = fullCodePath.lastIndexOf("/"); 10466 String subStr1 = fullCodePath.substring(0, eidx); 10467 int sidx = subStr1.lastIndexOf("/"); 10468 cid = subStr1.substring(sidx+1, eidx); 10469 setMountPath(subStr1); 10470 } 10471 10472 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10473 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10474 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10475 instructionSets, null); 10476 this.cid = cid; 10477 setMountPath(PackageHelper.getSdDir(cid)); 10478 } 10479 10480 void createCopyFile() { 10481 cid = mInstallerService.allocateExternalStageCidLegacy(); 10482 } 10483 10484 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10485 if (origin.staged) { 10486 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10487 cid = origin.cid; 10488 setMountPath(PackageHelper.getSdDir(cid)); 10489 return PackageManager.INSTALL_SUCCEEDED; 10490 } 10491 10492 if (temp) { 10493 createCopyFile(); 10494 } else { 10495 /* 10496 * Pre-emptively destroy the container since it's destroyed if 10497 * copying fails due to it existing anyway. 10498 */ 10499 PackageHelper.destroySdDir(cid); 10500 } 10501 10502 final String newMountPath = imcs.copyPackageToContainer( 10503 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10504 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10505 10506 if (newMountPath != null) { 10507 setMountPath(newMountPath); 10508 return PackageManager.INSTALL_SUCCEEDED; 10509 } else { 10510 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10511 } 10512 } 10513 10514 @Override 10515 String getCodePath() { 10516 return packagePath; 10517 } 10518 10519 @Override 10520 String getResourcePath() { 10521 return resourcePath; 10522 } 10523 10524 int doPreInstall(int status) { 10525 if (status != PackageManager.INSTALL_SUCCEEDED) { 10526 // Destroy container 10527 PackageHelper.destroySdDir(cid); 10528 } else { 10529 boolean mounted = PackageHelper.isContainerMounted(cid); 10530 if (!mounted) { 10531 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10532 Process.SYSTEM_UID); 10533 if (newMountPath != null) { 10534 setMountPath(newMountPath); 10535 } else { 10536 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10537 } 10538 } 10539 } 10540 return status; 10541 } 10542 10543 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10544 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10545 String newMountPath = null; 10546 if (PackageHelper.isContainerMounted(cid)) { 10547 // Unmount the container 10548 if (!PackageHelper.unMountSdDir(cid)) { 10549 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10550 return false; 10551 } 10552 } 10553 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10554 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10555 " which might be stale. Will try to clean up."); 10556 // Clean up the stale container and proceed to recreate. 10557 if (!PackageHelper.destroySdDir(newCacheId)) { 10558 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10559 return false; 10560 } 10561 // Successfully cleaned up stale container. Try to rename again. 10562 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10563 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10564 + " inspite of cleaning it up."); 10565 return false; 10566 } 10567 } 10568 if (!PackageHelper.isContainerMounted(newCacheId)) { 10569 Slog.w(TAG, "Mounting container " + newCacheId); 10570 newMountPath = PackageHelper.mountSdDir(newCacheId, 10571 getEncryptKey(), Process.SYSTEM_UID); 10572 } else { 10573 newMountPath = PackageHelper.getSdDir(newCacheId); 10574 } 10575 if (newMountPath == null) { 10576 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10577 return false; 10578 } 10579 Log.i(TAG, "Succesfully renamed " + cid + 10580 " to " + newCacheId + 10581 " at new path: " + newMountPath); 10582 cid = newCacheId; 10583 10584 final File beforeCodeFile = new File(packagePath); 10585 setMountPath(newMountPath); 10586 final File afterCodeFile = new File(packagePath); 10587 10588 // Reflect the rename in scanned details 10589 pkg.codePath = afterCodeFile.getAbsolutePath(); 10590 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10591 pkg.baseCodePath); 10592 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10593 pkg.splitCodePaths); 10594 10595 // Reflect the rename in app info 10596 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10597 pkg.applicationInfo.setCodePath(pkg.codePath); 10598 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10599 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10600 pkg.applicationInfo.setResourcePath(pkg.codePath); 10601 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10602 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10603 10604 return true; 10605 } 10606 10607 private void setMountPath(String mountPath) { 10608 final File mountFile = new File(mountPath); 10609 10610 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10611 if (monolithicFile.exists()) { 10612 packagePath = monolithicFile.getAbsolutePath(); 10613 if (isFwdLocked()) { 10614 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10615 } else { 10616 resourcePath = packagePath; 10617 } 10618 } else { 10619 packagePath = mountFile.getAbsolutePath(); 10620 resourcePath = packagePath; 10621 } 10622 } 10623 10624 int doPostInstall(int status, int uid) { 10625 if (status != PackageManager.INSTALL_SUCCEEDED) { 10626 cleanUp(); 10627 } else { 10628 final int groupOwner; 10629 final String protectedFile; 10630 if (isFwdLocked()) { 10631 groupOwner = UserHandle.getSharedAppGid(uid); 10632 protectedFile = RES_FILE_NAME; 10633 } else { 10634 groupOwner = -1; 10635 protectedFile = null; 10636 } 10637 10638 if (uid < Process.FIRST_APPLICATION_UID 10639 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10640 Slog.e(TAG, "Failed to finalize " + cid); 10641 PackageHelper.destroySdDir(cid); 10642 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10643 } 10644 10645 boolean mounted = PackageHelper.isContainerMounted(cid); 10646 if (!mounted) { 10647 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10648 } 10649 } 10650 return status; 10651 } 10652 10653 private void cleanUp() { 10654 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10655 10656 // Destroy secure container 10657 PackageHelper.destroySdDir(cid); 10658 } 10659 10660 private List<String> getAllCodePaths() { 10661 final File codeFile = new File(getCodePath()); 10662 if (codeFile != null && codeFile.exists()) { 10663 try { 10664 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10665 return pkg.getAllCodePaths(); 10666 } catch (PackageParserException e) { 10667 // Ignored; we tried our best 10668 } 10669 } 10670 return Collections.EMPTY_LIST; 10671 } 10672 10673 void cleanUpResourcesLI() { 10674 // Enumerate all code paths before deleting 10675 cleanUpResourcesLI(getAllCodePaths()); 10676 } 10677 10678 private void cleanUpResourcesLI(List<String> allCodePaths) { 10679 cleanUp(); 10680 removeDexFiles(allCodePaths, instructionSets); 10681 } 10682 10683 String getPackageName() { 10684 return getAsecPackageName(cid); 10685 } 10686 10687 boolean doPostDeleteLI(boolean delete) { 10688 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10689 final List<String> allCodePaths = getAllCodePaths(); 10690 boolean mounted = PackageHelper.isContainerMounted(cid); 10691 if (mounted) { 10692 // Unmount first 10693 if (PackageHelper.unMountSdDir(cid)) { 10694 mounted = false; 10695 } 10696 } 10697 if (!mounted && delete) { 10698 cleanUpResourcesLI(allCodePaths); 10699 } 10700 return !mounted; 10701 } 10702 10703 @Override 10704 int doPreCopy() { 10705 if (isFwdLocked()) { 10706 if (!PackageHelper.fixSdPermissions(cid, 10707 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10708 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10709 } 10710 } 10711 10712 return PackageManager.INSTALL_SUCCEEDED; 10713 } 10714 10715 @Override 10716 int doPostCopy(int uid) { 10717 if (isFwdLocked()) { 10718 if (uid < Process.FIRST_APPLICATION_UID 10719 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10720 RES_FILE_NAME)) { 10721 Slog.e(TAG, "Failed to finalize " + cid); 10722 PackageHelper.destroySdDir(cid); 10723 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10724 } 10725 } 10726 10727 return PackageManager.INSTALL_SUCCEEDED; 10728 } 10729 } 10730 10731 /** 10732 * Logic to handle movement of existing installed applications. 10733 */ 10734 class MoveInstallArgs extends InstallArgs { 10735 private File codeFile; 10736 private File resourceFile; 10737 10738 /** New install */ 10739 MoveInstallArgs(InstallParams params) { 10740 super(params.origin, params.move, params.observer, params.installFlags, 10741 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10742 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10743 } 10744 10745 int copyApk(IMediaContainerService imcs, boolean temp) { 10746 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10747 + move.toUuid); 10748 synchronized (mInstaller) { 10749 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10750 move.dataAppName, move.appId, move.seinfo) != 0) { 10751 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10752 } 10753 } 10754 10755 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10756 resourceFile = codeFile; 10757 Slog.d(TAG, "codeFile after move is " + codeFile); 10758 10759 return PackageManager.INSTALL_SUCCEEDED; 10760 } 10761 10762 int doPreInstall(int status) { 10763 if (status != PackageManager.INSTALL_SUCCEEDED) { 10764 cleanUp(); 10765 } 10766 return status; 10767 } 10768 10769 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10770 if (status != PackageManager.INSTALL_SUCCEEDED) { 10771 cleanUp(); 10772 return false; 10773 } 10774 10775 // Reflect the move in app info 10776 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10777 pkg.applicationInfo.setCodePath(pkg.codePath); 10778 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10779 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10780 pkg.applicationInfo.setResourcePath(pkg.codePath); 10781 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10782 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10783 10784 return true; 10785 } 10786 10787 int doPostInstall(int status, int uid) { 10788 if (status != PackageManager.INSTALL_SUCCEEDED) { 10789 cleanUp(); 10790 } 10791 return status; 10792 } 10793 10794 @Override 10795 String getCodePath() { 10796 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10797 } 10798 10799 @Override 10800 String getResourcePath() { 10801 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10802 } 10803 10804 private boolean cleanUp() { 10805 if (codeFile == null || !codeFile.exists()) { 10806 return false; 10807 } 10808 10809 if (codeFile.isDirectory()) { 10810 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10811 } else { 10812 codeFile.delete(); 10813 } 10814 10815 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10816 resourceFile.delete(); 10817 } 10818 10819 return true; 10820 } 10821 10822 void cleanUpResourcesLI() { 10823 cleanUp(); 10824 } 10825 10826 boolean doPostDeleteLI(boolean delete) { 10827 // XXX err, shouldn't we respect the delete flag? 10828 cleanUpResourcesLI(); 10829 return true; 10830 } 10831 } 10832 10833 static String getAsecPackageName(String packageCid) { 10834 int idx = packageCid.lastIndexOf("-"); 10835 if (idx == -1) { 10836 return packageCid; 10837 } 10838 return packageCid.substring(0, idx); 10839 } 10840 10841 // Utility method used to create code paths based on package name and available index. 10842 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10843 String idxStr = ""; 10844 int idx = 1; 10845 // Fall back to default value of idx=1 if prefix is not 10846 // part of oldCodePath 10847 if (oldCodePath != null) { 10848 String subStr = oldCodePath; 10849 // Drop the suffix right away 10850 if (suffix != null && subStr.endsWith(suffix)) { 10851 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10852 } 10853 // If oldCodePath already contains prefix find out the 10854 // ending index to either increment or decrement. 10855 int sidx = subStr.lastIndexOf(prefix); 10856 if (sidx != -1) { 10857 subStr = subStr.substring(sidx + prefix.length()); 10858 if (subStr != null) { 10859 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10860 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10861 } 10862 try { 10863 idx = Integer.parseInt(subStr); 10864 if (idx <= 1) { 10865 idx++; 10866 } else { 10867 idx--; 10868 } 10869 } catch(NumberFormatException e) { 10870 } 10871 } 10872 } 10873 } 10874 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10875 return prefix + idxStr; 10876 } 10877 10878 private File getNextCodePath(File targetDir, String packageName) { 10879 int suffix = 1; 10880 File result; 10881 do { 10882 result = new File(targetDir, packageName + "-" + suffix); 10883 suffix++; 10884 } while (result.exists()); 10885 return result; 10886 } 10887 10888 // Utility method that returns the relative package path with respect 10889 // to the installation directory. Like say for /data/data/com.test-1.apk 10890 // string com.test-1 is returned. 10891 static String deriveCodePathName(String codePath) { 10892 if (codePath == null) { 10893 return null; 10894 } 10895 final File codeFile = new File(codePath); 10896 final String name = codeFile.getName(); 10897 if (codeFile.isDirectory()) { 10898 return name; 10899 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10900 final int lastDot = name.lastIndexOf('.'); 10901 return name.substring(0, lastDot); 10902 } else { 10903 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10904 return null; 10905 } 10906 } 10907 10908 class PackageInstalledInfo { 10909 String name; 10910 int uid; 10911 // The set of users that originally had this package installed. 10912 int[] origUsers; 10913 // The set of users that now have this package installed. 10914 int[] newUsers; 10915 PackageParser.Package pkg; 10916 int returnCode; 10917 String returnMsg; 10918 PackageRemovedInfo removedInfo; 10919 10920 public void setError(int code, String msg) { 10921 returnCode = code; 10922 returnMsg = msg; 10923 Slog.w(TAG, msg); 10924 } 10925 10926 public void setError(String msg, PackageParserException e) { 10927 returnCode = e.error; 10928 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10929 Slog.w(TAG, msg, e); 10930 } 10931 10932 public void setError(String msg, PackageManagerException e) { 10933 returnCode = e.error; 10934 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10935 Slog.w(TAG, msg, e); 10936 } 10937 10938 // In some error cases we want to convey more info back to the observer 10939 String origPackage; 10940 String origPermission; 10941 } 10942 10943 /* 10944 * Install a non-existing package. 10945 */ 10946 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10947 UserHandle user, String installerPackageName, String volumeUuid, 10948 PackageInstalledInfo res) { 10949 // Remember this for later, in case we need to rollback this install 10950 String pkgName = pkg.packageName; 10951 10952 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10953 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10954 UserHandle.USER_OWNER).exists(); 10955 synchronized(mPackages) { 10956 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10957 // A package with the same name is already installed, though 10958 // it has been renamed to an older name. The package we 10959 // are trying to install should be installed as an update to 10960 // the existing one, but that has not been requested, so bail. 10961 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10962 + " without first uninstalling package running as " 10963 + mSettings.mRenamedPackages.get(pkgName)); 10964 return; 10965 } 10966 if (mPackages.containsKey(pkgName)) { 10967 // Don't allow installation over an existing package with the same name. 10968 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10969 + " without first uninstalling."); 10970 return; 10971 } 10972 } 10973 10974 try { 10975 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10976 System.currentTimeMillis(), user); 10977 10978 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10979 // delete the partially installed application. the data directory will have to be 10980 // restored if it was already existing 10981 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10982 // remove package from internal structures. Note that we want deletePackageX to 10983 // delete the package data and cache directories that it created in 10984 // scanPackageLocked, unless those directories existed before we even tried to 10985 // install. 10986 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10987 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10988 res.removedInfo, true); 10989 } 10990 10991 } catch (PackageManagerException e) { 10992 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10993 } 10994 } 10995 10996 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10997 // Upgrade keysets are being used. Determine if new package has a superset of the 10998 // required keys. 10999 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11000 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11001 for (int i = 0; i < upgradeKeySets.length; i++) { 11002 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11003 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11004 return true; 11005 } 11006 } 11007 return false; 11008 } 11009 11010 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11011 UserHandle user, String installerPackageName, String volumeUuid, 11012 PackageInstalledInfo res) { 11013 final PackageParser.Package oldPackage; 11014 final String pkgName = pkg.packageName; 11015 final int[] allUsers; 11016 final boolean[] perUserInstalled; 11017 final boolean weFroze; 11018 11019 // First find the old package info and check signatures 11020 synchronized(mPackages) { 11021 oldPackage = mPackages.get(pkgName); 11022 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11023 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11024 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11025 // default to original signature matching 11026 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11027 != PackageManager.SIGNATURE_MATCH) { 11028 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11029 "New package has a different signature: " + pkgName); 11030 return; 11031 } 11032 } else { 11033 if(!checkUpgradeKeySetLP(ps, pkg)) { 11034 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11035 "New package not signed by keys specified by upgrade-keysets: " 11036 + pkgName); 11037 return; 11038 } 11039 } 11040 11041 // In case of rollback, remember per-user/profile install state 11042 allUsers = sUserManager.getUserIds(); 11043 perUserInstalled = new boolean[allUsers.length]; 11044 for (int i = 0; i < allUsers.length; i++) { 11045 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11046 } 11047 11048 // Mark the app as frozen to prevent launching during the upgrade 11049 // process, and then kill all running instances 11050 if (!ps.frozen) { 11051 ps.frozen = true; 11052 weFroze = true; 11053 } else { 11054 weFroze = false; 11055 } 11056 } 11057 11058 // Now that we're guarded by frozen state, kill app during upgrade 11059 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11060 11061 try { 11062 boolean sysPkg = (isSystemApp(oldPackage)); 11063 if (sysPkg) { 11064 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11065 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11066 } else { 11067 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11068 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11069 } 11070 } finally { 11071 // Regardless of success or failure of upgrade steps above, always 11072 // unfreeze the package if we froze it 11073 if (weFroze) { 11074 unfreezePackage(pkgName); 11075 } 11076 } 11077 } 11078 11079 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11080 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11081 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11082 String volumeUuid, PackageInstalledInfo res) { 11083 String pkgName = deletedPackage.packageName; 11084 boolean deletedPkg = true; 11085 boolean updatedSettings = false; 11086 11087 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11088 + deletedPackage); 11089 long origUpdateTime; 11090 if (pkg.mExtras != null) { 11091 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11092 } else { 11093 origUpdateTime = 0; 11094 } 11095 11096 // First delete the existing package while retaining the data directory 11097 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11098 res.removedInfo, true)) { 11099 // If the existing package wasn't successfully deleted 11100 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11101 deletedPkg = false; 11102 } else { 11103 // Successfully deleted the old package; proceed with replace. 11104 11105 // If deleted package lived in a container, give users a chance to 11106 // relinquish resources before killing. 11107 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11108 if (DEBUG_INSTALL) { 11109 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11110 } 11111 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11112 final ArrayList<String> pkgList = new ArrayList<String>(1); 11113 pkgList.add(deletedPackage.applicationInfo.packageName); 11114 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11115 } 11116 11117 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11118 try { 11119 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11120 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11121 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11122 perUserInstalled, res, user); 11123 updatedSettings = true; 11124 } catch (PackageManagerException e) { 11125 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11126 } 11127 } 11128 11129 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11130 // remove package from internal structures. Note that we want deletePackageX to 11131 // delete the package data and cache directories that it created in 11132 // scanPackageLocked, unless those directories existed before we even tried to 11133 // install. 11134 if(updatedSettings) { 11135 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11136 deletePackageLI( 11137 pkgName, null, true, allUsers, perUserInstalled, 11138 PackageManager.DELETE_KEEP_DATA, 11139 res.removedInfo, true); 11140 } 11141 // Since we failed to install the new package we need to restore the old 11142 // package that we deleted. 11143 if (deletedPkg) { 11144 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11145 File restoreFile = new File(deletedPackage.codePath); 11146 // Parse old package 11147 boolean oldExternal = isExternal(deletedPackage); 11148 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11149 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11150 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11151 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11152 try { 11153 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11154 } catch (PackageManagerException e) { 11155 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11156 + e.getMessage()); 11157 return; 11158 } 11159 // Restore of old package succeeded. Update permissions. 11160 // writer 11161 synchronized (mPackages) { 11162 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11163 UPDATE_PERMISSIONS_ALL); 11164 // can downgrade to reader 11165 mSettings.writeLPr(); 11166 } 11167 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11168 } 11169 } 11170 } 11171 11172 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11173 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11174 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11175 String volumeUuid, PackageInstalledInfo res) { 11176 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11177 + ", old=" + deletedPackage); 11178 boolean disabledSystem = false; 11179 boolean updatedSettings = false; 11180 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11181 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11182 != 0) { 11183 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11184 } 11185 String packageName = deletedPackage.packageName; 11186 if (packageName == null) { 11187 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11188 "Attempt to delete null packageName."); 11189 return; 11190 } 11191 PackageParser.Package oldPkg; 11192 PackageSetting oldPkgSetting; 11193 // reader 11194 synchronized (mPackages) { 11195 oldPkg = mPackages.get(packageName); 11196 oldPkgSetting = mSettings.mPackages.get(packageName); 11197 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11198 (oldPkgSetting == null)) { 11199 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11200 "Couldn't find package:" + packageName + " information"); 11201 return; 11202 } 11203 } 11204 11205 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11206 res.removedInfo.removedPackage = packageName; 11207 // Remove existing system package 11208 removePackageLI(oldPkgSetting, true); 11209 // writer 11210 synchronized (mPackages) { 11211 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11212 if (!disabledSystem && deletedPackage != null) { 11213 // We didn't need to disable the .apk as a current system package, 11214 // which means we are replacing another update that is already 11215 // installed. We need to make sure to delete the older one's .apk. 11216 res.removedInfo.args = createInstallArgsForExisting(0, 11217 deletedPackage.applicationInfo.getCodePath(), 11218 deletedPackage.applicationInfo.getResourcePath(), 11219 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11220 } else { 11221 res.removedInfo.args = null; 11222 } 11223 } 11224 11225 // Successfully disabled the old package. Now proceed with re-installation 11226 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11227 11228 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11229 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11230 11231 PackageParser.Package newPackage = null; 11232 try { 11233 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11234 if (newPackage.mExtras != null) { 11235 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11236 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11237 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11238 11239 // is the update attempting to change shared user? that isn't going to work... 11240 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11241 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11242 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11243 + " to " + newPkgSetting.sharedUser); 11244 updatedSettings = true; 11245 } 11246 } 11247 11248 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11249 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11250 perUserInstalled, res, user); 11251 updatedSettings = true; 11252 } 11253 11254 } catch (PackageManagerException e) { 11255 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11256 } 11257 11258 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11259 // Re installation failed. Restore old information 11260 // Remove new pkg information 11261 if (newPackage != null) { 11262 removeInstalledPackageLI(newPackage, true); 11263 } 11264 // Add back the old system package 11265 try { 11266 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11267 } catch (PackageManagerException e) { 11268 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11269 } 11270 // Restore the old system information in Settings 11271 synchronized (mPackages) { 11272 if (disabledSystem) { 11273 mSettings.enableSystemPackageLPw(packageName); 11274 } 11275 if (updatedSettings) { 11276 mSettings.setInstallerPackageName(packageName, 11277 oldPkgSetting.installerPackageName); 11278 } 11279 mSettings.writeLPr(); 11280 } 11281 } 11282 } 11283 11284 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11285 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11286 UserHandle user) { 11287 String pkgName = newPackage.packageName; 11288 synchronized (mPackages) { 11289 //write settings. the installStatus will be incomplete at this stage. 11290 //note that the new package setting would have already been 11291 //added to mPackages. It hasn't been persisted yet. 11292 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11293 mSettings.writeLPr(); 11294 } 11295 11296 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11297 11298 synchronized (mPackages) { 11299 updatePermissionsLPw(newPackage.packageName, newPackage, 11300 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11301 ? UPDATE_PERMISSIONS_ALL : 0)); 11302 // For system-bundled packages, we assume that installing an upgraded version 11303 // of the package implies that the user actually wants to run that new code, 11304 // so we enable the package. 11305 PackageSetting ps = mSettings.mPackages.get(pkgName); 11306 if (ps != null) { 11307 if (isSystemApp(newPackage)) { 11308 // NB: implicit assumption that system package upgrades apply to all users 11309 if (DEBUG_INSTALL) { 11310 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11311 } 11312 if (res.origUsers != null) { 11313 for (int userHandle : res.origUsers) { 11314 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11315 userHandle, installerPackageName); 11316 } 11317 } 11318 // Also convey the prior install/uninstall state 11319 if (allUsers != null && perUserInstalled != null) { 11320 for (int i = 0; i < allUsers.length; i++) { 11321 if (DEBUG_INSTALL) { 11322 Slog.d(TAG, " user " + allUsers[i] 11323 + " => " + perUserInstalled[i]); 11324 } 11325 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11326 } 11327 // these install state changes will be persisted in the 11328 // upcoming call to mSettings.writeLPr(). 11329 } 11330 } 11331 // It's implied that when a user requests installation, they want the app to be 11332 // installed and enabled. 11333 int userId = user.getIdentifier(); 11334 if (userId != UserHandle.USER_ALL) { 11335 ps.setInstalled(true, userId); 11336 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11337 } 11338 } 11339 res.name = pkgName; 11340 res.uid = newPackage.applicationInfo.uid; 11341 res.pkg = newPackage; 11342 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11343 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11344 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11345 //to update install status 11346 mSettings.writeLPr(); 11347 } 11348 } 11349 11350 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11351 final int installFlags = args.installFlags; 11352 final String installerPackageName = args.installerPackageName; 11353 final String volumeUuid = args.volumeUuid; 11354 final File tmpPackageFile = new File(args.getCodePath()); 11355 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11356 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11357 || (args.volumeUuid != null)); 11358 boolean replace = false; 11359 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11360 // Result object to be returned 11361 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11362 11363 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11364 // Retrieve PackageSettings and parse package 11365 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11366 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11367 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11368 PackageParser pp = new PackageParser(); 11369 pp.setSeparateProcesses(mSeparateProcesses); 11370 pp.setDisplayMetrics(mMetrics); 11371 11372 final PackageParser.Package pkg; 11373 try { 11374 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11375 } catch (PackageParserException e) { 11376 res.setError("Failed parse during installPackageLI", e); 11377 return; 11378 } 11379 11380 // Mark that we have an install time CPU ABI override. 11381 pkg.cpuAbiOverride = args.abiOverride; 11382 11383 String pkgName = res.name = pkg.packageName; 11384 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11385 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11386 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11387 return; 11388 } 11389 } 11390 11391 try { 11392 pp.collectCertificates(pkg, parseFlags); 11393 pp.collectManifestDigest(pkg); 11394 } catch (PackageParserException e) { 11395 res.setError("Failed collect during installPackageLI", e); 11396 return; 11397 } 11398 11399 /* If the installer passed in a manifest digest, compare it now. */ 11400 if (args.manifestDigest != null) { 11401 if (DEBUG_INSTALL) { 11402 final String parsedManifest = pkg.manifestDigest == null ? "null" 11403 : pkg.manifestDigest.toString(); 11404 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11405 + parsedManifest); 11406 } 11407 11408 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11409 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11410 return; 11411 } 11412 } else if (DEBUG_INSTALL) { 11413 final String parsedManifest = pkg.manifestDigest == null 11414 ? "null" : pkg.manifestDigest.toString(); 11415 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11416 } 11417 11418 // Get rid of all references to package scan path via parser. 11419 pp = null; 11420 String oldCodePath = null; 11421 boolean systemApp = false; 11422 synchronized (mPackages) { 11423 // Check if installing already existing package 11424 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11425 String oldName = mSettings.mRenamedPackages.get(pkgName); 11426 if (pkg.mOriginalPackages != null 11427 && pkg.mOriginalPackages.contains(oldName) 11428 && mPackages.containsKey(oldName)) { 11429 // This package is derived from an original package, 11430 // and this device has been updating from that original 11431 // name. We must continue using the original name, so 11432 // rename the new package here. 11433 pkg.setPackageName(oldName); 11434 pkgName = pkg.packageName; 11435 replace = true; 11436 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11437 + oldName + " pkgName=" + pkgName); 11438 } else if (mPackages.containsKey(pkgName)) { 11439 // This package, under its official name, already exists 11440 // on the device; we should replace it. 11441 replace = true; 11442 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11443 } 11444 } 11445 11446 PackageSetting ps = mSettings.mPackages.get(pkgName); 11447 if (ps != null) { 11448 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11449 11450 // Quick sanity check that we're signed correctly if updating; 11451 // we'll check this again later when scanning, but we want to 11452 // bail early here before tripping over redefined permissions. 11453 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11454 try { 11455 verifySignaturesLP(ps, pkg); 11456 } catch (PackageManagerException e) { 11457 res.setError(e.error, e.getMessage()); 11458 return; 11459 } 11460 } else { 11461 if (!checkUpgradeKeySetLP(ps, pkg)) { 11462 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11463 + pkg.packageName + " upgrade keys do not match the " 11464 + "previously installed version"); 11465 return; 11466 } 11467 } 11468 11469 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11470 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11471 systemApp = (ps.pkg.applicationInfo.flags & 11472 ApplicationInfo.FLAG_SYSTEM) != 0; 11473 } 11474 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11475 } 11476 11477 // Check whether the newly-scanned package wants to define an already-defined perm 11478 int N = pkg.permissions.size(); 11479 for (int i = N-1; i >= 0; i--) { 11480 PackageParser.Permission perm = pkg.permissions.get(i); 11481 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11482 if (bp != null) { 11483 // If the defining package is signed with our cert, it's okay. This 11484 // also includes the "updating the same package" case, of course. 11485 // "updating same package" could also involve key-rotation. 11486 final boolean sigsOk; 11487 if (!bp.sourcePackage.equals(pkg.packageName) 11488 || !(bp.packageSetting instanceof PackageSetting) 11489 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11490 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11491 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11492 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11493 } else { 11494 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11495 } 11496 if (!sigsOk) { 11497 // If the owning package is the system itself, we log but allow 11498 // install to proceed; we fail the install on all other permission 11499 // redefinitions. 11500 if (!bp.sourcePackage.equals("android")) { 11501 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11502 + pkg.packageName + " attempting to redeclare permission " 11503 + perm.info.name + " already owned by " + bp.sourcePackage); 11504 res.origPermission = perm.info.name; 11505 res.origPackage = bp.sourcePackage; 11506 return; 11507 } else { 11508 Slog.w(TAG, "Package " + pkg.packageName 11509 + " attempting to redeclare system permission " 11510 + perm.info.name + "; ignoring new declaration"); 11511 pkg.permissions.remove(i); 11512 } 11513 } 11514 } 11515 } 11516 11517 } 11518 11519 if (systemApp && onExternal) { 11520 // Disable updates to system apps on sdcard 11521 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11522 "Cannot install updates to system apps on sdcard"); 11523 return; 11524 } 11525 11526 if (args.move != null) { 11527 // We did an in-place move, so dex is ready to roll 11528 scanFlags |= SCAN_NO_DEX; 11529 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11530 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11531 scanFlags |= SCAN_NO_DEX; 11532 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11533 int result = mPackageDexOptimizer 11534 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11535 false /* defer */, false /* inclDependencies */); 11536 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11537 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11538 return; 11539 } 11540 } 11541 11542 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11543 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11544 return; 11545 } 11546 11547 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11548 11549 if (replace) { 11550 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11551 installerPackageName, volumeUuid, res); 11552 } else { 11553 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11554 args.user, installerPackageName, volumeUuid, res); 11555 } 11556 synchronized (mPackages) { 11557 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11558 if (ps != null) { 11559 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11560 } 11561 } 11562 } 11563 11564 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11565 if (mIntentFilterVerifierComponent == null) { 11566 Slog.d(TAG, "No IntentFilter verification will not be done as " 11567 + "there is no IntentFilterVerifier available!"); 11568 return; 11569 } 11570 11571 final int verifierUid = getPackageUid( 11572 mIntentFilterVerifierComponent.getPackageName(), 11573 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11574 11575 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11576 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11577 msg.obj = pkg; 11578 msg.arg1 = userId; 11579 msg.arg2 = verifierUid; 11580 11581 mHandler.sendMessage(msg); 11582 } 11583 11584 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11585 PackageParser.Package pkg) { 11586 int size = pkg.activities.size(); 11587 if (size == 0) { 11588 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11589 return; 11590 } 11591 11592 final boolean hasDomainURLs = hasDomainURLs(pkg); 11593 if (!hasDomainURLs) { 11594 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11595 return; 11596 } 11597 11598 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11599 + " Activities needs verification ..."); 11600 11601 final int verificationId = mIntentFilterVerificationToken++; 11602 int count = 0; 11603 final String packageName = pkg.packageName; 11604 ArrayList<String> allHosts = new ArrayList<>(); 11605 11606 synchronized (mPackages) { 11607 for (PackageParser.Activity a : pkg.activities) { 11608 for (ActivityIntentInfo filter : a.intents) { 11609 boolean needsFilterVerification = filter.needsVerification(); 11610 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11611 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11612 mIntentFilterVerifier.addOneIntentFilterVerification( 11613 verifierUid, userId, verificationId, filter, packageName); 11614 count++; 11615 } else if (!needsFilterVerification) { 11616 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11617 if (hasValidDomains(filter)) { 11618 ArrayList<String> hosts = filter.getHostsList(); 11619 if (hosts.size() > 0) { 11620 allHosts.addAll(hosts); 11621 } else { 11622 if (allHosts.isEmpty()) { 11623 allHosts.add("*"); 11624 } 11625 } 11626 } 11627 } else { 11628 Slog.d(TAG, "Verification already done for IntentFilter:" 11629 + filter.toString()); 11630 } 11631 } 11632 } 11633 } 11634 11635 if (count > 0) { 11636 mIntentFilterVerifier.startVerifications(userId); 11637 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11638 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11639 } else { 11640 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11641 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11642 packageName, allHosts) != null) { 11643 scheduleWriteSettingsLocked(); 11644 } 11645 } 11646 } 11647 11648 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11649 final ComponentName cn = filter.activity.getComponentName(); 11650 final String packageName = cn.getPackageName(); 11651 11652 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11653 packageName); 11654 if (ivi == null) { 11655 return true; 11656 } 11657 int status = ivi.getStatus(); 11658 switch (status) { 11659 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11660 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11661 return true; 11662 11663 default: 11664 // Nothing to do 11665 return false; 11666 } 11667 } 11668 11669 private static boolean isMultiArch(PackageSetting ps) { 11670 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11671 } 11672 11673 private static boolean isMultiArch(ApplicationInfo info) { 11674 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11675 } 11676 11677 private static boolean isExternal(PackageParser.Package pkg) { 11678 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11679 } 11680 11681 private static boolean isExternal(PackageSetting ps) { 11682 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11683 } 11684 11685 private static boolean isExternal(ApplicationInfo info) { 11686 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11687 } 11688 11689 private static boolean isSystemApp(PackageParser.Package pkg) { 11690 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11691 } 11692 11693 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11694 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11695 } 11696 11697 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11698 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11699 } 11700 11701 private static boolean isSystemApp(PackageSetting ps) { 11702 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11703 } 11704 11705 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11706 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11707 } 11708 11709 private int packageFlagsToInstallFlags(PackageSetting ps) { 11710 int installFlags = 0; 11711 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11712 // This existing package was an external ASEC install when we have 11713 // the external flag without a UUID 11714 installFlags |= PackageManager.INSTALL_EXTERNAL; 11715 } 11716 if (ps.isForwardLocked()) { 11717 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11718 } 11719 return installFlags; 11720 } 11721 11722 private void deleteTempPackageFiles() { 11723 final FilenameFilter filter = new FilenameFilter() { 11724 public boolean accept(File dir, String name) { 11725 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11726 } 11727 }; 11728 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11729 file.delete(); 11730 } 11731 } 11732 11733 @Override 11734 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11735 int flags) { 11736 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11737 flags); 11738 } 11739 11740 @Override 11741 public void deletePackage(final String packageName, 11742 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11743 mContext.enforceCallingOrSelfPermission( 11744 android.Manifest.permission.DELETE_PACKAGES, null); 11745 final int uid = Binder.getCallingUid(); 11746 if (UserHandle.getUserId(uid) != userId) { 11747 mContext.enforceCallingPermission( 11748 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11749 "deletePackage for user " + userId); 11750 } 11751 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11752 try { 11753 observer.onPackageDeleted(packageName, 11754 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11755 } catch (RemoteException re) { 11756 } 11757 return; 11758 } 11759 11760 boolean uninstallBlocked = false; 11761 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11762 int[] users = sUserManager.getUserIds(); 11763 for (int i = 0; i < users.length; ++i) { 11764 if (getBlockUninstallForUser(packageName, users[i])) { 11765 uninstallBlocked = true; 11766 break; 11767 } 11768 } 11769 } else { 11770 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11771 } 11772 if (uninstallBlocked) { 11773 try { 11774 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11775 null); 11776 } catch (RemoteException re) { 11777 } 11778 return; 11779 } 11780 11781 if (DEBUG_REMOVE) { 11782 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11783 } 11784 // Queue up an async operation since the package deletion may take a little while. 11785 mHandler.post(new Runnable() { 11786 public void run() { 11787 mHandler.removeCallbacks(this); 11788 final int returnCode = deletePackageX(packageName, userId, flags); 11789 if (observer != null) { 11790 try { 11791 observer.onPackageDeleted(packageName, returnCode, null); 11792 } catch (RemoteException e) { 11793 Log.i(TAG, "Observer no longer exists."); 11794 } //end catch 11795 } //end if 11796 } //end run 11797 }); 11798 } 11799 11800 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11801 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11802 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11803 try { 11804 if (dpm != null) { 11805 if (dpm.isDeviceOwner(packageName)) { 11806 return true; 11807 } 11808 int[] users; 11809 if (userId == UserHandle.USER_ALL) { 11810 users = sUserManager.getUserIds(); 11811 } else { 11812 users = new int[]{userId}; 11813 } 11814 for (int i = 0; i < users.length; ++i) { 11815 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11816 return true; 11817 } 11818 } 11819 } 11820 } catch (RemoteException e) { 11821 } 11822 return false; 11823 } 11824 11825 /** 11826 * This method is an internal method that could be get invoked either 11827 * to delete an installed package or to clean up a failed installation. 11828 * After deleting an installed package, a broadcast is sent to notify any 11829 * listeners that the package has been installed. For cleaning up a failed 11830 * installation, the broadcast is not necessary since the package's 11831 * installation wouldn't have sent the initial broadcast either 11832 * The key steps in deleting a package are 11833 * deleting the package information in internal structures like mPackages, 11834 * deleting the packages base directories through installd 11835 * updating mSettings to reflect current status 11836 * persisting settings for later use 11837 * sending a broadcast if necessary 11838 */ 11839 private int deletePackageX(String packageName, int userId, int flags) { 11840 final PackageRemovedInfo info = new PackageRemovedInfo(); 11841 final boolean res; 11842 11843 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11844 ? UserHandle.ALL : new UserHandle(userId); 11845 11846 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11847 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11848 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11849 } 11850 11851 boolean removedForAllUsers = false; 11852 boolean systemUpdate = false; 11853 11854 // for the uninstall-updates case and restricted profiles, remember the per- 11855 // userhandle installed state 11856 int[] allUsers; 11857 boolean[] perUserInstalled; 11858 synchronized (mPackages) { 11859 PackageSetting ps = mSettings.mPackages.get(packageName); 11860 allUsers = sUserManager.getUserIds(); 11861 perUserInstalled = new boolean[allUsers.length]; 11862 for (int i = 0; i < allUsers.length; i++) { 11863 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11864 } 11865 } 11866 11867 synchronized (mInstallLock) { 11868 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11869 res = deletePackageLI(packageName, removeForUser, 11870 true, allUsers, perUserInstalled, 11871 flags | REMOVE_CHATTY, info, true); 11872 systemUpdate = info.isRemovedPackageSystemUpdate; 11873 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11874 removedForAllUsers = true; 11875 } 11876 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11877 + " removedForAllUsers=" + removedForAllUsers); 11878 } 11879 11880 if (res) { 11881 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11882 11883 // If the removed package was a system update, the old system package 11884 // was re-enabled; we need to broadcast this information 11885 if (systemUpdate) { 11886 Bundle extras = new Bundle(1); 11887 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11888 ? info.removedAppId : info.uid); 11889 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11890 11891 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11892 extras, null, null, null); 11893 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11894 extras, null, null, null); 11895 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11896 null, packageName, null, null); 11897 } 11898 } 11899 // Force a gc here. 11900 Runtime.getRuntime().gc(); 11901 // Delete the resources here after sending the broadcast to let 11902 // other processes clean up before deleting resources. 11903 if (info.args != null) { 11904 synchronized (mInstallLock) { 11905 info.args.doPostDeleteLI(true); 11906 } 11907 } 11908 11909 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11910 } 11911 11912 class PackageRemovedInfo { 11913 String removedPackage; 11914 int uid = -1; 11915 int removedAppId = -1; 11916 int[] removedUsers = null; 11917 boolean isRemovedPackageSystemUpdate = false; 11918 // Clean up resources deleted packages. 11919 InstallArgs args = null; 11920 11921 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11922 Bundle extras = new Bundle(1); 11923 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11924 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11925 if (replacing) { 11926 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11927 } 11928 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11929 if (removedPackage != null) { 11930 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11931 extras, null, null, removedUsers); 11932 if (fullRemove && !replacing) { 11933 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11934 extras, null, null, removedUsers); 11935 } 11936 } 11937 if (removedAppId >= 0) { 11938 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11939 removedUsers); 11940 } 11941 } 11942 } 11943 11944 /* 11945 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11946 * flag is not set, the data directory is removed as well. 11947 * make sure this flag is set for partially installed apps. If not its meaningless to 11948 * delete a partially installed application. 11949 */ 11950 private void removePackageDataLI(PackageSetting ps, 11951 int[] allUserHandles, boolean[] perUserInstalled, 11952 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11953 String packageName = ps.name; 11954 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11955 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11956 // Retrieve object to delete permissions for shared user later on 11957 final PackageSetting deletedPs; 11958 // reader 11959 synchronized (mPackages) { 11960 deletedPs = mSettings.mPackages.get(packageName); 11961 if (outInfo != null) { 11962 outInfo.removedPackage = packageName; 11963 outInfo.removedUsers = deletedPs != null 11964 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11965 : null; 11966 } 11967 } 11968 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11969 removeDataDirsLI(ps.volumeUuid, packageName); 11970 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11971 } 11972 // writer 11973 synchronized (mPackages) { 11974 if (deletedPs != null) { 11975 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11976 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11977 clearDefaultBrowserIfNeeded(packageName); 11978 if (outInfo != null) { 11979 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11980 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11981 } 11982 updatePermissionsLPw(deletedPs.name, null, 0); 11983 if (deletedPs.sharedUser != null) { 11984 // Remove permissions associated with package. Since runtime 11985 // permissions are per user we have to kill the removed package 11986 // or packages running under the shared user of the removed 11987 // package if revoking the permissions requested only by the removed 11988 // package is successful and this causes a change in gids. 11989 for (int userId : UserManagerService.getInstance().getUserIds()) { 11990 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11991 userId); 11992 if (userIdToKill == UserHandle.USER_ALL 11993 || userIdToKill >= UserHandle.USER_OWNER) { 11994 // If gids changed for this user, kill all affected packages. 11995 mHandler.post(new Runnable() { 11996 @Override 11997 public void run() { 11998 // This has to happen with no lock held. 11999 killSettingPackagesForUser(deletedPs, userIdToKill, 12000 KILL_APP_REASON_GIDS_CHANGED); 12001 } 12002 }); 12003 break; 12004 } 12005 } 12006 } 12007 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12008 } 12009 // make sure to preserve per-user disabled state if this removal was just 12010 // a downgrade of a system app to the factory package 12011 if (allUserHandles != null && perUserInstalled != null) { 12012 if (DEBUG_REMOVE) { 12013 Slog.d(TAG, "Propagating install state across downgrade"); 12014 } 12015 for (int i = 0; i < allUserHandles.length; i++) { 12016 if (DEBUG_REMOVE) { 12017 Slog.d(TAG, " user " + allUserHandles[i] 12018 + " => " + perUserInstalled[i]); 12019 } 12020 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12021 } 12022 } 12023 } 12024 // can downgrade to reader 12025 if (writeSettings) { 12026 // Save settings now 12027 mSettings.writeLPr(); 12028 } 12029 } 12030 if (outInfo != null) { 12031 // A user ID was deleted here. Go through all users and remove it 12032 // from KeyStore. 12033 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12034 } 12035 } 12036 12037 static boolean locationIsPrivileged(File path) { 12038 try { 12039 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12040 .getCanonicalPath(); 12041 return path.getCanonicalPath().startsWith(privilegedAppDir); 12042 } catch (IOException e) { 12043 Slog.e(TAG, "Unable to access code path " + path); 12044 } 12045 return false; 12046 } 12047 12048 /* 12049 * Tries to delete system package. 12050 */ 12051 private boolean deleteSystemPackageLI(PackageSetting newPs, 12052 int[] allUserHandles, boolean[] perUserInstalled, 12053 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12054 final boolean applyUserRestrictions 12055 = (allUserHandles != null) && (perUserInstalled != null); 12056 PackageSetting disabledPs = null; 12057 // Confirm if the system package has been updated 12058 // An updated system app can be deleted. This will also have to restore 12059 // the system pkg from system partition 12060 // reader 12061 synchronized (mPackages) { 12062 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12063 } 12064 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12065 + " disabledPs=" + disabledPs); 12066 if (disabledPs == null) { 12067 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12068 return false; 12069 } else if (DEBUG_REMOVE) { 12070 Slog.d(TAG, "Deleting system pkg from data partition"); 12071 } 12072 if (DEBUG_REMOVE) { 12073 if (applyUserRestrictions) { 12074 Slog.d(TAG, "Remembering install states:"); 12075 for (int i = 0; i < allUserHandles.length; i++) { 12076 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12077 } 12078 } 12079 } 12080 // Delete the updated package 12081 outInfo.isRemovedPackageSystemUpdate = true; 12082 if (disabledPs.versionCode < newPs.versionCode) { 12083 // Delete data for downgrades 12084 flags &= ~PackageManager.DELETE_KEEP_DATA; 12085 } else { 12086 // Preserve data by setting flag 12087 flags |= PackageManager.DELETE_KEEP_DATA; 12088 } 12089 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12090 allUserHandles, perUserInstalled, outInfo, writeSettings); 12091 if (!ret) { 12092 return false; 12093 } 12094 // writer 12095 synchronized (mPackages) { 12096 // Reinstate the old system package 12097 mSettings.enableSystemPackageLPw(newPs.name); 12098 // Remove any native libraries from the upgraded package. 12099 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12100 } 12101 // Install the system package 12102 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12103 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12104 if (locationIsPrivileged(disabledPs.codePath)) { 12105 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12106 } 12107 12108 final PackageParser.Package newPkg; 12109 try { 12110 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12111 } catch (PackageManagerException e) { 12112 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12113 return false; 12114 } 12115 12116 // writer 12117 synchronized (mPackages) { 12118 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12119 updatePermissionsLPw(newPkg.packageName, newPkg, 12120 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12121 if (applyUserRestrictions) { 12122 if (DEBUG_REMOVE) { 12123 Slog.d(TAG, "Propagating install state across reinstall"); 12124 } 12125 for (int i = 0; i < allUserHandles.length; i++) { 12126 if (DEBUG_REMOVE) { 12127 Slog.d(TAG, " user " + allUserHandles[i] 12128 + " => " + perUserInstalled[i]); 12129 } 12130 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12131 } 12132 // Regardless of writeSettings we need to ensure that this restriction 12133 // state propagation is persisted 12134 mSettings.writeAllUsersPackageRestrictionsLPr(); 12135 } 12136 // can downgrade to reader here 12137 if (writeSettings) { 12138 mSettings.writeLPr(); 12139 } 12140 } 12141 return true; 12142 } 12143 12144 private boolean deleteInstalledPackageLI(PackageSetting ps, 12145 boolean deleteCodeAndResources, int flags, 12146 int[] allUserHandles, boolean[] perUserInstalled, 12147 PackageRemovedInfo outInfo, boolean writeSettings) { 12148 if (outInfo != null) { 12149 outInfo.uid = ps.appId; 12150 } 12151 12152 // Delete package data from internal structures and also remove data if flag is set 12153 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12154 12155 // Delete application code and resources 12156 if (deleteCodeAndResources && (outInfo != null)) { 12157 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12158 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12159 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12160 } 12161 return true; 12162 } 12163 12164 @Override 12165 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12166 int userId) { 12167 mContext.enforceCallingOrSelfPermission( 12168 android.Manifest.permission.DELETE_PACKAGES, null); 12169 synchronized (mPackages) { 12170 PackageSetting ps = mSettings.mPackages.get(packageName); 12171 if (ps == null) { 12172 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12173 return false; 12174 } 12175 if (!ps.getInstalled(userId)) { 12176 // Can't block uninstall for an app that is not installed or enabled. 12177 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12178 return false; 12179 } 12180 ps.setBlockUninstall(blockUninstall, userId); 12181 mSettings.writePackageRestrictionsLPr(userId); 12182 } 12183 return true; 12184 } 12185 12186 @Override 12187 public boolean getBlockUninstallForUser(String packageName, int userId) { 12188 synchronized (mPackages) { 12189 PackageSetting ps = mSettings.mPackages.get(packageName); 12190 if (ps == null) { 12191 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12192 return false; 12193 } 12194 return ps.getBlockUninstall(userId); 12195 } 12196 } 12197 12198 /* 12199 * This method handles package deletion in general 12200 */ 12201 private boolean deletePackageLI(String packageName, UserHandle user, 12202 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12203 int flags, PackageRemovedInfo outInfo, 12204 boolean writeSettings) { 12205 if (packageName == null) { 12206 Slog.w(TAG, "Attempt to delete null packageName."); 12207 return false; 12208 } 12209 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12210 PackageSetting ps; 12211 boolean dataOnly = false; 12212 int removeUser = -1; 12213 int appId = -1; 12214 synchronized (mPackages) { 12215 ps = mSettings.mPackages.get(packageName); 12216 if (ps == null) { 12217 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12218 return false; 12219 } 12220 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12221 && user.getIdentifier() != UserHandle.USER_ALL) { 12222 // The caller is asking that the package only be deleted for a single 12223 // user. To do this, we just mark its uninstalled state and delete 12224 // its data. If this is a system app, we only allow this to happen if 12225 // they have set the special DELETE_SYSTEM_APP which requests different 12226 // semantics than normal for uninstalling system apps. 12227 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12228 ps.setUserState(user.getIdentifier(), 12229 COMPONENT_ENABLED_STATE_DEFAULT, 12230 false, //installed 12231 true, //stopped 12232 true, //notLaunched 12233 false, //hidden 12234 null, null, null, 12235 false, // blockUninstall 12236 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12237 if (!isSystemApp(ps)) { 12238 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12239 // Other user still have this package installed, so all 12240 // we need to do is clear this user's data and save that 12241 // it is uninstalled. 12242 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12243 removeUser = user.getIdentifier(); 12244 appId = ps.appId; 12245 scheduleWritePackageRestrictionsLocked(removeUser); 12246 } else { 12247 // We need to set it back to 'installed' so the uninstall 12248 // broadcasts will be sent correctly. 12249 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12250 ps.setInstalled(true, user.getIdentifier()); 12251 } 12252 } else { 12253 // This is a system app, so we assume that the 12254 // other users still have this package installed, so all 12255 // we need to do is clear this user's data and save that 12256 // it is uninstalled. 12257 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12258 removeUser = user.getIdentifier(); 12259 appId = ps.appId; 12260 scheduleWritePackageRestrictionsLocked(removeUser); 12261 } 12262 } 12263 } 12264 12265 if (removeUser >= 0) { 12266 // From above, we determined that we are deleting this only 12267 // for a single user. Continue the work here. 12268 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12269 if (outInfo != null) { 12270 outInfo.removedPackage = packageName; 12271 outInfo.removedAppId = appId; 12272 outInfo.removedUsers = new int[] {removeUser}; 12273 } 12274 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12275 removeKeystoreDataIfNeeded(removeUser, appId); 12276 schedulePackageCleaning(packageName, removeUser, false); 12277 synchronized (mPackages) { 12278 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12279 scheduleWritePackageRestrictionsLocked(removeUser); 12280 } 12281 } 12282 return true; 12283 } 12284 12285 if (dataOnly) { 12286 // Delete application data first 12287 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12288 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12289 return true; 12290 } 12291 12292 boolean ret = false; 12293 if (isSystemApp(ps)) { 12294 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12295 // When an updated system application is deleted we delete the existing resources as well and 12296 // fall back to existing code in system partition 12297 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12298 flags, outInfo, writeSettings); 12299 } else { 12300 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12301 // Kill application pre-emptively especially for apps on sd. 12302 killApplication(packageName, ps.appId, "uninstall pkg"); 12303 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12304 allUserHandles, perUserInstalled, 12305 outInfo, writeSettings); 12306 } 12307 12308 return ret; 12309 } 12310 12311 private final class ClearStorageConnection implements ServiceConnection { 12312 IMediaContainerService mContainerService; 12313 12314 @Override 12315 public void onServiceConnected(ComponentName name, IBinder service) { 12316 synchronized (this) { 12317 mContainerService = IMediaContainerService.Stub.asInterface(service); 12318 notifyAll(); 12319 } 12320 } 12321 12322 @Override 12323 public void onServiceDisconnected(ComponentName name) { 12324 } 12325 } 12326 12327 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12328 final boolean mounted; 12329 if (Environment.isExternalStorageEmulated()) { 12330 mounted = true; 12331 } else { 12332 final String status = Environment.getExternalStorageState(); 12333 12334 mounted = status.equals(Environment.MEDIA_MOUNTED) 12335 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12336 } 12337 12338 if (!mounted) { 12339 return; 12340 } 12341 12342 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12343 int[] users; 12344 if (userId == UserHandle.USER_ALL) { 12345 users = sUserManager.getUserIds(); 12346 } else { 12347 users = new int[] { userId }; 12348 } 12349 final ClearStorageConnection conn = new ClearStorageConnection(); 12350 if (mContext.bindServiceAsUser( 12351 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12352 try { 12353 for (int curUser : users) { 12354 long timeout = SystemClock.uptimeMillis() + 5000; 12355 synchronized (conn) { 12356 long now = SystemClock.uptimeMillis(); 12357 while (conn.mContainerService == null && now < timeout) { 12358 try { 12359 conn.wait(timeout - now); 12360 } catch (InterruptedException e) { 12361 } 12362 } 12363 } 12364 if (conn.mContainerService == null) { 12365 return; 12366 } 12367 12368 final UserEnvironment userEnv = new UserEnvironment(curUser); 12369 clearDirectory(conn.mContainerService, 12370 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12371 if (allData) { 12372 clearDirectory(conn.mContainerService, 12373 userEnv.buildExternalStorageAppDataDirs(packageName)); 12374 clearDirectory(conn.mContainerService, 12375 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12376 } 12377 } 12378 } finally { 12379 mContext.unbindService(conn); 12380 } 12381 } 12382 } 12383 12384 @Override 12385 public void clearApplicationUserData(final String packageName, 12386 final IPackageDataObserver observer, final int userId) { 12387 mContext.enforceCallingOrSelfPermission( 12388 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12389 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12390 // Queue up an async operation since the package deletion may take a little while. 12391 mHandler.post(new Runnable() { 12392 public void run() { 12393 mHandler.removeCallbacks(this); 12394 final boolean succeeded; 12395 synchronized (mInstallLock) { 12396 succeeded = clearApplicationUserDataLI(packageName, userId); 12397 } 12398 clearExternalStorageDataSync(packageName, userId, true); 12399 if (succeeded) { 12400 // invoke DeviceStorageMonitor's update method to clear any notifications 12401 DeviceStorageMonitorInternal 12402 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12403 if (dsm != null) { 12404 dsm.checkMemory(); 12405 } 12406 } 12407 if(observer != null) { 12408 try { 12409 observer.onRemoveCompleted(packageName, succeeded); 12410 } catch (RemoteException e) { 12411 Log.i(TAG, "Observer no longer exists."); 12412 } 12413 } //end if observer 12414 } //end run 12415 }); 12416 } 12417 12418 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12419 if (packageName == null) { 12420 Slog.w(TAG, "Attempt to delete null packageName."); 12421 return false; 12422 } 12423 12424 // Try finding details about the requested package 12425 PackageParser.Package pkg; 12426 synchronized (mPackages) { 12427 pkg = mPackages.get(packageName); 12428 if (pkg == null) { 12429 final PackageSetting ps = mSettings.mPackages.get(packageName); 12430 if (ps != null) { 12431 pkg = ps.pkg; 12432 } 12433 } 12434 } 12435 12436 if (pkg == null) { 12437 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12438 } 12439 12440 // Always delete data directories for package, even if we found no other 12441 // record of app. This helps users recover from UID mismatches without 12442 // resorting to a full data wipe. 12443 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12444 if (retCode < 0) { 12445 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12446 return false; 12447 } 12448 12449 if (pkg == null) { 12450 return false; 12451 } 12452 12453 if (pkg != null && pkg.applicationInfo != null) { 12454 final int appId = pkg.applicationInfo.uid; 12455 removeKeystoreDataIfNeeded(userId, appId); 12456 } 12457 12458 // Create a native library symlink only if we have native libraries 12459 // and if the native libraries are 32 bit libraries. We do not provide 12460 // this symlink for 64 bit libraries. 12461 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12462 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12463 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12464 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12465 nativeLibPath, userId) < 0) { 12466 Slog.w(TAG, "Failed linking native library dir"); 12467 return false; 12468 } 12469 } 12470 12471 return true; 12472 } 12473 12474 /** 12475 * Remove entries from the keystore daemon. Will only remove it if the 12476 * {@code appId} is valid. 12477 */ 12478 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12479 if (appId < 0) { 12480 return; 12481 } 12482 12483 final KeyStore keyStore = KeyStore.getInstance(); 12484 if (keyStore != null) { 12485 if (userId == UserHandle.USER_ALL) { 12486 for (final int individual : sUserManager.getUserIds()) { 12487 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12488 } 12489 } else { 12490 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12491 } 12492 } else { 12493 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12494 } 12495 } 12496 12497 @Override 12498 public void deleteApplicationCacheFiles(final String packageName, 12499 final IPackageDataObserver observer) { 12500 mContext.enforceCallingOrSelfPermission( 12501 android.Manifest.permission.DELETE_CACHE_FILES, null); 12502 // Queue up an async operation since the package deletion may take a little while. 12503 final int userId = UserHandle.getCallingUserId(); 12504 mHandler.post(new Runnable() { 12505 public void run() { 12506 mHandler.removeCallbacks(this); 12507 final boolean succeded; 12508 synchronized (mInstallLock) { 12509 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12510 } 12511 clearExternalStorageDataSync(packageName, userId, false); 12512 if (observer != null) { 12513 try { 12514 observer.onRemoveCompleted(packageName, succeded); 12515 } catch (RemoteException e) { 12516 Log.i(TAG, "Observer no longer exists."); 12517 } 12518 } //end if observer 12519 } //end run 12520 }); 12521 } 12522 12523 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12524 if (packageName == null) { 12525 Slog.w(TAG, "Attempt to delete null packageName."); 12526 return false; 12527 } 12528 PackageParser.Package p; 12529 synchronized (mPackages) { 12530 p = mPackages.get(packageName); 12531 } 12532 if (p == null) { 12533 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12534 return false; 12535 } 12536 final ApplicationInfo applicationInfo = p.applicationInfo; 12537 if (applicationInfo == null) { 12538 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12539 return false; 12540 } 12541 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12542 if (retCode < 0) { 12543 Slog.w(TAG, "Couldn't remove cache files for package: " 12544 + packageName + " u" + userId); 12545 return false; 12546 } 12547 return true; 12548 } 12549 12550 @Override 12551 public void getPackageSizeInfo(final String packageName, int userHandle, 12552 final IPackageStatsObserver observer) { 12553 mContext.enforceCallingOrSelfPermission( 12554 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12555 if (packageName == null) { 12556 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12557 } 12558 12559 PackageStats stats = new PackageStats(packageName, userHandle); 12560 12561 /* 12562 * Queue up an async operation since the package measurement may take a 12563 * little while. 12564 */ 12565 Message msg = mHandler.obtainMessage(INIT_COPY); 12566 msg.obj = new MeasureParams(stats, observer); 12567 mHandler.sendMessage(msg); 12568 } 12569 12570 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12571 PackageStats pStats) { 12572 if (packageName == null) { 12573 Slog.w(TAG, "Attempt to get size of null packageName."); 12574 return false; 12575 } 12576 PackageParser.Package p; 12577 boolean dataOnly = false; 12578 String libDirRoot = null; 12579 String asecPath = null; 12580 PackageSetting ps = null; 12581 synchronized (mPackages) { 12582 p = mPackages.get(packageName); 12583 ps = mSettings.mPackages.get(packageName); 12584 if(p == null) { 12585 dataOnly = true; 12586 if((ps == null) || (ps.pkg == null)) { 12587 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12588 return false; 12589 } 12590 p = ps.pkg; 12591 } 12592 if (ps != null) { 12593 libDirRoot = ps.legacyNativeLibraryPathString; 12594 } 12595 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12596 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12597 if (secureContainerId != null) { 12598 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12599 } 12600 } 12601 } 12602 String publicSrcDir = null; 12603 if(!dataOnly) { 12604 final ApplicationInfo applicationInfo = p.applicationInfo; 12605 if (applicationInfo == null) { 12606 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12607 return false; 12608 } 12609 if (p.isForwardLocked()) { 12610 publicSrcDir = applicationInfo.getBaseResourcePath(); 12611 } 12612 } 12613 // TODO: extend to measure size of split APKs 12614 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12615 // not just the first level. 12616 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12617 // just the primary. 12618 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12619 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12620 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12621 if (res < 0) { 12622 return false; 12623 } 12624 12625 // Fix-up for forward-locked applications in ASEC containers. 12626 if (!isExternal(p)) { 12627 pStats.codeSize += pStats.externalCodeSize; 12628 pStats.externalCodeSize = 0L; 12629 } 12630 12631 return true; 12632 } 12633 12634 12635 @Override 12636 public void addPackageToPreferred(String packageName) { 12637 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12638 } 12639 12640 @Override 12641 public void removePackageFromPreferred(String packageName) { 12642 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12643 } 12644 12645 @Override 12646 public List<PackageInfo> getPreferredPackages(int flags) { 12647 return new ArrayList<PackageInfo>(); 12648 } 12649 12650 private int getUidTargetSdkVersionLockedLPr(int uid) { 12651 Object obj = mSettings.getUserIdLPr(uid); 12652 if (obj instanceof SharedUserSetting) { 12653 final SharedUserSetting sus = (SharedUserSetting) obj; 12654 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12655 final Iterator<PackageSetting> it = sus.packages.iterator(); 12656 while (it.hasNext()) { 12657 final PackageSetting ps = it.next(); 12658 if (ps.pkg != null) { 12659 int v = ps.pkg.applicationInfo.targetSdkVersion; 12660 if (v < vers) vers = v; 12661 } 12662 } 12663 return vers; 12664 } else if (obj instanceof PackageSetting) { 12665 final PackageSetting ps = (PackageSetting) obj; 12666 if (ps.pkg != null) { 12667 return ps.pkg.applicationInfo.targetSdkVersion; 12668 } 12669 } 12670 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12671 } 12672 12673 @Override 12674 public void addPreferredActivity(IntentFilter filter, int match, 12675 ComponentName[] set, ComponentName activity, int userId) { 12676 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12677 "Adding preferred"); 12678 } 12679 12680 private void addPreferredActivityInternal(IntentFilter filter, int match, 12681 ComponentName[] set, ComponentName activity, boolean always, int userId, 12682 String opname) { 12683 // writer 12684 int callingUid = Binder.getCallingUid(); 12685 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12686 if (filter.countActions() == 0) { 12687 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12688 return; 12689 } 12690 synchronized (mPackages) { 12691 if (mContext.checkCallingOrSelfPermission( 12692 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12693 != PackageManager.PERMISSION_GRANTED) { 12694 if (getUidTargetSdkVersionLockedLPr(callingUid) 12695 < Build.VERSION_CODES.FROYO) { 12696 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12697 + callingUid); 12698 return; 12699 } 12700 mContext.enforceCallingOrSelfPermission( 12701 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12702 } 12703 12704 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12705 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12706 + userId + ":"); 12707 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12708 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12709 scheduleWritePackageRestrictionsLocked(userId); 12710 } 12711 } 12712 12713 @Override 12714 public void replacePreferredActivity(IntentFilter filter, int match, 12715 ComponentName[] set, ComponentName activity, int userId) { 12716 if (filter.countActions() != 1) { 12717 throw new IllegalArgumentException( 12718 "replacePreferredActivity expects filter to have only 1 action."); 12719 } 12720 if (filter.countDataAuthorities() != 0 12721 || filter.countDataPaths() != 0 12722 || filter.countDataSchemes() > 1 12723 || filter.countDataTypes() != 0) { 12724 throw new IllegalArgumentException( 12725 "replacePreferredActivity expects filter to have no data authorities, " + 12726 "paths, or types; and at most one scheme."); 12727 } 12728 12729 final int callingUid = Binder.getCallingUid(); 12730 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12731 synchronized (mPackages) { 12732 if (mContext.checkCallingOrSelfPermission( 12733 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12734 != PackageManager.PERMISSION_GRANTED) { 12735 if (getUidTargetSdkVersionLockedLPr(callingUid) 12736 < Build.VERSION_CODES.FROYO) { 12737 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12738 + Binder.getCallingUid()); 12739 return; 12740 } 12741 mContext.enforceCallingOrSelfPermission( 12742 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12743 } 12744 12745 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12746 if (pir != null) { 12747 // Get all of the existing entries that exactly match this filter. 12748 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12749 if (existing != null && existing.size() == 1) { 12750 PreferredActivity cur = existing.get(0); 12751 if (DEBUG_PREFERRED) { 12752 Slog.i(TAG, "Checking replace of preferred:"); 12753 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12754 if (!cur.mPref.mAlways) { 12755 Slog.i(TAG, " -- CUR; not mAlways!"); 12756 } else { 12757 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12758 Slog.i(TAG, " -- CUR: mSet=" 12759 + Arrays.toString(cur.mPref.mSetComponents)); 12760 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12761 Slog.i(TAG, " -- NEW: mMatch=" 12762 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12763 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12764 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12765 } 12766 } 12767 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12768 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12769 && cur.mPref.sameSet(set)) { 12770 // Setting the preferred activity to what it happens to be already 12771 if (DEBUG_PREFERRED) { 12772 Slog.i(TAG, "Replacing with same preferred activity " 12773 + cur.mPref.mShortComponent + " for user " 12774 + userId + ":"); 12775 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12776 } 12777 return; 12778 } 12779 } 12780 12781 if (existing != null) { 12782 if (DEBUG_PREFERRED) { 12783 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12784 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12785 } 12786 for (int i = 0; i < existing.size(); i++) { 12787 PreferredActivity pa = existing.get(i); 12788 if (DEBUG_PREFERRED) { 12789 Slog.i(TAG, "Removing existing preferred activity " 12790 + pa.mPref.mComponent + ":"); 12791 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12792 } 12793 pir.removeFilter(pa); 12794 } 12795 } 12796 } 12797 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12798 "Replacing preferred"); 12799 } 12800 } 12801 12802 @Override 12803 public void clearPackagePreferredActivities(String packageName) { 12804 final int uid = Binder.getCallingUid(); 12805 // writer 12806 synchronized (mPackages) { 12807 PackageParser.Package pkg = mPackages.get(packageName); 12808 if (pkg == null || pkg.applicationInfo.uid != uid) { 12809 if (mContext.checkCallingOrSelfPermission( 12810 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12811 != PackageManager.PERMISSION_GRANTED) { 12812 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12813 < Build.VERSION_CODES.FROYO) { 12814 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12815 + Binder.getCallingUid()); 12816 return; 12817 } 12818 mContext.enforceCallingOrSelfPermission( 12819 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12820 } 12821 } 12822 12823 int user = UserHandle.getCallingUserId(); 12824 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12825 scheduleWritePackageRestrictionsLocked(user); 12826 } 12827 } 12828 } 12829 12830 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12831 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12832 ArrayList<PreferredActivity> removed = null; 12833 boolean changed = false; 12834 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12835 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12836 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12837 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12838 continue; 12839 } 12840 Iterator<PreferredActivity> it = pir.filterIterator(); 12841 while (it.hasNext()) { 12842 PreferredActivity pa = it.next(); 12843 // Mark entry for removal only if it matches the package name 12844 // and the entry is of type "always". 12845 if (packageName == null || 12846 (pa.mPref.mComponent.getPackageName().equals(packageName) 12847 && pa.mPref.mAlways)) { 12848 if (removed == null) { 12849 removed = new ArrayList<PreferredActivity>(); 12850 } 12851 removed.add(pa); 12852 } 12853 } 12854 if (removed != null) { 12855 for (int j=0; j<removed.size(); j++) { 12856 PreferredActivity pa = removed.get(j); 12857 pir.removeFilter(pa); 12858 } 12859 changed = true; 12860 } 12861 } 12862 return changed; 12863 } 12864 12865 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12866 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12867 if (userId == UserHandle.USER_ALL) { 12868 if (mSettings.removeIntentFilterVerificationLPw(packageName, 12869 sUserManager.getUserIds())) { 12870 for (int oneUserId : sUserManager.getUserIds()) { 12871 scheduleWritePackageRestrictionsLocked(oneUserId); 12872 } 12873 } 12874 } else { 12875 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 12876 scheduleWritePackageRestrictionsLocked(userId); 12877 } 12878 } 12879 } 12880 12881 12882 void clearDefaultBrowserIfNeeded(String packageName) { 12883 for (int oneUserId : sUserManager.getUserIds()) { 12884 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 12885 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 12886 if (packageName.equals(defaultBrowserPackageName)) { 12887 setDefaultBrowserPackageName(null, oneUserId); 12888 } 12889 } 12890 } 12891 12892 @Override 12893 public void resetPreferredActivities(int userId) { 12894 /* TODO: Actually use userId. Why is it being passed in? */ 12895 mContext.enforceCallingOrSelfPermission( 12896 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12897 // writer 12898 synchronized (mPackages) { 12899 int user = UserHandle.getCallingUserId(); 12900 clearPackagePreferredActivitiesLPw(null, user); 12901 mSettings.readDefaultPreferredAppsLPw(this, user); 12902 scheduleWritePackageRestrictionsLocked(user); 12903 } 12904 } 12905 12906 @Override 12907 public int getPreferredActivities(List<IntentFilter> outFilters, 12908 List<ComponentName> outActivities, String packageName) { 12909 12910 int num = 0; 12911 final int userId = UserHandle.getCallingUserId(); 12912 // reader 12913 synchronized (mPackages) { 12914 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12915 if (pir != null) { 12916 final Iterator<PreferredActivity> it = pir.filterIterator(); 12917 while (it.hasNext()) { 12918 final PreferredActivity pa = it.next(); 12919 if (packageName == null 12920 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12921 && pa.mPref.mAlways)) { 12922 if (outFilters != null) { 12923 outFilters.add(new IntentFilter(pa)); 12924 } 12925 if (outActivities != null) { 12926 outActivities.add(pa.mPref.mComponent); 12927 } 12928 } 12929 } 12930 } 12931 } 12932 12933 return num; 12934 } 12935 12936 @Override 12937 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12938 int userId) { 12939 int callingUid = Binder.getCallingUid(); 12940 if (callingUid != Process.SYSTEM_UID) { 12941 throw new SecurityException( 12942 "addPersistentPreferredActivity can only be run by the system"); 12943 } 12944 if (filter.countActions() == 0) { 12945 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12946 return; 12947 } 12948 synchronized (mPackages) { 12949 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12950 " :"); 12951 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12952 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12953 new PersistentPreferredActivity(filter, activity)); 12954 scheduleWritePackageRestrictionsLocked(userId); 12955 } 12956 } 12957 12958 @Override 12959 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12960 int callingUid = Binder.getCallingUid(); 12961 if (callingUid != Process.SYSTEM_UID) { 12962 throw new SecurityException( 12963 "clearPackagePersistentPreferredActivities can only be run by the system"); 12964 } 12965 ArrayList<PersistentPreferredActivity> removed = null; 12966 boolean changed = false; 12967 synchronized (mPackages) { 12968 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12969 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12970 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12971 .valueAt(i); 12972 if (userId != thisUserId) { 12973 continue; 12974 } 12975 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12976 while (it.hasNext()) { 12977 PersistentPreferredActivity ppa = it.next(); 12978 // Mark entry for removal only if it matches the package name. 12979 if (ppa.mComponent.getPackageName().equals(packageName)) { 12980 if (removed == null) { 12981 removed = new ArrayList<PersistentPreferredActivity>(); 12982 } 12983 removed.add(ppa); 12984 } 12985 } 12986 if (removed != null) { 12987 for (int j=0; j<removed.size(); j++) { 12988 PersistentPreferredActivity ppa = removed.get(j); 12989 ppir.removeFilter(ppa); 12990 } 12991 changed = true; 12992 } 12993 } 12994 12995 if (changed) { 12996 scheduleWritePackageRestrictionsLocked(userId); 12997 } 12998 } 12999 } 13000 13001 /** 13002 * Non-Binder method, support for the backup/restore mechanism: write the 13003 * full set of preferred activities in its canonical XML format. Returns true 13004 * on success; false otherwise. 13005 */ 13006 @Override 13007 public byte[] getPreferredActivityBackup(int userId) { 13008 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13009 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13010 } 13011 13012 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13013 try { 13014 final XmlSerializer serializer = new FastXmlSerializer(); 13015 serializer.setOutput(dataStream, "utf-8"); 13016 serializer.startDocument(null, true); 13017 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13018 13019 synchronized (mPackages) { 13020 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13021 } 13022 13023 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13024 serializer.endDocument(); 13025 serializer.flush(); 13026 } catch (Exception e) { 13027 if (DEBUG_BACKUP) { 13028 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13029 } 13030 return null; 13031 } 13032 13033 return dataStream.toByteArray(); 13034 } 13035 13036 @Override 13037 public void restorePreferredActivities(byte[] backup, int userId) { 13038 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13039 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13040 } 13041 13042 try { 13043 final XmlPullParser parser = Xml.newPullParser(); 13044 parser.setInput(new ByteArrayInputStream(backup), null); 13045 13046 int type; 13047 while ((type = parser.next()) != XmlPullParser.START_TAG 13048 && type != XmlPullParser.END_DOCUMENT) { 13049 } 13050 if (type != XmlPullParser.START_TAG) { 13051 // oops didn't find a start tag?! 13052 if (DEBUG_BACKUP) { 13053 Slog.e(TAG, "Didn't find start tag during restore"); 13054 } 13055 return; 13056 } 13057 13058 // this is supposed to be TAG_PREFERRED_BACKUP 13059 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13060 if (DEBUG_BACKUP) { 13061 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13062 } 13063 return; 13064 } 13065 13066 // skip interfering stuff, then we're aligned with the backing implementation 13067 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13068 synchronized (mPackages) { 13069 mSettings.readPreferredActivitiesLPw(parser, userId); 13070 } 13071 } catch (Exception e) { 13072 if (DEBUG_BACKUP) { 13073 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13074 } 13075 } 13076 } 13077 13078 @Override 13079 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13080 int sourceUserId, int targetUserId, int flags) { 13081 mContext.enforceCallingOrSelfPermission( 13082 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13083 int callingUid = Binder.getCallingUid(); 13084 enforceOwnerRights(ownerPackage, callingUid); 13085 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13086 if (intentFilter.countActions() == 0) { 13087 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13088 return; 13089 } 13090 synchronized (mPackages) { 13091 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13092 ownerPackage, targetUserId, flags); 13093 CrossProfileIntentResolver resolver = 13094 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13095 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13096 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13097 if (existing != null) { 13098 int size = existing.size(); 13099 for (int i = 0; i < size; i++) { 13100 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13101 return; 13102 } 13103 } 13104 } 13105 resolver.addFilter(newFilter); 13106 scheduleWritePackageRestrictionsLocked(sourceUserId); 13107 } 13108 } 13109 13110 @Override 13111 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13112 mContext.enforceCallingOrSelfPermission( 13113 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13114 int callingUid = Binder.getCallingUid(); 13115 enforceOwnerRights(ownerPackage, callingUid); 13116 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13117 synchronized (mPackages) { 13118 CrossProfileIntentResolver resolver = 13119 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13120 ArraySet<CrossProfileIntentFilter> set = 13121 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13122 for (CrossProfileIntentFilter filter : set) { 13123 if (filter.getOwnerPackage().equals(ownerPackage)) { 13124 resolver.removeFilter(filter); 13125 } 13126 } 13127 scheduleWritePackageRestrictionsLocked(sourceUserId); 13128 } 13129 } 13130 13131 // Enforcing that callingUid is owning pkg on userId 13132 private void enforceOwnerRights(String pkg, int callingUid) { 13133 // The system owns everything. 13134 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13135 return; 13136 } 13137 int callingUserId = UserHandle.getUserId(callingUid); 13138 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13139 if (pi == null) { 13140 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13141 + callingUserId); 13142 } 13143 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13144 throw new SecurityException("Calling uid " + callingUid 13145 + " does not own package " + pkg); 13146 } 13147 } 13148 13149 @Override 13150 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13151 Intent intent = new Intent(Intent.ACTION_MAIN); 13152 intent.addCategory(Intent.CATEGORY_HOME); 13153 13154 final int callingUserId = UserHandle.getCallingUserId(); 13155 List<ResolveInfo> list = queryIntentActivities(intent, null, 13156 PackageManager.GET_META_DATA, callingUserId); 13157 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13158 true, false, false, callingUserId); 13159 13160 allHomeCandidates.clear(); 13161 if (list != null) { 13162 for (ResolveInfo ri : list) { 13163 allHomeCandidates.add(ri); 13164 } 13165 } 13166 return (preferred == null || preferred.activityInfo == null) 13167 ? null 13168 : new ComponentName(preferred.activityInfo.packageName, 13169 preferred.activityInfo.name); 13170 } 13171 13172 @Override 13173 public void setApplicationEnabledSetting(String appPackageName, 13174 int newState, int flags, int userId, String callingPackage) { 13175 if (!sUserManager.exists(userId)) return; 13176 if (callingPackage == null) { 13177 callingPackage = Integer.toString(Binder.getCallingUid()); 13178 } 13179 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13180 } 13181 13182 @Override 13183 public void setComponentEnabledSetting(ComponentName componentName, 13184 int newState, int flags, int userId) { 13185 if (!sUserManager.exists(userId)) return; 13186 setEnabledSetting(componentName.getPackageName(), 13187 componentName.getClassName(), newState, flags, userId, null); 13188 } 13189 13190 private void setEnabledSetting(final String packageName, String className, int newState, 13191 final int flags, int userId, String callingPackage) { 13192 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13193 || newState == COMPONENT_ENABLED_STATE_ENABLED 13194 || newState == COMPONENT_ENABLED_STATE_DISABLED 13195 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13196 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13197 throw new IllegalArgumentException("Invalid new component state: " 13198 + newState); 13199 } 13200 PackageSetting pkgSetting; 13201 final int uid = Binder.getCallingUid(); 13202 final int permission = mContext.checkCallingOrSelfPermission( 13203 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13204 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13205 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13206 boolean sendNow = false; 13207 boolean isApp = (className == null); 13208 String componentName = isApp ? packageName : className; 13209 int packageUid = -1; 13210 ArrayList<String> components; 13211 13212 // writer 13213 synchronized (mPackages) { 13214 pkgSetting = mSettings.mPackages.get(packageName); 13215 if (pkgSetting == null) { 13216 if (className == null) { 13217 throw new IllegalArgumentException( 13218 "Unknown package: " + packageName); 13219 } 13220 throw new IllegalArgumentException( 13221 "Unknown component: " + packageName 13222 + "/" + className); 13223 } 13224 // Allow root and verify that userId is not being specified by a different user 13225 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13226 throw new SecurityException( 13227 "Permission Denial: attempt to change component state from pid=" 13228 + Binder.getCallingPid() 13229 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13230 } 13231 if (className == null) { 13232 // We're dealing with an application/package level state change 13233 if (pkgSetting.getEnabled(userId) == newState) { 13234 // Nothing to do 13235 return; 13236 } 13237 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13238 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13239 // Don't care about who enables an app. 13240 callingPackage = null; 13241 } 13242 pkgSetting.setEnabled(newState, userId, callingPackage); 13243 // pkgSetting.pkg.mSetEnabled = newState; 13244 } else { 13245 // We're dealing with a component level state change 13246 // First, verify that this is a valid class name. 13247 PackageParser.Package pkg = pkgSetting.pkg; 13248 if (pkg == null || !pkg.hasComponentClassName(className)) { 13249 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13250 throw new IllegalArgumentException("Component class " + className 13251 + " does not exist in " + packageName); 13252 } else { 13253 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13254 + className + " does not exist in " + packageName); 13255 } 13256 } 13257 switch (newState) { 13258 case COMPONENT_ENABLED_STATE_ENABLED: 13259 if (!pkgSetting.enableComponentLPw(className, userId)) { 13260 return; 13261 } 13262 break; 13263 case COMPONENT_ENABLED_STATE_DISABLED: 13264 if (!pkgSetting.disableComponentLPw(className, userId)) { 13265 return; 13266 } 13267 break; 13268 case COMPONENT_ENABLED_STATE_DEFAULT: 13269 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13270 return; 13271 } 13272 break; 13273 default: 13274 Slog.e(TAG, "Invalid new component state: " + newState); 13275 return; 13276 } 13277 } 13278 scheduleWritePackageRestrictionsLocked(userId); 13279 components = mPendingBroadcasts.get(userId, packageName); 13280 final boolean newPackage = components == null; 13281 if (newPackage) { 13282 components = new ArrayList<String>(); 13283 } 13284 if (!components.contains(componentName)) { 13285 components.add(componentName); 13286 } 13287 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13288 sendNow = true; 13289 // Purge entry from pending broadcast list if another one exists already 13290 // since we are sending one right away. 13291 mPendingBroadcasts.remove(userId, packageName); 13292 } else { 13293 if (newPackage) { 13294 mPendingBroadcasts.put(userId, packageName, components); 13295 } 13296 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13297 // Schedule a message 13298 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13299 } 13300 } 13301 } 13302 13303 long callingId = Binder.clearCallingIdentity(); 13304 try { 13305 if (sendNow) { 13306 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13307 sendPackageChangedBroadcast(packageName, 13308 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13309 } 13310 } finally { 13311 Binder.restoreCallingIdentity(callingId); 13312 } 13313 } 13314 13315 private void sendPackageChangedBroadcast(String packageName, 13316 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13317 if (DEBUG_INSTALL) 13318 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13319 + componentNames); 13320 Bundle extras = new Bundle(4); 13321 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13322 String nameList[] = new String[componentNames.size()]; 13323 componentNames.toArray(nameList); 13324 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13325 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13326 extras.putInt(Intent.EXTRA_UID, packageUid); 13327 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13328 new int[] {UserHandle.getUserId(packageUid)}); 13329 } 13330 13331 @Override 13332 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13333 if (!sUserManager.exists(userId)) return; 13334 final int uid = Binder.getCallingUid(); 13335 final int permission = mContext.checkCallingOrSelfPermission( 13336 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13337 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13338 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13339 // writer 13340 synchronized (mPackages) { 13341 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13342 allowedByPermission, uid, userId)) { 13343 scheduleWritePackageRestrictionsLocked(userId); 13344 } 13345 } 13346 } 13347 13348 @Override 13349 public String getInstallerPackageName(String packageName) { 13350 // reader 13351 synchronized (mPackages) { 13352 return mSettings.getInstallerPackageNameLPr(packageName); 13353 } 13354 } 13355 13356 @Override 13357 public int getApplicationEnabledSetting(String packageName, int userId) { 13358 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13359 int uid = Binder.getCallingUid(); 13360 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13361 // reader 13362 synchronized (mPackages) { 13363 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13364 } 13365 } 13366 13367 @Override 13368 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13369 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13370 int uid = Binder.getCallingUid(); 13371 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13372 // reader 13373 synchronized (mPackages) { 13374 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13375 } 13376 } 13377 13378 @Override 13379 public void enterSafeMode() { 13380 enforceSystemOrRoot("Only the system can request entering safe mode"); 13381 13382 if (!mSystemReady) { 13383 mSafeMode = true; 13384 } 13385 } 13386 13387 @Override 13388 public void systemReady() { 13389 mSystemReady = true; 13390 13391 // Read the compatibilty setting when the system is ready. 13392 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13393 mContext.getContentResolver(), 13394 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13395 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13396 if (DEBUG_SETTINGS) { 13397 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13398 } 13399 13400 synchronized (mPackages) { 13401 // Verify that all of the preferred activity components actually 13402 // exist. It is possible for applications to be updated and at 13403 // that point remove a previously declared activity component that 13404 // had been set as a preferred activity. We try to clean this up 13405 // the next time we encounter that preferred activity, but it is 13406 // possible for the user flow to never be able to return to that 13407 // situation so here we do a sanity check to make sure we haven't 13408 // left any junk around. 13409 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13410 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13411 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13412 removed.clear(); 13413 for (PreferredActivity pa : pir.filterSet()) { 13414 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13415 removed.add(pa); 13416 } 13417 } 13418 if (removed.size() > 0) { 13419 for (int r=0; r<removed.size(); r++) { 13420 PreferredActivity pa = removed.get(r); 13421 Slog.w(TAG, "Removing dangling preferred activity: " 13422 + pa.mPref.mComponent); 13423 pir.removeFilter(pa); 13424 } 13425 mSettings.writePackageRestrictionsLPr( 13426 mSettings.mPreferredActivities.keyAt(i)); 13427 } 13428 } 13429 } 13430 sUserManager.systemReady(); 13431 13432 // Kick off any messages waiting for system ready 13433 if (mPostSystemReadyMessages != null) { 13434 for (Message msg : mPostSystemReadyMessages) { 13435 msg.sendToTarget(); 13436 } 13437 mPostSystemReadyMessages = null; 13438 } 13439 13440 // Watch for external volumes that come and go over time 13441 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13442 storage.registerListener(mStorageListener); 13443 13444 mInstallerService.systemReady(); 13445 } 13446 13447 @Override 13448 public boolean isSafeMode() { 13449 return mSafeMode; 13450 } 13451 13452 @Override 13453 public boolean hasSystemUidErrors() { 13454 return mHasSystemUidErrors; 13455 } 13456 13457 static String arrayToString(int[] array) { 13458 StringBuffer buf = new StringBuffer(128); 13459 buf.append('['); 13460 if (array != null) { 13461 for (int i=0; i<array.length; i++) { 13462 if (i > 0) buf.append(", "); 13463 buf.append(array[i]); 13464 } 13465 } 13466 buf.append(']'); 13467 return buf.toString(); 13468 } 13469 13470 static class DumpState { 13471 public static final int DUMP_LIBS = 1 << 0; 13472 public static final int DUMP_FEATURES = 1 << 1; 13473 public static final int DUMP_RESOLVERS = 1 << 2; 13474 public static final int DUMP_PERMISSIONS = 1 << 3; 13475 public static final int DUMP_PACKAGES = 1 << 4; 13476 public static final int DUMP_SHARED_USERS = 1 << 5; 13477 public static final int DUMP_MESSAGES = 1 << 6; 13478 public static final int DUMP_PROVIDERS = 1 << 7; 13479 public static final int DUMP_VERIFIERS = 1 << 8; 13480 public static final int DUMP_PREFERRED = 1 << 9; 13481 public static final int DUMP_PREFERRED_XML = 1 << 10; 13482 public static final int DUMP_KEYSETS = 1 << 11; 13483 public static final int DUMP_VERSION = 1 << 12; 13484 public static final int DUMP_INSTALLS = 1 << 13; 13485 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13486 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13487 13488 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13489 13490 private int mTypes; 13491 13492 private int mOptions; 13493 13494 private boolean mTitlePrinted; 13495 13496 private SharedUserSetting mSharedUser; 13497 13498 public boolean isDumping(int type) { 13499 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13500 return true; 13501 } 13502 13503 return (mTypes & type) != 0; 13504 } 13505 13506 public void setDump(int type) { 13507 mTypes |= type; 13508 } 13509 13510 public boolean isOptionEnabled(int option) { 13511 return (mOptions & option) != 0; 13512 } 13513 13514 public void setOptionEnabled(int option) { 13515 mOptions |= option; 13516 } 13517 13518 public boolean onTitlePrinted() { 13519 final boolean printed = mTitlePrinted; 13520 mTitlePrinted = true; 13521 return printed; 13522 } 13523 13524 public boolean getTitlePrinted() { 13525 return mTitlePrinted; 13526 } 13527 13528 public void setTitlePrinted(boolean enabled) { 13529 mTitlePrinted = enabled; 13530 } 13531 13532 public SharedUserSetting getSharedUser() { 13533 return mSharedUser; 13534 } 13535 13536 public void setSharedUser(SharedUserSetting user) { 13537 mSharedUser = user; 13538 } 13539 } 13540 13541 @Override 13542 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13543 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13544 != PackageManager.PERMISSION_GRANTED) { 13545 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13546 + Binder.getCallingPid() 13547 + ", uid=" + Binder.getCallingUid() 13548 + " without permission " 13549 + android.Manifest.permission.DUMP); 13550 return; 13551 } 13552 13553 DumpState dumpState = new DumpState(); 13554 boolean fullPreferred = false; 13555 boolean checkin = false; 13556 13557 String packageName = null; 13558 13559 int opti = 0; 13560 while (opti < args.length) { 13561 String opt = args[opti]; 13562 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13563 break; 13564 } 13565 opti++; 13566 13567 if ("-a".equals(opt)) { 13568 // Right now we only know how to print all. 13569 } else if ("-h".equals(opt)) { 13570 pw.println("Package manager dump options:"); 13571 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13572 pw.println(" --checkin: dump for a checkin"); 13573 pw.println(" -f: print details of intent filters"); 13574 pw.println(" -h: print this help"); 13575 pw.println(" cmd may be one of:"); 13576 pw.println(" l[ibraries]: list known shared libraries"); 13577 pw.println(" f[ibraries]: list device features"); 13578 pw.println(" k[eysets]: print known keysets"); 13579 pw.println(" r[esolvers]: dump intent resolvers"); 13580 pw.println(" perm[issions]: dump permissions"); 13581 pw.println(" pref[erred]: print preferred package settings"); 13582 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13583 pw.println(" prov[iders]: dump content providers"); 13584 pw.println(" p[ackages]: dump installed packages"); 13585 pw.println(" s[hared-users]: dump shared user IDs"); 13586 pw.println(" m[essages]: print collected runtime messages"); 13587 pw.println(" v[erifiers]: print package verifier info"); 13588 pw.println(" version: print database version info"); 13589 pw.println(" write: write current settings now"); 13590 pw.println(" <package.name>: info about given package"); 13591 pw.println(" installs: details about install sessions"); 13592 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13593 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13594 return; 13595 } else if ("--checkin".equals(opt)) { 13596 checkin = true; 13597 } else if ("-f".equals(opt)) { 13598 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13599 } else { 13600 pw.println("Unknown argument: " + opt + "; use -h for help"); 13601 } 13602 } 13603 13604 // Is the caller requesting to dump a particular piece of data? 13605 if (opti < args.length) { 13606 String cmd = args[opti]; 13607 opti++; 13608 // Is this a package name? 13609 if ("android".equals(cmd) || cmd.contains(".")) { 13610 packageName = cmd; 13611 // When dumping a single package, we always dump all of its 13612 // filter information since the amount of data will be reasonable. 13613 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13614 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13615 dumpState.setDump(DumpState.DUMP_LIBS); 13616 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13617 dumpState.setDump(DumpState.DUMP_FEATURES); 13618 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13619 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13620 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13621 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13622 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13623 dumpState.setDump(DumpState.DUMP_PREFERRED); 13624 } else if ("preferred-xml".equals(cmd)) { 13625 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13626 if (opti < args.length && "--full".equals(args[opti])) { 13627 fullPreferred = true; 13628 opti++; 13629 } 13630 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13631 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13632 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13633 dumpState.setDump(DumpState.DUMP_PACKAGES); 13634 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13635 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13636 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13637 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13638 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13639 dumpState.setDump(DumpState.DUMP_MESSAGES); 13640 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13641 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13642 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13643 || "intent-filter-verifiers".equals(cmd)) { 13644 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13645 } else if ("version".equals(cmd)) { 13646 dumpState.setDump(DumpState.DUMP_VERSION); 13647 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13648 dumpState.setDump(DumpState.DUMP_KEYSETS); 13649 } else if ("installs".equals(cmd)) { 13650 dumpState.setDump(DumpState.DUMP_INSTALLS); 13651 } else if ("write".equals(cmd)) { 13652 synchronized (mPackages) { 13653 mSettings.writeLPr(); 13654 pw.println("Settings written."); 13655 return; 13656 } 13657 } 13658 } 13659 13660 if (checkin) { 13661 pw.println("vers,1"); 13662 } 13663 13664 // reader 13665 synchronized (mPackages) { 13666 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13667 if (!checkin) { 13668 if (dumpState.onTitlePrinted()) 13669 pw.println(); 13670 pw.println("Database versions:"); 13671 pw.print(" SDK Version:"); 13672 pw.print(" internal="); 13673 pw.print(mSettings.mInternalSdkPlatform); 13674 pw.print(" external="); 13675 pw.println(mSettings.mExternalSdkPlatform); 13676 pw.print(" DB Version:"); 13677 pw.print(" internal="); 13678 pw.print(mSettings.mInternalDatabaseVersion); 13679 pw.print(" external="); 13680 pw.println(mSettings.mExternalDatabaseVersion); 13681 } 13682 } 13683 13684 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13685 if (!checkin) { 13686 if (dumpState.onTitlePrinted()) 13687 pw.println(); 13688 pw.println("Verifiers:"); 13689 pw.print(" Required: "); 13690 pw.print(mRequiredVerifierPackage); 13691 pw.print(" (uid="); 13692 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13693 pw.println(")"); 13694 } else if (mRequiredVerifierPackage != null) { 13695 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13696 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13697 } 13698 } 13699 13700 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13701 packageName == null) { 13702 if (mIntentFilterVerifierComponent != null) { 13703 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13704 if (!checkin) { 13705 if (dumpState.onTitlePrinted()) 13706 pw.println(); 13707 pw.println("Intent Filter Verifier:"); 13708 pw.print(" Using: "); 13709 pw.print(verifierPackageName); 13710 pw.print(" (uid="); 13711 pw.print(getPackageUid(verifierPackageName, 0)); 13712 pw.println(")"); 13713 } else if (verifierPackageName != null) { 13714 pw.print("ifv,"); pw.print(verifierPackageName); 13715 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13716 } 13717 } else { 13718 pw.println(); 13719 pw.println("No Intent Filter Verifier available!"); 13720 } 13721 } 13722 13723 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13724 boolean printedHeader = false; 13725 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13726 while (it.hasNext()) { 13727 String name = it.next(); 13728 SharedLibraryEntry ent = mSharedLibraries.get(name); 13729 if (!checkin) { 13730 if (!printedHeader) { 13731 if (dumpState.onTitlePrinted()) 13732 pw.println(); 13733 pw.println("Libraries:"); 13734 printedHeader = true; 13735 } 13736 pw.print(" "); 13737 } else { 13738 pw.print("lib,"); 13739 } 13740 pw.print(name); 13741 if (!checkin) { 13742 pw.print(" -> "); 13743 } 13744 if (ent.path != null) { 13745 if (!checkin) { 13746 pw.print("(jar) "); 13747 pw.print(ent.path); 13748 } else { 13749 pw.print(",jar,"); 13750 pw.print(ent.path); 13751 } 13752 } else { 13753 if (!checkin) { 13754 pw.print("(apk) "); 13755 pw.print(ent.apk); 13756 } else { 13757 pw.print(",apk,"); 13758 pw.print(ent.apk); 13759 } 13760 } 13761 pw.println(); 13762 } 13763 } 13764 13765 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13766 if (dumpState.onTitlePrinted()) 13767 pw.println(); 13768 if (!checkin) { 13769 pw.println("Features:"); 13770 } 13771 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13772 while (it.hasNext()) { 13773 String name = it.next(); 13774 if (!checkin) { 13775 pw.print(" "); 13776 } else { 13777 pw.print("feat,"); 13778 } 13779 pw.println(name); 13780 } 13781 } 13782 13783 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13784 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13785 : "Activity Resolver Table:", " ", packageName, 13786 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13787 dumpState.setTitlePrinted(true); 13788 } 13789 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13790 : "Receiver Resolver Table:", " ", packageName, 13791 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13792 dumpState.setTitlePrinted(true); 13793 } 13794 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13795 : "Service Resolver Table:", " ", packageName, 13796 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13797 dumpState.setTitlePrinted(true); 13798 } 13799 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13800 : "Provider Resolver Table:", " ", packageName, 13801 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13802 dumpState.setTitlePrinted(true); 13803 } 13804 } 13805 13806 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13807 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13808 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13809 int user = mSettings.mPreferredActivities.keyAt(i); 13810 if (pir.dump(pw, 13811 dumpState.getTitlePrinted() 13812 ? "\nPreferred Activities User " + user + ":" 13813 : "Preferred Activities User " + user + ":", " ", 13814 packageName, true, false)) { 13815 dumpState.setTitlePrinted(true); 13816 } 13817 } 13818 } 13819 13820 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13821 pw.flush(); 13822 FileOutputStream fout = new FileOutputStream(fd); 13823 BufferedOutputStream str = new BufferedOutputStream(fout); 13824 XmlSerializer serializer = new FastXmlSerializer(); 13825 try { 13826 serializer.setOutput(str, "utf-8"); 13827 serializer.startDocument(null, true); 13828 serializer.setFeature( 13829 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13830 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13831 serializer.endDocument(); 13832 serializer.flush(); 13833 } catch (IllegalArgumentException e) { 13834 pw.println("Failed writing: " + e); 13835 } catch (IllegalStateException e) { 13836 pw.println("Failed writing: " + e); 13837 } catch (IOException e) { 13838 pw.println("Failed writing: " + e); 13839 } 13840 } 13841 13842 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13843 pw.println(); 13844 int count = mSettings.mPackages.size(); 13845 if (count == 0) { 13846 pw.println("No domain preferred apps!"); 13847 pw.println(); 13848 } else { 13849 final String prefix = " "; 13850 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13851 if (allPackageSettings.size() == 0) { 13852 pw.println("No domain preferred apps!"); 13853 pw.println(); 13854 } else { 13855 pw.println("Domain preferred apps status:"); 13856 pw.println(); 13857 count = 0; 13858 for (PackageSetting ps : allPackageSettings) { 13859 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13860 if (ivi == null || ivi.getPackageName() == null) continue; 13861 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13862 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13863 pw.println(prefix + "Status: " + ivi.getStatusString()); 13864 pw.println(); 13865 count++; 13866 } 13867 if (count == 0) { 13868 pw.println(prefix + "No domain preferred app status!"); 13869 pw.println(); 13870 } 13871 for (int userId : sUserManager.getUserIds()) { 13872 pw.println("Domain preferred apps for User " + userId + ":"); 13873 pw.println(); 13874 count = 0; 13875 for (PackageSetting ps : allPackageSettings) { 13876 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13877 if (ivi == null || ivi.getPackageName() == null) { 13878 continue; 13879 } 13880 final int status = ps.getDomainVerificationStatusForUser(userId); 13881 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13882 continue; 13883 } 13884 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13885 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13886 String statusStr = IntentFilterVerificationInfo. 13887 getStatusStringFromValue(status); 13888 pw.println(prefix + "Status: " + statusStr); 13889 pw.println(); 13890 count++; 13891 } 13892 if (count == 0) { 13893 pw.println(prefix + "No domain preferred apps!"); 13894 pw.println(); 13895 } 13896 } 13897 } 13898 } 13899 } 13900 13901 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13902 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13903 if (packageName == null) { 13904 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13905 if (iperm == 0) { 13906 if (dumpState.onTitlePrinted()) 13907 pw.println(); 13908 pw.println("AppOp Permissions:"); 13909 } 13910 pw.print(" AppOp Permission "); 13911 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13912 pw.println(":"); 13913 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13914 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13915 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13916 } 13917 } 13918 } 13919 } 13920 13921 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13922 boolean printedSomething = false; 13923 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13924 if (packageName != null && !packageName.equals(p.info.packageName)) { 13925 continue; 13926 } 13927 if (!printedSomething) { 13928 if (dumpState.onTitlePrinted()) 13929 pw.println(); 13930 pw.println("Registered ContentProviders:"); 13931 printedSomething = true; 13932 } 13933 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13934 pw.print(" "); pw.println(p.toString()); 13935 } 13936 printedSomething = false; 13937 for (Map.Entry<String, PackageParser.Provider> entry : 13938 mProvidersByAuthority.entrySet()) { 13939 PackageParser.Provider p = entry.getValue(); 13940 if (packageName != null && !packageName.equals(p.info.packageName)) { 13941 continue; 13942 } 13943 if (!printedSomething) { 13944 if (dumpState.onTitlePrinted()) 13945 pw.println(); 13946 pw.println("ContentProvider Authorities:"); 13947 printedSomething = true; 13948 } 13949 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13950 pw.print(" "); pw.println(p.toString()); 13951 if (p.info != null && p.info.applicationInfo != null) { 13952 final String appInfo = p.info.applicationInfo.toString(); 13953 pw.print(" applicationInfo="); pw.println(appInfo); 13954 } 13955 } 13956 } 13957 13958 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13959 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13960 } 13961 13962 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13963 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13964 } 13965 13966 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13967 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13968 } 13969 13970 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13971 // XXX should handle packageName != null by dumping only install data that 13972 // the given package is involved with. 13973 if (dumpState.onTitlePrinted()) pw.println(); 13974 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13975 } 13976 13977 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13978 if (dumpState.onTitlePrinted()) pw.println(); 13979 mSettings.dumpReadMessagesLPr(pw, dumpState); 13980 13981 pw.println(); 13982 pw.println("Package warning messages:"); 13983 BufferedReader in = null; 13984 String line = null; 13985 try { 13986 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13987 while ((line = in.readLine()) != null) { 13988 if (line.contains("ignored: updated version")) continue; 13989 pw.println(line); 13990 } 13991 } catch (IOException ignored) { 13992 } finally { 13993 IoUtils.closeQuietly(in); 13994 } 13995 } 13996 13997 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13998 BufferedReader in = null; 13999 String line = null; 14000 try { 14001 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14002 while ((line = in.readLine()) != null) { 14003 if (line.contains("ignored: updated version")) continue; 14004 pw.print("msg,"); 14005 pw.println(line); 14006 } 14007 } catch (IOException ignored) { 14008 } finally { 14009 IoUtils.closeQuietly(in); 14010 } 14011 } 14012 } 14013 } 14014 14015 // ------- apps on sdcard specific code ------- 14016 static final boolean DEBUG_SD_INSTALL = false; 14017 14018 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14019 14020 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14021 14022 private boolean mMediaMounted = false; 14023 14024 static String getEncryptKey() { 14025 try { 14026 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14027 SD_ENCRYPTION_KEYSTORE_NAME); 14028 if (sdEncKey == null) { 14029 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14030 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14031 if (sdEncKey == null) { 14032 Slog.e(TAG, "Failed to create encryption keys"); 14033 return null; 14034 } 14035 } 14036 return sdEncKey; 14037 } catch (NoSuchAlgorithmException nsae) { 14038 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14039 return null; 14040 } catch (IOException ioe) { 14041 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14042 return null; 14043 } 14044 } 14045 14046 /* 14047 * Update media status on PackageManager. 14048 */ 14049 @Override 14050 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14051 int callingUid = Binder.getCallingUid(); 14052 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14053 throw new SecurityException("Media status can only be updated by the system"); 14054 } 14055 // reader; this apparently protects mMediaMounted, but should probably 14056 // be a different lock in that case. 14057 synchronized (mPackages) { 14058 Log.i(TAG, "Updating external media status from " 14059 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14060 + (mediaStatus ? "mounted" : "unmounted")); 14061 if (DEBUG_SD_INSTALL) 14062 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14063 + ", mMediaMounted=" + mMediaMounted); 14064 if (mediaStatus == mMediaMounted) { 14065 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14066 : 0, -1); 14067 mHandler.sendMessage(msg); 14068 return; 14069 } 14070 mMediaMounted = mediaStatus; 14071 } 14072 // Queue up an async operation since the package installation may take a 14073 // little while. 14074 mHandler.post(new Runnable() { 14075 public void run() { 14076 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14077 } 14078 }); 14079 } 14080 14081 /** 14082 * Called by MountService when the initial ASECs to scan are available. 14083 * Should block until all the ASEC containers are finished being scanned. 14084 */ 14085 public void scanAvailableAsecs() { 14086 updateExternalMediaStatusInner(true, false, false); 14087 if (mShouldRestoreconData) { 14088 SELinuxMMAC.setRestoreconDone(); 14089 mShouldRestoreconData = false; 14090 } 14091 } 14092 14093 /* 14094 * Collect information of applications on external media, map them against 14095 * existing containers and update information based on current mount status. 14096 * Please note that we always have to report status if reportStatus has been 14097 * set to true especially when unloading packages. 14098 */ 14099 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14100 boolean externalStorage) { 14101 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14102 int[] uidArr = EmptyArray.INT; 14103 14104 final String[] list = PackageHelper.getSecureContainerList(); 14105 if (ArrayUtils.isEmpty(list)) { 14106 Log.i(TAG, "No secure containers found"); 14107 } else { 14108 // Process list of secure containers and categorize them 14109 // as active or stale based on their package internal state. 14110 14111 // reader 14112 synchronized (mPackages) { 14113 for (String cid : list) { 14114 // Leave stages untouched for now; installer service owns them 14115 if (PackageInstallerService.isStageName(cid)) continue; 14116 14117 if (DEBUG_SD_INSTALL) 14118 Log.i(TAG, "Processing container " + cid); 14119 String pkgName = getAsecPackageName(cid); 14120 if (pkgName == null) { 14121 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14122 continue; 14123 } 14124 if (DEBUG_SD_INSTALL) 14125 Log.i(TAG, "Looking for pkg : " + pkgName); 14126 14127 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14128 if (ps == null) { 14129 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14130 continue; 14131 } 14132 14133 /* 14134 * Skip packages that are not external if we're unmounting 14135 * external storage. 14136 */ 14137 if (externalStorage && !isMounted && !isExternal(ps)) { 14138 continue; 14139 } 14140 14141 final AsecInstallArgs args = new AsecInstallArgs(cid, 14142 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14143 // The package status is changed only if the code path 14144 // matches between settings and the container id. 14145 if (ps.codePathString != null 14146 && ps.codePathString.startsWith(args.getCodePath())) { 14147 if (DEBUG_SD_INSTALL) { 14148 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14149 + " at code path: " + ps.codePathString); 14150 } 14151 14152 // We do have a valid package installed on sdcard 14153 processCids.put(args, ps.codePathString); 14154 final int uid = ps.appId; 14155 if (uid != -1) { 14156 uidArr = ArrayUtils.appendInt(uidArr, uid); 14157 } 14158 } else { 14159 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14160 + ps.codePathString); 14161 } 14162 } 14163 } 14164 14165 Arrays.sort(uidArr); 14166 } 14167 14168 // Process packages with valid entries. 14169 if (isMounted) { 14170 if (DEBUG_SD_INSTALL) 14171 Log.i(TAG, "Loading packages"); 14172 loadMediaPackages(processCids, uidArr); 14173 startCleaningPackages(); 14174 mInstallerService.onSecureContainersAvailable(); 14175 } else { 14176 if (DEBUG_SD_INSTALL) 14177 Log.i(TAG, "Unloading packages"); 14178 unloadMediaPackages(processCids, uidArr, reportStatus); 14179 } 14180 } 14181 14182 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14183 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14184 final int size = infos.size(); 14185 final String[] packageNames = new String[size]; 14186 final int[] packageUids = new int[size]; 14187 for (int i = 0; i < size; i++) { 14188 final ApplicationInfo info = infos.get(i); 14189 packageNames[i] = info.packageName; 14190 packageUids[i] = info.uid; 14191 } 14192 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14193 finishedReceiver); 14194 } 14195 14196 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14197 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14198 sendResourcesChangedBroadcast(mediaStatus, replacing, 14199 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14200 } 14201 14202 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14203 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14204 int size = pkgList.length; 14205 if (size > 0) { 14206 // Send broadcasts here 14207 Bundle extras = new Bundle(); 14208 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14209 if (uidArr != null) { 14210 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14211 } 14212 if (replacing) { 14213 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14214 } 14215 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14216 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14217 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14218 } 14219 } 14220 14221 /* 14222 * Look at potentially valid container ids from processCids If package 14223 * information doesn't match the one on record or package scanning fails, 14224 * the cid is added to list of removeCids. We currently don't delete stale 14225 * containers. 14226 */ 14227 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14228 ArrayList<String> pkgList = new ArrayList<String>(); 14229 Set<AsecInstallArgs> keys = processCids.keySet(); 14230 14231 for (AsecInstallArgs args : keys) { 14232 String codePath = processCids.get(args); 14233 if (DEBUG_SD_INSTALL) 14234 Log.i(TAG, "Loading container : " + args.cid); 14235 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14236 try { 14237 // Make sure there are no container errors first. 14238 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14239 Slog.e(TAG, "Failed to mount cid : " + args.cid 14240 + " when installing from sdcard"); 14241 continue; 14242 } 14243 // Check code path here. 14244 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14245 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14246 + " does not match one in settings " + codePath); 14247 continue; 14248 } 14249 // Parse package 14250 int parseFlags = mDefParseFlags; 14251 if (args.isExternalAsec()) { 14252 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14253 } 14254 if (args.isFwdLocked()) { 14255 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14256 } 14257 14258 synchronized (mInstallLock) { 14259 PackageParser.Package pkg = null; 14260 try { 14261 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14262 } catch (PackageManagerException e) { 14263 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14264 } 14265 // Scan the package 14266 if (pkg != null) { 14267 /* 14268 * TODO why is the lock being held? doPostInstall is 14269 * called in other places without the lock. This needs 14270 * to be straightened out. 14271 */ 14272 // writer 14273 synchronized (mPackages) { 14274 retCode = PackageManager.INSTALL_SUCCEEDED; 14275 pkgList.add(pkg.packageName); 14276 // Post process args 14277 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14278 pkg.applicationInfo.uid); 14279 } 14280 } else { 14281 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14282 } 14283 } 14284 14285 } finally { 14286 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14287 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14288 } 14289 } 14290 } 14291 // writer 14292 synchronized (mPackages) { 14293 // If the platform SDK has changed since the last time we booted, 14294 // we need to re-grant app permission to catch any new ones that 14295 // appear. This is really a hack, and means that apps can in some 14296 // cases get permissions that the user didn't initially explicitly 14297 // allow... it would be nice to have some better way to handle 14298 // this situation. 14299 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14300 if (regrantPermissions) 14301 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14302 + mSdkVersion + "; regranting permissions for external storage"); 14303 mSettings.mExternalSdkPlatform = mSdkVersion; 14304 14305 // Make sure group IDs have been assigned, and any permission 14306 // changes in other apps are accounted for 14307 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14308 | (regrantPermissions 14309 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14310 : 0)); 14311 14312 mSettings.updateExternalDatabaseVersion(); 14313 14314 // can downgrade to reader 14315 // Persist settings 14316 mSettings.writeLPr(); 14317 } 14318 // Send a broadcast to let everyone know we are done processing 14319 if (pkgList.size() > 0) { 14320 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14321 } 14322 } 14323 14324 /* 14325 * Utility method to unload a list of specified containers 14326 */ 14327 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14328 // Just unmount all valid containers. 14329 for (AsecInstallArgs arg : cidArgs) { 14330 synchronized (mInstallLock) { 14331 arg.doPostDeleteLI(false); 14332 } 14333 } 14334 } 14335 14336 /* 14337 * Unload packages mounted on external media. This involves deleting package 14338 * data from internal structures, sending broadcasts about diabled packages, 14339 * gc'ing to free up references, unmounting all secure containers 14340 * corresponding to packages on external media, and posting a 14341 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14342 * that we always have to post this message if status has been requested no 14343 * matter what. 14344 */ 14345 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14346 final boolean reportStatus) { 14347 if (DEBUG_SD_INSTALL) 14348 Log.i(TAG, "unloading media packages"); 14349 ArrayList<String> pkgList = new ArrayList<String>(); 14350 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14351 final Set<AsecInstallArgs> keys = processCids.keySet(); 14352 for (AsecInstallArgs args : keys) { 14353 String pkgName = args.getPackageName(); 14354 if (DEBUG_SD_INSTALL) 14355 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14356 // Delete package internally 14357 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14358 synchronized (mInstallLock) { 14359 boolean res = deletePackageLI(pkgName, null, false, null, null, 14360 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14361 if (res) { 14362 pkgList.add(pkgName); 14363 } else { 14364 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14365 failedList.add(args); 14366 } 14367 } 14368 } 14369 14370 // reader 14371 synchronized (mPackages) { 14372 // We didn't update the settings after removing each package; 14373 // write them now for all packages. 14374 mSettings.writeLPr(); 14375 } 14376 14377 // We have to absolutely send UPDATED_MEDIA_STATUS only 14378 // after confirming that all the receivers processed the ordered 14379 // broadcast when packages get disabled, force a gc to clean things up. 14380 // and unload all the containers. 14381 if (pkgList.size() > 0) { 14382 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14383 new IIntentReceiver.Stub() { 14384 public void performReceive(Intent intent, int resultCode, String data, 14385 Bundle extras, boolean ordered, boolean sticky, 14386 int sendingUser) throws RemoteException { 14387 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14388 reportStatus ? 1 : 0, 1, keys); 14389 mHandler.sendMessage(msg); 14390 } 14391 }); 14392 } else { 14393 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14394 keys); 14395 mHandler.sendMessage(msg); 14396 } 14397 } 14398 14399 private void loadPrivatePackages(VolumeInfo vol) { 14400 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14401 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14402 synchronized (mInstallLock) { 14403 synchronized (mPackages) { 14404 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14405 for (PackageSetting ps : packages) { 14406 final PackageParser.Package pkg; 14407 try { 14408 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14409 loaded.add(pkg.applicationInfo); 14410 } catch (PackageManagerException e) { 14411 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14412 } 14413 } 14414 14415 // TODO: regrant any permissions that changed based since original install 14416 14417 mSettings.writeLPr(); 14418 } 14419 } 14420 14421 Slog.d(TAG, "Loaded packages " + loaded); 14422 sendResourcesChangedBroadcast(true, false, loaded, null); 14423 } 14424 14425 private void unloadPrivatePackages(VolumeInfo vol) { 14426 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14427 synchronized (mInstallLock) { 14428 synchronized (mPackages) { 14429 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14430 for (PackageSetting ps : packages) { 14431 if (ps.pkg == null) continue; 14432 14433 final ApplicationInfo info = ps.pkg.applicationInfo; 14434 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14435 if (deletePackageLI(ps.name, null, false, null, null, 14436 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14437 unloaded.add(info); 14438 } else { 14439 Slog.w(TAG, "Failed to unload " + ps.codePath); 14440 } 14441 } 14442 14443 mSettings.writeLPr(); 14444 } 14445 } 14446 14447 Slog.d(TAG, "Unloaded packages " + unloaded); 14448 sendResourcesChangedBroadcast(false, false, unloaded, null); 14449 } 14450 14451 private void unfreezePackage(String packageName) { 14452 synchronized (mPackages) { 14453 final PackageSetting ps = mSettings.mPackages.get(packageName); 14454 if (ps != null) { 14455 ps.frozen = false; 14456 } 14457 } 14458 } 14459 14460 @Override 14461 public int movePackage(final String packageName, final String volumeUuid) { 14462 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14463 14464 final int moveId = mNextMoveId.getAndIncrement(); 14465 try { 14466 movePackageInternal(packageName, volumeUuid, moveId); 14467 } catch (PackageManagerException e) { 14468 Slog.d(TAG, "Failed to move " + packageName, e); 14469 mMoveCallbacks.notifyStatusChanged(moveId, 14470 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14471 } 14472 return moveId; 14473 } 14474 14475 private void movePackageInternal(final String packageName, final String volumeUuid, 14476 final int moveId) throws PackageManagerException { 14477 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14478 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14479 final PackageManager pm = mContext.getPackageManager(); 14480 14481 final boolean currentAsec; 14482 final String currentVolumeUuid; 14483 final File codeFile; 14484 final String installerPackageName; 14485 final String packageAbiOverride; 14486 final int appId; 14487 final String seinfo; 14488 final String label; 14489 14490 // reader 14491 synchronized (mPackages) { 14492 final PackageParser.Package pkg = mPackages.get(packageName); 14493 final PackageSetting ps = mSettings.mPackages.get(packageName); 14494 if (pkg == null || ps == null) { 14495 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14496 } 14497 14498 if (pkg.applicationInfo.isSystemApp()) { 14499 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14500 "Cannot move system application"); 14501 } 14502 14503 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14504 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14505 "Package already moved to " + volumeUuid); 14506 } 14507 14508 final File probe = new File(pkg.codePath); 14509 final File probeOat = new File(probe, "oat"); 14510 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14511 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14512 "Move only supported for modern cluster style installs"); 14513 } 14514 14515 if (ps.frozen) { 14516 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14517 "Failed to move already frozen package"); 14518 } 14519 ps.frozen = true; 14520 14521 currentAsec = pkg.applicationInfo.isForwardLocked() 14522 || pkg.applicationInfo.isExternalAsec(); 14523 currentVolumeUuid = ps.volumeUuid; 14524 codeFile = new File(pkg.codePath); 14525 installerPackageName = ps.installerPackageName; 14526 packageAbiOverride = ps.cpuAbiOverrideString; 14527 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14528 seinfo = pkg.applicationInfo.seinfo; 14529 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14530 } 14531 14532 // Now that we're guarded by frozen state, kill app during move 14533 killApplication(packageName, appId, "move pkg"); 14534 14535 final Bundle extras = new Bundle(); 14536 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14537 extras.putString(Intent.EXTRA_TITLE, label); 14538 mMoveCallbacks.notifyCreated(moveId, extras); 14539 14540 int installFlags; 14541 final boolean moveCompleteApp; 14542 final File measurePath; 14543 14544 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14545 installFlags = INSTALL_INTERNAL; 14546 moveCompleteApp = !currentAsec; 14547 measurePath = Environment.getDataAppDirectory(volumeUuid); 14548 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14549 installFlags = INSTALL_EXTERNAL; 14550 moveCompleteApp = false; 14551 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14552 } else { 14553 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14554 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14555 || !volume.isMountedWritable()) { 14556 unfreezePackage(packageName); 14557 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14558 "Move location not mounted private volume"); 14559 } 14560 14561 Preconditions.checkState(!currentAsec); 14562 14563 installFlags = INSTALL_INTERNAL; 14564 moveCompleteApp = true; 14565 measurePath = Environment.getDataAppDirectory(volumeUuid); 14566 } 14567 14568 final PackageStats stats = new PackageStats(null, -1); 14569 synchronized (mInstaller) { 14570 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14571 unfreezePackage(packageName); 14572 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14573 "Failed to measure package size"); 14574 } 14575 } 14576 14577 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14578 14579 final long startFreeBytes = measurePath.getFreeSpace(); 14580 final long sizeBytes; 14581 if (moveCompleteApp) { 14582 sizeBytes = stats.codeSize + stats.dataSize; 14583 } else { 14584 sizeBytes = stats.codeSize; 14585 } 14586 14587 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14588 unfreezePackage(packageName); 14589 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14590 "Not enough free space to move"); 14591 } 14592 14593 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14594 14595 final CountDownLatch installedLatch = new CountDownLatch(1); 14596 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14597 @Override 14598 public void onUserActionRequired(Intent intent) throws RemoteException { 14599 throw new IllegalStateException(); 14600 } 14601 14602 @Override 14603 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14604 Bundle extras) throws RemoteException { 14605 Slog.d(TAG, "Install result for move: " 14606 + PackageManager.installStatusToString(returnCode, msg)); 14607 14608 installedLatch.countDown(); 14609 14610 // Regardless of success or failure of the move operation, 14611 // always unfreeze the package 14612 unfreezePackage(packageName); 14613 14614 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14615 switch (status) { 14616 case PackageInstaller.STATUS_SUCCESS: 14617 mMoveCallbacks.notifyStatusChanged(moveId, 14618 PackageManager.MOVE_SUCCEEDED); 14619 break; 14620 case PackageInstaller.STATUS_FAILURE_STORAGE: 14621 mMoveCallbacks.notifyStatusChanged(moveId, 14622 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14623 break; 14624 default: 14625 mMoveCallbacks.notifyStatusChanged(moveId, 14626 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14627 break; 14628 } 14629 } 14630 }; 14631 14632 final MoveInfo move; 14633 if (moveCompleteApp) { 14634 // Kick off a thread to report progress estimates 14635 new Thread() { 14636 @Override 14637 public void run() { 14638 while (true) { 14639 try { 14640 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14641 break; 14642 } 14643 } catch (InterruptedException ignored) { 14644 } 14645 14646 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14647 final int progress = 10 + (int) MathUtils.constrain( 14648 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14649 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14650 } 14651 } 14652 }.start(); 14653 14654 final String dataAppName = codeFile.getName(); 14655 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14656 dataAppName, appId, seinfo); 14657 } else { 14658 move = null; 14659 } 14660 14661 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14662 14663 final Message msg = mHandler.obtainMessage(INIT_COPY); 14664 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14665 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14666 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14667 mHandler.sendMessage(msg); 14668 } 14669 14670 @Override 14671 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14672 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14673 14674 final int realMoveId = mNextMoveId.getAndIncrement(); 14675 final Bundle extras = new Bundle(); 14676 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14677 mMoveCallbacks.notifyCreated(realMoveId, extras); 14678 14679 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14680 @Override 14681 public void onCreated(int moveId, Bundle extras) { 14682 // Ignored 14683 } 14684 14685 @Override 14686 public void onStatusChanged(int moveId, int status, long estMillis) { 14687 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14688 } 14689 }; 14690 14691 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14692 storage.setPrimaryStorageUuid(volumeUuid, callback); 14693 return realMoveId; 14694 } 14695 14696 @Override 14697 public int getMoveStatus(int moveId) { 14698 mContext.enforceCallingOrSelfPermission( 14699 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14700 return mMoveCallbacks.mLastStatus.get(moveId); 14701 } 14702 14703 @Override 14704 public void registerMoveCallback(IPackageMoveObserver callback) { 14705 mContext.enforceCallingOrSelfPermission( 14706 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14707 mMoveCallbacks.register(callback); 14708 } 14709 14710 @Override 14711 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14712 mContext.enforceCallingOrSelfPermission( 14713 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14714 mMoveCallbacks.unregister(callback); 14715 } 14716 14717 @Override 14718 public boolean setInstallLocation(int loc) { 14719 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14720 null); 14721 if (getInstallLocation() == loc) { 14722 return true; 14723 } 14724 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14725 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14726 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14727 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14728 return true; 14729 } 14730 return false; 14731 } 14732 14733 @Override 14734 public int getInstallLocation() { 14735 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14736 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14737 PackageHelper.APP_INSTALL_AUTO); 14738 } 14739 14740 /** Called by UserManagerService */ 14741 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14742 mDirtyUsers.remove(userHandle); 14743 mSettings.removeUserLPw(userHandle); 14744 mPendingBroadcasts.remove(userHandle); 14745 if (mInstaller != null) { 14746 // Technically, we shouldn't be doing this with the package lock 14747 // held. However, this is very rare, and there is already so much 14748 // other disk I/O going on, that we'll let it slide for now. 14749 final StorageManager storage = StorageManager.from(mContext); 14750 final List<VolumeInfo> vols = storage.getVolumes(); 14751 for (VolumeInfo vol : vols) { 14752 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14753 final String volumeUuid = vol.getFsUuid(); 14754 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14755 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14756 } 14757 } 14758 } 14759 mUserNeedsBadging.delete(userHandle); 14760 removeUnusedPackagesLILPw(userManager, userHandle); 14761 } 14762 14763 /** 14764 * We're removing userHandle and would like to remove any downloaded packages 14765 * that are no longer in use by any other user. 14766 * @param userHandle the user being removed 14767 */ 14768 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14769 final boolean DEBUG_CLEAN_APKS = false; 14770 int [] users = userManager.getUserIdsLPr(); 14771 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14772 while (psit.hasNext()) { 14773 PackageSetting ps = psit.next(); 14774 if (ps.pkg == null) { 14775 continue; 14776 } 14777 final String packageName = ps.pkg.packageName; 14778 // Skip over if system app 14779 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14780 continue; 14781 } 14782 if (DEBUG_CLEAN_APKS) { 14783 Slog.i(TAG, "Checking package " + packageName); 14784 } 14785 boolean keep = false; 14786 for (int i = 0; i < users.length; i++) { 14787 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14788 keep = true; 14789 if (DEBUG_CLEAN_APKS) { 14790 Slog.i(TAG, " Keeping package " + packageName + " for user " 14791 + users[i]); 14792 } 14793 break; 14794 } 14795 } 14796 if (!keep) { 14797 if (DEBUG_CLEAN_APKS) { 14798 Slog.i(TAG, " Removing package " + packageName); 14799 } 14800 mHandler.post(new Runnable() { 14801 public void run() { 14802 deletePackageX(packageName, userHandle, 0); 14803 } //end run 14804 }); 14805 } 14806 } 14807 } 14808 14809 /** Called by UserManagerService */ 14810 void createNewUserLILPw(int userHandle, File path) { 14811 if (mInstaller != null) { 14812 mInstaller.createUserConfig(userHandle); 14813 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14814 } 14815 } 14816 14817 void newUserCreatedLILPw(int userHandle) { 14818 // Adding a user requires updating runtime permissions for system apps. 14819 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14820 } 14821 14822 @Override 14823 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14824 mContext.enforceCallingOrSelfPermission( 14825 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14826 "Only package verification agents can read the verifier device identity"); 14827 14828 synchronized (mPackages) { 14829 return mSettings.getVerifierDeviceIdentityLPw(); 14830 } 14831 } 14832 14833 @Override 14834 public void setPermissionEnforced(String permission, boolean enforced) { 14835 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14836 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14837 synchronized (mPackages) { 14838 if (mSettings.mReadExternalStorageEnforced == null 14839 || mSettings.mReadExternalStorageEnforced != enforced) { 14840 mSettings.mReadExternalStorageEnforced = enforced; 14841 mSettings.writeLPr(); 14842 } 14843 } 14844 // kill any non-foreground processes so we restart them and 14845 // grant/revoke the GID. 14846 final IActivityManager am = ActivityManagerNative.getDefault(); 14847 if (am != null) { 14848 final long token = Binder.clearCallingIdentity(); 14849 try { 14850 am.killProcessesBelowForeground("setPermissionEnforcement"); 14851 } catch (RemoteException e) { 14852 } finally { 14853 Binder.restoreCallingIdentity(token); 14854 } 14855 } 14856 } else { 14857 throw new IllegalArgumentException("No selective enforcement for " + permission); 14858 } 14859 } 14860 14861 @Override 14862 @Deprecated 14863 public boolean isPermissionEnforced(String permission) { 14864 return true; 14865 } 14866 14867 @Override 14868 public boolean isStorageLow() { 14869 final long token = Binder.clearCallingIdentity(); 14870 try { 14871 final DeviceStorageMonitorInternal 14872 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14873 if (dsm != null) { 14874 return dsm.isMemoryLow(); 14875 } else { 14876 return false; 14877 } 14878 } finally { 14879 Binder.restoreCallingIdentity(token); 14880 } 14881 } 14882 14883 @Override 14884 public IPackageInstaller getPackageInstaller() { 14885 return mInstallerService; 14886 } 14887 14888 private boolean userNeedsBadging(int userId) { 14889 int index = mUserNeedsBadging.indexOfKey(userId); 14890 if (index < 0) { 14891 final UserInfo userInfo; 14892 final long token = Binder.clearCallingIdentity(); 14893 try { 14894 userInfo = sUserManager.getUserInfo(userId); 14895 } finally { 14896 Binder.restoreCallingIdentity(token); 14897 } 14898 final boolean b; 14899 if (userInfo != null && userInfo.isManagedProfile()) { 14900 b = true; 14901 } else { 14902 b = false; 14903 } 14904 mUserNeedsBadging.put(userId, b); 14905 return b; 14906 } 14907 return mUserNeedsBadging.valueAt(index); 14908 } 14909 14910 @Override 14911 public KeySet getKeySetByAlias(String packageName, String alias) { 14912 if (packageName == null || alias == null) { 14913 return null; 14914 } 14915 synchronized(mPackages) { 14916 final PackageParser.Package pkg = mPackages.get(packageName); 14917 if (pkg == null) { 14918 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14919 throw new IllegalArgumentException("Unknown package: " + packageName); 14920 } 14921 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14922 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14923 } 14924 } 14925 14926 @Override 14927 public KeySet getSigningKeySet(String packageName) { 14928 if (packageName == null) { 14929 return null; 14930 } 14931 synchronized(mPackages) { 14932 final PackageParser.Package pkg = mPackages.get(packageName); 14933 if (pkg == null) { 14934 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14935 throw new IllegalArgumentException("Unknown package: " + packageName); 14936 } 14937 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14938 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14939 throw new SecurityException("May not access signing KeySet of other apps."); 14940 } 14941 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14942 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14943 } 14944 } 14945 14946 @Override 14947 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14948 if (packageName == null || ks == null) { 14949 return false; 14950 } 14951 synchronized(mPackages) { 14952 final PackageParser.Package pkg = mPackages.get(packageName); 14953 if (pkg == null) { 14954 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14955 throw new IllegalArgumentException("Unknown package: " + packageName); 14956 } 14957 IBinder ksh = ks.getToken(); 14958 if (ksh instanceof KeySetHandle) { 14959 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14960 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14961 } 14962 return false; 14963 } 14964 } 14965 14966 @Override 14967 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14968 if (packageName == null || ks == null) { 14969 return false; 14970 } 14971 synchronized(mPackages) { 14972 final PackageParser.Package pkg = mPackages.get(packageName); 14973 if (pkg == null) { 14974 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14975 throw new IllegalArgumentException("Unknown package: " + packageName); 14976 } 14977 IBinder ksh = ks.getToken(); 14978 if (ksh instanceof KeySetHandle) { 14979 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14980 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14981 } 14982 return false; 14983 } 14984 } 14985 14986 public void getUsageStatsIfNoPackageUsageInfo() { 14987 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14988 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14989 if (usm == null) { 14990 throw new IllegalStateException("UsageStatsManager must be initialized"); 14991 } 14992 long now = System.currentTimeMillis(); 14993 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14994 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14995 String packageName = entry.getKey(); 14996 PackageParser.Package pkg = mPackages.get(packageName); 14997 if (pkg == null) { 14998 continue; 14999 } 15000 UsageStats usage = entry.getValue(); 15001 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15002 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15003 } 15004 } 15005 } 15006 15007 /** 15008 * Check and throw if the given before/after packages would be considered a 15009 * downgrade. 15010 */ 15011 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15012 throws PackageManagerException { 15013 if (after.versionCode < before.mVersionCode) { 15014 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15015 "Update version code " + after.versionCode + " is older than current " 15016 + before.mVersionCode); 15017 } else if (after.versionCode == before.mVersionCode) { 15018 if (after.baseRevisionCode < before.baseRevisionCode) { 15019 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15020 "Update base revision code " + after.baseRevisionCode 15021 + " is older than current " + before.baseRevisionCode); 15022 } 15023 15024 if (!ArrayUtils.isEmpty(after.splitNames)) { 15025 for (int i = 0; i < after.splitNames.length; i++) { 15026 final String splitName = after.splitNames[i]; 15027 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15028 if (j != -1) { 15029 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15030 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15031 "Update split " + splitName + " revision code " 15032 + after.splitRevisionCodes[i] + " is older than current " 15033 + before.splitRevisionCodes[j]); 15034 } 15035 } 15036 } 15037 } 15038 } 15039 } 15040 15041 private static class MoveCallbacks extends Handler { 15042 private static final int MSG_CREATED = 1; 15043 private static final int MSG_STATUS_CHANGED = 2; 15044 15045 private final RemoteCallbackList<IPackageMoveObserver> 15046 mCallbacks = new RemoteCallbackList<>(); 15047 15048 private final SparseIntArray mLastStatus = new SparseIntArray(); 15049 15050 public MoveCallbacks(Looper looper) { 15051 super(looper); 15052 } 15053 15054 public void register(IPackageMoveObserver callback) { 15055 mCallbacks.register(callback); 15056 } 15057 15058 public void unregister(IPackageMoveObserver callback) { 15059 mCallbacks.unregister(callback); 15060 } 15061 15062 @Override 15063 public void handleMessage(Message msg) { 15064 final SomeArgs args = (SomeArgs) msg.obj; 15065 final int n = mCallbacks.beginBroadcast(); 15066 for (int i = 0; i < n; i++) { 15067 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15068 try { 15069 invokeCallback(callback, msg.what, args); 15070 } catch (RemoteException ignored) { 15071 } 15072 } 15073 mCallbacks.finishBroadcast(); 15074 args.recycle(); 15075 } 15076 15077 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15078 throws RemoteException { 15079 switch (what) { 15080 case MSG_CREATED: { 15081 callback.onCreated(args.argi1, (Bundle) args.arg2); 15082 break; 15083 } 15084 case MSG_STATUS_CHANGED: { 15085 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15086 break; 15087 } 15088 } 15089 } 15090 15091 private void notifyCreated(int moveId, Bundle extras) { 15092 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15093 15094 final SomeArgs args = SomeArgs.obtain(); 15095 args.argi1 = moveId; 15096 args.arg2 = extras; 15097 obtainMessage(MSG_CREATED, args).sendToTarget(); 15098 } 15099 15100 private void notifyStatusChanged(int moveId, int status) { 15101 notifyStatusChanged(moveId, status, -1); 15102 } 15103 15104 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15105 Slog.v(TAG, "Move " + moveId + " status " + status); 15106 15107 final SomeArgs args = SomeArgs.obtain(); 15108 args.argi1 = moveId; 15109 args.argi2 = status; 15110 args.arg3 = estMillis; 15111 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15112 15113 synchronized (mLastStatus) { 15114 mLastStatus.put(moveId, status); 15115 } 15116 } 15117 } 15118} 15119