PackageManagerService.java revision 649efc68cb3cd9648db6801989108c79f99dc1f2
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 undefined ones and 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 result.removeAll(undefinedList); 4166 if (result.size() == 0) { 4167 result.addAll(undefinedList); 4168 if ((flags & MATCH_ALL) != 0) { 4169 result.addAll(matchAllList); 4170 } else { 4171 // Try to add the Default Browser if we can 4172 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4173 UserHandle.myUserId()); 4174 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4175 boolean defaultBrowserFound = false; 4176 final int browserCount = matchAllList.size(); 4177 for (int n=0; n<browserCount; n++) { 4178 ResolveInfo browser = matchAllList.get(n); 4179 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4180 result.add(browser); 4181 defaultBrowserFound = true; 4182 break; 4183 } 4184 } 4185 if (!defaultBrowserFound) { 4186 result.addAll(matchAllList); 4187 } 4188 } else { 4189 result.addAll(matchAllList); 4190 } 4191 } 4192 } 4193 } 4194 if (DEBUG_PREFERRED) { 4195 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4196 result.size()); 4197 } 4198 return result; 4199 } 4200 4201 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4202 int status = ps.getDomainVerificationStatusForUser(userId); 4203 // if none available, get the master status 4204 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4205 if (ps.getIntentFilterVerificationInfo() != null) { 4206 status = ps.getIntentFilterVerificationInfo().getStatus(); 4207 } 4208 } 4209 return status; 4210 } 4211 4212 private ResolveInfo querySkipCurrentProfileIntents( 4213 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4214 int flags, int sourceUserId) { 4215 if (matchingFilters != null) { 4216 int size = matchingFilters.size(); 4217 for (int i = 0; i < size; i ++) { 4218 CrossProfileIntentFilter filter = matchingFilters.get(i); 4219 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4220 // Checking if there are activities in the target user that can handle the 4221 // intent. 4222 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4223 flags, sourceUserId); 4224 if (resolveInfo != null) { 4225 return resolveInfo; 4226 } 4227 } 4228 } 4229 } 4230 return null; 4231 } 4232 4233 // Return matching ResolveInfo if any for skip current profile intent filters. 4234 private ResolveInfo queryCrossProfileIntents( 4235 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4236 int flags, int sourceUserId) { 4237 if (matchingFilters != null) { 4238 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4239 // match the same intent. For performance reasons, it is better not to 4240 // run queryIntent twice for the same userId 4241 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4242 int size = matchingFilters.size(); 4243 for (int i = 0; i < size; i++) { 4244 CrossProfileIntentFilter filter = matchingFilters.get(i); 4245 int targetUserId = filter.getTargetUserId(); 4246 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4247 && !alreadyTriedUserIds.get(targetUserId)) { 4248 // Checking if there are activities in the target user that can handle the 4249 // intent. 4250 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4251 flags, sourceUserId); 4252 if (resolveInfo != null) return resolveInfo; 4253 alreadyTriedUserIds.put(targetUserId, true); 4254 } 4255 } 4256 } 4257 return null; 4258 } 4259 4260 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4261 String resolvedType, int flags, int sourceUserId) { 4262 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4263 resolvedType, flags, filter.getTargetUserId()); 4264 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4265 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4266 } 4267 return null; 4268 } 4269 4270 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4271 int sourceUserId, int targetUserId) { 4272 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4273 String className; 4274 if (targetUserId == UserHandle.USER_OWNER) { 4275 className = FORWARD_INTENT_TO_USER_OWNER; 4276 } else { 4277 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4278 } 4279 ComponentName forwardingActivityComponentName = new ComponentName( 4280 mAndroidApplication.packageName, className); 4281 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4282 sourceUserId); 4283 if (targetUserId == UserHandle.USER_OWNER) { 4284 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4285 forwardingResolveInfo.noResourceId = true; 4286 } 4287 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4288 forwardingResolveInfo.priority = 0; 4289 forwardingResolveInfo.preferredOrder = 0; 4290 forwardingResolveInfo.match = 0; 4291 forwardingResolveInfo.isDefault = true; 4292 forwardingResolveInfo.filter = filter; 4293 forwardingResolveInfo.targetUserId = targetUserId; 4294 return forwardingResolveInfo; 4295 } 4296 4297 @Override 4298 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4299 Intent[] specifics, String[] specificTypes, Intent intent, 4300 String resolvedType, int flags, int userId) { 4301 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4302 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4303 false, "query intent activity options"); 4304 final String resultsAction = intent.getAction(); 4305 4306 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4307 | PackageManager.GET_RESOLVED_FILTER, userId); 4308 4309 if (DEBUG_INTENT_MATCHING) { 4310 Log.v(TAG, "Query " + intent + ": " + results); 4311 } 4312 4313 int specificsPos = 0; 4314 int N; 4315 4316 // todo: note that the algorithm used here is O(N^2). This 4317 // isn't a problem in our current environment, but if we start running 4318 // into situations where we have more than 5 or 10 matches then this 4319 // should probably be changed to something smarter... 4320 4321 // First we go through and resolve each of the specific items 4322 // that were supplied, taking care of removing any corresponding 4323 // duplicate items in the generic resolve list. 4324 if (specifics != null) { 4325 for (int i=0; i<specifics.length; i++) { 4326 final Intent sintent = specifics[i]; 4327 if (sintent == null) { 4328 continue; 4329 } 4330 4331 if (DEBUG_INTENT_MATCHING) { 4332 Log.v(TAG, "Specific #" + i + ": " + sintent); 4333 } 4334 4335 String action = sintent.getAction(); 4336 if (resultsAction != null && resultsAction.equals(action)) { 4337 // If this action was explicitly requested, then don't 4338 // remove things that have it. 4339 action = null; 4340 } 4341 4342 ResolveInfo ri = null; 4343 ActivityInfo ai = null; 4344 4345 ComponentName comp = sintent.getComponent(); 4346 if (comp == null) { 4347 ri = resolveIntent( 4348 sintent, 4349 specificTypes != null ? specificTypes[i] : null, 4350 flags, userId); 4351 if (ri == null) { 4352 continue; 4353 } 4354 if (ri == mResolveInfo) { 4355 // ACK! Must do something better with this. 4356 } 4357 ai = ri.activityInfo; 4358 comp = new ComponentName(ai.applicationInfo.packageName, 4359 ai.name); 4360 } else { 4361 ai = getActivityInfo(comp, flags, userId); 4362 if (ai == null) { 4363 continue; 4364 } 4365 } 4366 4367 // Look for any generic query activities that are duplicates 4368 // of this specific one, and remove them from the results. 4369 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4370 N = results.size(); 4371 int j; 4372 for (j=specificsPos; j<N; j++) { 4373 ResolveInfo sri = results.get(j); 4374 if ((sri.activityInfo.name.equals(comp.getClassName()) 4375 && sri.activityInfo.applicationInfo.packageName.equals( 4376 comp.getPackageName())) 4377 || (action != null && sri.filter.matchAction(action))) { 4378 results.remove(j); 4379 if (DEBUG_INTENT_MATCHING) Log.v( 4380 TAG, "Removing duplicate item from " + j 4381 + " due to specific " + specificsPos); 4382 if (ri == null) { 4383 ri = sri; 4384 } 4385 j--; 4386 N--; 4387 } 4388 } 4389 4390 // Add this specific item to its proper place. 4391 if (ri == null) { 4392 ri = new ResolveInfo(); 4393 ri.activityInfo = ai; 4394 } 4395 results.add(specificsPos, ri); 4396 ri.specificIndex = i; 4397 specificsPos++; 4398 } 4399 } 4400 4401 // Now we go through the remaining generic results and remove any 4402 // duplicate actions that are found here. 4403 N = results.size(); 4404 for (int i=specificsPos; i<N-1; i++) { 4405 final ResolveInfo rii = results.get(i); 4406 if (rii.filter == null) { 4407 continue; 4408 } 4409 4410 // Iterate over all of the actions of this result's intent 4411 // filter... typically this should be just one. 4412 final Iterator<String> it = rii.filter.actionsIterator(); 4413 if (it == null) { 4414 continue; 4415 } 4416 while (it.hasNext()) { 4417 final String action = it.next(); 4418 if (resultsAction != null && resultsAction.equals(action)) { 4419 // If this action was explicitly requested, then don't 4420 // remove things that have it. 4421 continue; 4422 } 4423 for (int j=i+1; j<N; j++) { 4424 final ResolveInfo rij = results.get(j); 4425 if (rij.filter != null && rij.filter.hasAction(action)) { 4426 results.remove(j); 4427 if (DEBUG_INTENT_MATCHING) Log.v( 4428 TAG, "Removing duplicate item from " + j 4429 + " due to action " + action + " at " + i); 4430 j--; 4431 N--; 4432 } 4433 } 4434 } 4435 4436 // If the caller didn't request filter information, drop it now 4437 // so we don't have to marshall/unmarshall it. 4438 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4439 rii.filter = null; 4440 } 4441 } 4442 4443 // Filter out the caller activity if so requested. 4444 if (caller != null) { 4445 N = results.size(); 4446 for (int i=0; i<N; i++) { 4447 ActivityInfo ainfo = results.get(i).activityInfo; 4448 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4449 && caller.getClassName().equals(ainfo.name)) { 4450 results.remove(i); 4451 break; 4452 } 4453 } 4454 } 4455 4456 // If the caller didn't request filter information, 4457 // drop them now so we don't have to 4458 // marshall/unmarshall it. 4459 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4460 N = results.size(); 4461 for (int i=0; i<N; i++) { 4462 results.get(i).filter = null; 4463 } 4464 } 4465 4466 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4467 return results; 4468 } 4469 4470 @Override 4471 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4472 int userId) { 4473 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4474 ComponentName comp = intent.getComponent(); 4475 if (comp == null) { 4476 if (intent.getSelector() != null) { 4477 intent = intent.getSelector(); 4478 comp = intent.getComponent(); 4479 } 4480 } 4481 if (comp != null) { 4482 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4483 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4484 if (ai != null) { 4485 ResolveInfo ri = new ResolveInfo(); 4486 ri.activityInfo = ai; 4487 list.add(ri); 4488 } 4489 return list; 4490 } 4491 4492 // reader 4493 synchronized (mPackages) { 4494 String pkgName = intent.getPackage(); 4495 if (pkgName == null) { 4496 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4497 } 4498 final PackageParser.Package pkg = mPackages.get(pkgName); 4499 if (pkg != null) { 4500 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4501 userId); 4502 } 4503 return null; 4504 } 4505 } 4506 4507 @Override 4508 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4509 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4510 if (!sUserManager.exists(userId)) return null; 4511 if (query != null) { 4512 if (query.size() >= 1) { 4513 // If there is more than one service with the same priority, 4514 // just arbitrarily pick the first one. 4515 return query.get(0); 4516 } 4517 } 4518 return null; 4519 } 4520 4521 @Override 4522 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4523 int userId) { 4524 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4525 ComponentName comp = intent.getComponent(); 4526 if (comp == null) { 4527 if (intent.getSelector() != null) { 4528 intent = intent.getSelector(); 4529 comp = intent.getComponent(); 4530 } 4531 } 4532 if (comp != null) { 4533 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4534 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4535 if (si != null) { 4536 final ResolveInfo ri = new ResolveInfo(); 4537 ri.serviceInfo = si; 4538 list.add(ri); 4539 } 4540 return list; 4541 } 4542 4543 // reader 4544 synchronized (mPackages) { 4545 String pkgName = intent.getPackage(); 4546 if (pkgName == null) { 4547 return mServices.queryIntent(intent, resolvedType, flags, userId); 4548 } 4549 final PackageParser.Package pkg = mPackages.get(pkgName); 4550 if (pkg != null) { 4551 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4552 userId); 4553 } 4554 return null; 4555 } 4556 } 4557 4558 @Override 4559 public List<ResolveInfo> queryIntentContentProviders( 4560 Intent intent, String resolvedType, int flags, int userId) { 4561 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4562 ComponentName comp = intent.getComponent(); 4563 if (comp == null) { 4564 if (intent.getSelector() != null) { 4565 intent = intent.getSelector(); 4566 comp = intent.getComponent(); 4567 } 4568 } 4569 if (comp != null) { 4570 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4571 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4572 if (pi != null) { 4573 final ResolveInfo ri = new ResolveInfo(); 4574 ri.providerInfo = pi; 4575 list.add(ri); 4576 } 4577 return list; 4578 } 4579 4580 // reader 4581 synchronized (mPackages) { 4582 String pkgName = intent.getPackage(); 4583 if (pkgName == null) { 4584 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4585 } 4586 final PackageParser.Package pkg = mPackages.get(pkgName); 4587 if (pkg != null) { 4588 return mProviders.queryIntentForPackage( 4589 intent, resolvedType, flags, pkg.providers, userId); 4590 } 4591 return null; 4592 } 4593 } 4594 4595 @Override 4596 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4597 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4598 4599 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4600 4601 // writer 4602 synchronized (mPackages) { 4603 ArrayList<PackageInfo> list; 4604 if (listUninstalled) { 4605 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4606 for (PackageSetting ps : mSettings.mPackages.values()) { 4607 PackageInfo pi; 4608 if (ps.pkg != null) { 4609 pi = generatePackageInfo(ps.pkg, flags, userId); 4610 } else { 4611 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4612 } 4613 if (pi != null) { 4614 list.add(pi); 4615 } 4616 } 4617 } else { 4618 list = new ArrayList<PackageInfo>(mPackages.size()); 4619 for (PackageParser.Package p : mPackages.values()) { 4620 PackageInfo pi = generatePackageInfo(p, flags, userId); 4621 if (pi != null) { 4622 list.add(pi); 4623 } 4624 } 4625 } 4626 4627 return new ParceledListSlice<PackageInfo>(list); 4628 } 4629 } 4630 4631 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4632 String[] permissions, boolean[] tmp, int flags, int userId) { 4633 int numMatch = 0; 4634 final PermissionsState permissionsState = ps.getPermissionsState(); 4635 for (int i=0; i<permissions.length; i++) { 4636 final String permission = permissions[i]; 4637 if (permissionsState.hasPermission(permission, userId)) { 4638 tmp[i] = true; 4639 numMatch++; 4640 } else { 4641 tmp[i] = false; 4642 } 4643 } 4644 if (numMatch == 0) { 4645 return; 4646 } 4647 PackageInfo pi; 4648 if (ps.pkg != null) { 4649 pi = generatePackageInfo(ps.pkg, flags, userId); 4650 } else { 4651 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4652 } 4653 // The above might return null in cases of uninstalled apps or install-state 4654 // skew across users/profiles. 4655 if (pi != null) { 4656 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4657 if (numMatch == permissions.length) { 4658 pi.requestedPermissions = permissions; 4659 } else { 4660 pi.requestedPermissions = new String[numMatch]; 4661 numMatch = 0; 4662 for (int i=0; i<permissions.length; i++) { 4663 if (tmp[i]) { 4664 pi.requestedPermissions[numMatch] = permissions[i]; 4665 numMatch++; 4666 } 4667 } 4668 } 4669 } 4670 list.add(pi); 4671 } 4672 } 4673 4674 @Override 4675 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4676 String[] permissions, int flags, int userId) { 4677 if (!sUserManager.exists(userId)) return null; 4678 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4679 4680 // writer 4681 synchronized (mPackages) { 4682 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4683 boolean[] tmpBools = new boolean[permissions.length]; 4684 if (listUninstalled) { 4685 for (PackageSetting ps : mSettings.mPackages.values()) { 4686 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4687 } 4688 } else { 4689 for (PackageParser.Package pkg : mPackages.values()) { 4690 PackageSetting ps = (PackageSetting)pkg.mExtras; 4691 if (ps != null) { 4692 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4693 userId); 4694 } 4695 } 4696 } 4697 4698 return new ParceledListSlice<PackageInfo>(list); 4699 } 4700 } 4701 4702 @Override 4703 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4704 if (!sUserManager.exists(userId)) return null; 4705 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4706 4707 // writer 4708 synchronized (mPackages) { 4709 ArrayList<ApplicationInfo> list; 4710 if (listUninstalled) { 4711 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4712 for (PackageSetting ps : mSettings.mPackages.values()) { 4713 ApplicationInfo ai; 4714 if (ps.pkg != null) { 4715 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4716 ps.readUserState(userId), userId); 4717 } else { 4718 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4719 } 4720 if (ai != null) { 4721 list.add(ai); 4722 } 4723 } 4724 } else { 4725 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4726 for (PackageParser.Package p : mPackages.values()) { 4727 if (p.mExtras != null) { 4728 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4729 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4730 if (ai != null) { 4731 list.add(ai); 4732 } 4733 } 4734 } 4735 } 4736 4737 return new ParceledListSlice<ApplicationInfo>(list); 4738 } 4739 } 4740 4741 public List<ApplicationInfo> getPersistentApplications(int flags) { 4742 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4743 4744 // reader 4745 synchronized (mPackages) { 4746 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4747 final int userId = UserHandle.getCallingUserId(); 4748 while (i.hasNext()) { 4749 final PackageParser.Package p = i.next(); 4750 if (p.applicationInfo != null 4751 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4752 && (!mSafeMode || isSystemApp(p))) { 4753 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4754 if (ps != null) { 4755 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4756 ps.readUserState(userId), userId); 4757 if (ai != null) { 4758 finalList.add(ai); 4759 } 4760 } 4761 } 4762 } 4763 } 4764 4765 return finalList; 4766 } 4767 4768 @Override 4769 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4770 if (!sUserManager.exists(userId)) return null; 4771 // reader 4772 synchronized (mPackages) { 4773 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4774 PackageSetting ps = provider != null 4775 ? mSettings.mPackages.get(provider.owner.packageName) 4776 : null; 4777 return ps != null 4778 && mSettings.isEnabledLPr(provider.info, flags, userId) 4779 && (!mSafeMode || (provider.info.applicationInfo.flags 4780 &ApplicationInfo.FLAG_SYSTEM) != 0) 4781 ? PackageParser.generateProviderInfo(provider, flags, 4782 ps.readUserState(userId), userId) 4783 : null; 4784 } 4785 } 4786 4787 /** 4788 * @deprecated 4789 */ 4790 @Deprecated 4791 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4792 // reader 4793 synchronized (mPackages) { 4794 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4795 .entrySet().iterator(); 4796 final int userId = UserHandle.getCallingUserId(); 4797 while (i.hasNext()) { 4798 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4799 PackageParser.Provider p = entry.getValue(); 4800 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4801 4802 if (ps != null && p.syncable 4803 && (!mSafeMode || (p.info.applicationInfo.flags 4804 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4805 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4806 ps.readUserState(userId), userId); 4807 if (info != null) { 4808 outNames.add(entry.getKey()); 4809 outInfo.add(info); 4810 } 4811 } 4812 } 4813 } 4814 } 4815 4816 @Override 4817 public List<ProviderInfo> queryContentProviders(String processName, 4818 int uid, int flags) { 4819 ArrayList<ProviderInfo> finalList = null; 4820 // reader 4821 synchronized (mPackages) { 4822 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4823 final int userId = processName != null ? 4824 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4825 while (i.hasNext()) { 4826 final PackageParser.Provider p = i.next(); 4827 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4828 if (ps != null && p.info.authority != null 4829 && (processName == null 4830 || (p.info.processName.equals(processName) 4831 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4832 && mSettings.isEnabledLPr(p.info, flags, userId) 4833 && (!mSafeMode 4834 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4835 if (finalList == null) { 4836 finalList = new ArrayList<ProviderInfo>(3); 4837 } 4838 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4839 ps.readUserState(userId), userId); 4840 if (info != null) { 4841 finalList.add(info); 4842 } 4843 } 4844 } 4845 } 4846 4847 if (finalList != null) { 4848 Collections.sort(finalList, mProviderInitOrderSorter); 4849 } 4850 4851 return finalList; 4852 } 4853 4854 @Override 4855 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4856 int flags) { 4857 // reader 4858 synchronized (mPackages) { 4859 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4860 return PackageParser.generateInstrumentationInfo(i, flags); 4861 } 4862 } 4863 4864 @Override 4865 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4866 int flags) { 4867 ArrayList<InstrumentationInfo> finalList = 4868 new ArrayList<InstrumentationInfo>(); 4869 4870 // reader 4871 synchronized (mPackages) { 4872 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4873 while (i.hasNext()) { 4874 final PackageParser.Instrumentation p = i.next(); 4875 if (targetPackage == null 4876 || targetPackage.equals(p.info.targetPackage)) { 4877 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4878 flags); 4879 if (ii != null) { 4880 finalList.add(ii); 4881 } 4882 } 4883 } 4884 } 4885 4886 return finalList; 4887 } 4888 4889 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4890 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4891 if (overlays == null) { 4892 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4893 return; 4894 } 4895 for (PackageParser.Package opkg : overlays.values()) { 4896 // Not much to do if idmap fails: we already logged the error 4897 // and we certainly don't want to abort installation of pkg simply 4898 // because an overlay didn't fit properly. For these reasons, 4899 // ignore the return value of createIdmapForPackagePairLI. 4900 createIdmapForPackagePairLI(pkg, opkg); 4901 } 4902 } 4903 4904 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4905 PackageParser.Package opkg) { 4906 if (!opkg.mTrustedOverlay) { 4907 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4908 opkg.baseCodePath + ": overlay not trusted"); 4909 return false; 4910 } 4911 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4912 if (overlaySet == null) { 4913 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4914 opkg.baseCodePath + " but target package has no known overlays"); 4915 return false; 4916 } 4917 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4918 // TODO: generate idmap for split APKs 4919 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4920 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4921 + opkg.baseCodePath); 4922 return false; 4923 } 4924 PackageParser.Package[] overlayArray = 4925 overlaySet.values().toArray(new PackageParser.Package[0]); 4926 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4927 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4928 return p1.mOverlayPriority - p2.mOverlayPriority; 4929 } 4930 }; 4931 Arrays.sort(overlayArray, cmp); 4932 4933 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4934 int i = 0; 4935 for (PackageParser.Package p : overlayArray) { 4936 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4937 } 4938 return true; 4939 } 4940 4941 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4942 final File[] files = dir.listFiles(); 4943 if (ArrayUtils.isEmpty(files)) { 4944 Log.d(TAG, "No files in app dir " + dir); 4945 return; 4946 } 4947 4948 if (DEBUG_PACKAGE_SCANNING) { 4949 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4950 + " flags=0x" + Integer.toHexString(parseFlags)); 4951 } 4952 4953 for (File file : files) { 4954 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4955 && !PackageInstallerService.isStageName(file.getName()); 4956 if (!isPackage) { 4957 // Ignore entries which are not packages 4958 continue; 4959 } 4960 try { 4961 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4962 scanFlags, currentTime, null); 4963 } catch (PackageManagerException e) { 4964 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4965 4966 // Delete invalid userdata apps 4967 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4968 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4969 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4970 if (file.isDirectory()) { 4971 mInstaller.rmPackageDir(file.getAbsolutePath()); 4972 } else { 4973 file.delete(); 4974 } 4975 } 4976 } 4977 } 4978 } 4979 4980 private static File getSettingsProblemFile() { 4981 File dataDir = Environment.getDataDirectory(); 4982 File systemDir = new File(dataDir, "system"); 4983 File fname = new File(systemDir, "uiderrors.txt"); 4984 return fname; 4985 } 4986 4987 static void reportSettingsProblem(int priority, String msg) { 4988 logCriticalInfo(priority, msg); 4989 } 4990 4991 static void logCriticalInfo(int priority, String msg) { 4992 Slog.println(priority, TAG, msg); 4993 EventLogTags.writePmCriticalInfo(msg); 4994 try { 4995 File fname = getSettingsProblemFile(); 4996 FileOutputStream out = new FileOutputStream(fname, true); 4997 PrintWriter pw = new FastPrintWriter(out); 4998 SimpleDateFormat formatter = new SimpleDateFormat(); 4999 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5000 pw.println(dateString + ": " + msg); 5001 pw.close(); 5002 FileUtils.setPermissions( 5003 fname.toString(), 5004 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5005 -1, -1); 5006 } catch (java.io.IOException e) { 5007 } 5008 } 5009 5010 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5011 PackageParser.Package pkg, File srcFile, int parseFlags) 5012 throws PackageManagerException { 5013 if (ps != null 5014 && ps.codePath.equals(srcFile) 5015 && ps.timeStamp == srcFile.lastModified() 5016 && !isCompatSignatureUpdateNeeded(pkg) 5017 && !isRecoverSignatureUpdateNeeded(pkg)) { 5018 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5019 if (ps.signatures.mSignatures != null 5020 && ps.signatures.mSignatures.length != 0 5021 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5022 // Optimization: reuse the existing cached certificates 5023 // if the package appears to be unchanged. 5024 pkg.mSignatures = ps.signatures.mSignatures; 5025 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5026 synchronized (mPackages) { 5027 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5028 } 5029 return; 5030 } 5031 5032 Slog.w(TAG, "PackageSetting for " + ps.name 5033 + " is missing signatures. Collecting certs again to recover them."); 5034 } else { 5035 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5036 } 5037 5038 try { 5039 pp.collectCertificates(pkg, parseFlags); 5040 pp.collectManifestDigest(pkg); 5041 } catch (PackageParserException e) { 5042 throw PackageManagerException.from(e); 5043 } 5044 } 5045 5046 /* 5047 * Scan a package and return the newly parsed package. 5048 * Returns null in case of errors and the error code is stored in mLastScanError 5049 */ 5050 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5051 long currentTime, UserHandle user) throws PackageManagerException { 5052 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5053 parseFlags |= mDefParseFlags; 5054 PackageParser pp = new PackageParser(); 5055 pp.setSeparateProcesses(mSeparateProcesses); 5056 pp.setOnlyCoreApps(mOnlyCore); 5057 pp.setDisplayMetrics(mMetrics); 5058 5059 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5060 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5061 } 5062 5063 final PackageParser.Package pkg; 5064 try { 5065 pkg = pp.parsePackage(scanFile, parseFlags); 5066 } catch (PackageParserException e) { 5067 throw PackageManagerException.from(e); 5068 } 5069 5070 PackageSetting ps = null; 5071 PackageSetting updatedPkg; 5072 // reader 5073 synchronized (mPackages) { 5074 // Look to see if we already know about this package. 5075 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5076 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5077 // This package has been renamed to its original name. Let's 5078 // use that. 5079 ps = mSettings.peekPackageLPr(oldName); 5080 } 5081 // If there was no original package, see one for the real package name. 5082 if (ps == null) { 5083 ps = mSettings.peekPackageLPr(pkg.packageName); 5084 } 5085 // Check to see if this package could be hiding/updating a system 5086 // package. Must look for it either under the original or real 5087 // package name depending on our state. 5088 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5089 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5090 } 5091 boolean updatedPkgBetter = false; 5092 // First check if this is a system package that may involve an update 5093 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5094 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5095 // it needs to drop FLAG_PRIVILEGED. 5096 if (locationIsPrivileged(scanFile)) { 5097 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5098 } else { 5099 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5100 } 5101 5102 if (ps != null && !ps.codePath.equals(scanFile)) { 5103 // The path has changed from what was last scanned... check the 5104 // version of the new path against what we have stored to determine 5105 // what to do. 5106 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5107 if (pkg.mVersionCode <= ps.versionCode) { 5108 // The system package has been updated and the code path does not match 5109 // Ignore entry. Skip it. 5110 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5111 + " ignored: updated version " + ps.versionCode 5112 + " better than this " + pkg.mVersionCode); 5113 if (!updatedPkg.codePath.equals(scanFile)) { 5114 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5115 + ps.name + " changing from " + updatedPkg.codePathString 5116 + " to " + scanFile); 5117 updatedPkg.codePath = scanFile; 5118 updatedPkg.codePathString = scanFile.toString(); 5119 updatedPkg.resourcePath = scanFile; 5120 updatedPkg.resourcePathString = scanFile.toString(); 5121 } 5122 updatedPkg.pkg = pkg; 5123 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5124 } else { 5125 // The current app on the system partition is better than 5126 // what we have updated to on the data partition; switch 5127 // back to the system partition version. 5128 // At this point, its safely assumed that package installation for 5129 // apps in system partition will go through. If not there won't be a working 5130 // version of the app 5131 // writer 5132 synchronized (mPackages) { 5133 // Just remove the loaded entries from package lists. 5134 mPackages.remove(ps.name); 5135 } 5136 5137 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5138 + " reverting from " + ps.codePathString 5139 + ": new version " + pkg.mVersionCode 5140 + " better than installed " + ps.versionCode); 5141 5142 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5143 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5144 synchronized (mInstallLock) { 5145 args.cleanUpResourcesLI(); 5146 } 5147 synchronized (mPackages) { 5148 mSettings.enableSystemPackageLPw(ps.name); 5149 } 5150 updatedPkgBetter = true; 5151 } 5152 } 5153 } 5154 5155 if (updatedPkg != null) { 5156 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5157 // initially 5158 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5159 5160 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5161 // flag set initially 5162 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5163 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5164 } 5165 } 5166 5167 // Verify certificates against what was last scanned 5168 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5169 5170 /* 5171 * A new system app appeared, but we already had a non-system one of the 5172 * same name installed earlier. 5173 */ 5174 boolean shouldHideSystemApp = false; 5175 if (updatedPkg == null && ps != null 5176 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5177 /* 5178 * Check to make sure the signatures match first. If they don't, 5179 * wipe the installed application and its data. 5180 */ 5181 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5182 != PackageManager.SIGNATURE_MATCH) { 5183 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5184 + " signatures don't match existing userdata copy; removing"); 5185 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5186 ps = null; 5187 } else { 5188 /* 5189 * If the newly-added system app is an older version than the 5190 * already installed version, hide it. It will be scanned later 5191 * and re-added like an update. 5192 */ 5193 if (pkg.mVersionCode <= ps.versionCode) { 5194 shouldHideSystemApp = true; 5195 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5196 + " but new version " + pkg.mVersionCode + " better than installed " 5197 + ps.versionCode + "; hiding system"); 5198 } else { 5199 /* 5200 * The newly found system app is a newer version that the 5201 * one previously installed. Simply remove the 5202 * already-installed application and replace it with our own 5203 * while keeping the application data. 5204 */ 5205 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5206 + " reverting from " + ps.codePathString + ": new version " 5207 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5208 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5209 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5210 synchronized (mInstallLock) { 5211 args.cleanUpResourcesLI(); 5212 } 5213 } 5214 } 5215 } 5216 5217 // The apk is forward locked (not public) if its code and resources 5218 // are kept in different files. (except for app in either system or 5219 // vendor path). 5220 // TODO grab this value from PackageSettings 5221 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5222 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5223 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5224 } 5225 } 5226 5227 // TODO: extend to support forward-locked splits 5228 String resourcePath = null; 5229 String baseResourcePath = null; 5230 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5231 if (ps != null && ps.resourcePathString != null) { 5232 resourcePath = ps.resourcePathString; 5233 baseResourcePath = ps.resourcePathString; 5234 } else { 5235 // Should not happen at all. Just log an error. 5236 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5237 } 5238 } else { 5239 resourcePath = pkg.codePath; 5240 baseResourcePath = pkg.baseCodePath; 5241 } 5242 5243 // Set application objects path explicitly. 5244 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5245 pkg.applicationInfo.setCodePath(pkg.codePath); 5246 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5247 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5248 pkg.applicationInfo.setResourcePath(resourcePath); 5249 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5250 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5251 5252 // Note that we invoke the following method only if we are about to unpack an application 5253 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5254 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5255 5256 /* 5257 * If the system app should be overridden by a previously installed 5258 * data, hide the system app now and let the /data/app scan pick it up 5259 * again. 5260 */ 5261 if (shouldHideSystemApp) { 5262 synchronized (mPackages) { 5263 /* 5264 * We have to grant systems permissions before we hide, because 5265 * grantPermissions will assume the package update is trying to 5266 * expand its permissions. 5267 */ 5268 grantPermissionsLPw(pkg, true, pkg.packageName); 5269 mSettings.disableSystemPackageLPw(pkg.packageName); 5270 } 5271 } 5272 5273 return scannedPkg; 5274 } 5275 5276 private static String fixProcessName(String defProcessName, 5277 String processName, int uid) { 5278 if (processName == null) { 5279 return defProcessName; 5280 } 5281 return processName; 5282 } 5283 5284 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5285 throws PackageManagerException { 5286 if (pkgSetting.signatures.mSignatures != null) { 5287 // Already existing package. Make sure signatures match 5288 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5289 == PackageManager.SIGNATURE_MATCH; 5290 if (!match) { 5291 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5292 == PackageManager.SIGNATURE_MATCH; 5293 } 5294 if (!match) { 5295 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5296 == PackageManager.SIGNATURE_MATCH; 5297 } 5298 if (!match) { 5299 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5300 + pkg.packageName + " signatures do not match the " 5301 + "previously installed version; ignoring!"); 5302 } 5303 } 5304 5305 // Check for shared user signatures 5306 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5307 // Already existing package. Make sure signatures match 5308 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5309 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5310 if (!match) { 5311 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5312 == PackageManager.SIGNATURE_MATCH; 5313 } 5314 if (!match) { 5315 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5316 == PackageManager.SIGNATURE_MATCH; 5317 } 5318 if (!match) { 5319 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5320 "Package " + pkg.packageName 5321 + " has no signatures that match those in shared user " 5322 + pkgSetting.sharedUser.name + "; ignoring!"); 5323 } 5324 } 5325 } 5326 5327 /** 5328 * Enforces that only the system UID or root's UID can call a method exposed 5329 * via Binder. 5330 * 5331 * @param message used as message if SecurityException is thrown 5332 * @throws SecurityException if the caller is not system or root 5333 */ 5334 private static final void enforceSystemOrRoot(String message) { 5335 final int uid = Binder.getCallingUid(); 5336 if (uid != Process.SYSTEM_UID && uid != 0) { 5337 throw new SecurityException(message); 5338 } 5339 } 5340 5341 @Override 5342 public void performBootDexOpt() { 5343 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5344 5345 // Before everything else, see whether we need to fstrim. 5346 try { 5347 IMountService ms = PackageHelper.getMountService(); 5348 if (ms != null) { 5349 final boolean isUpgrade = isUpgrade(); 5350 boolean doTrim = isUpgrade; 5351 if (doTrim) { 5352 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5353 } else { 5354 final long interval = android.provider.Settings.Global.getLong( 5355 mContext.getContentResolver(), 5356 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5357 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5358 if (interval > 0) { 5359 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5360 if (timeSinceLast > interval) { 5361 doTrim = true; 5362 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5363 + "; running immediately"); 5364 } 5365 } 5366 } 5367 if (doTrim) { 5368 if (!isFirstBoot()) { 5369 try { 5370 ActivityManagerNative.getDefault().showBootMessage( 5371 mContext.getResources().getString( 5372 R.string.android_upgrading_fstrim), true); 5373 } catch (RemoteException e) { 5374 } 5375 } 5376 ms.runMaintenance(); 5377 } 5378 } else { 5379 Slog.e(TAG, "Mount service unavailable!"); 5380 } 5381 } catch (RemoteException e) { 5382 // Can't happen; MountService is local 5383 } 5384 5385 final ArraySet<PackageParser.Package> pkgs; 5386 synchronized (mPackages) { 5387 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5388 } 5389 5390 if (pkgs != null) { 5391 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5392 // in case the device runs out of space. 5393 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5394 // Give priority to core apps. 5395 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5396 PackageParser.Package pkg = it.next(); 5397 if (pkg.coreApp) { 5398 if (DEBUG_DEXOPT) { 5399 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5400 } 5401 sortedPkgs.add(pkg); 5402 it.remove(); 5403 } 5404 } 5405 // Give priority to system apps that listen for pre boot complete. 5406 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5407 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5408 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5409 PackageParser.Package pkg = it.next(); 5410 if (pkgNames.contains(pkg.packageName)) { 5411 if (DEBUG_DEXOPT) { 5412 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5413 } 5414 sortedPkgs.add(pkg); 5415 it.remove(); 5416 } 5417 } 5418 // Give priority to system apps. 5419 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5420 PackageParser.Package pkg = it.next(); 5421 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5422 if (DEBUG_DEXOPT) { 5423 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5424 } 5425 sortedPkgs.add(pkg); 5426 it.remove(); 5427 } 5428 } 5429 // Give priority to updated system apps. 5430 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5431 PackageParser.Package pkg = it.next(); 5432 if (pkg.isUpdatedSystemApp()) { 5433 if (DEBUG_DEXOPT) { 5434 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5435 } 5436 sortedPkgs.add(pkg); 5437 it.remove(); 5438 } 5439 } 5440 // Give priority to apps that listen for boot complete. 5441 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5442 pkgNames = getPackageNamesForIntent(intent); 5443 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5444 PackageParser.Package pkg = it.next(); 5445 if (pkgNames.contains(pkg.packageName)) { 5446 if (DEBUG_DEXOPT) { 5447 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5448 } 5449 sortedPkgs.add(pkg); 5450 it.remove(); 5451 } 5452 } 5453 // Filter out packages that aren't recently used. 5454 filterRecentlyUsedApps(pkgs); 5455 // Add all remaining apps. 5456 for (PackageParser.Package pkg : pkgs) { 5457 if (DEBUG_DEXOPT) { 5458 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5459 } 5460 sortedPkgs.add(pkg); 5461 } 5462 5463 // If we want to be lazy, filter everything that wasn't recently used. 5464 if (mLazyDexOpt) { 5465 filterRecentlyUsedApps(sortedPkgs); 5466 } 5467 5468 int i = 0; 5469 int total = sortedPkgs.size(); 5470 File dataDir = Environment.getDataDirectory(); 5471 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5472 if (lowThreshold == 0) { 5473 throw new IllegalStateException("Invalid low memory threshold"); 5474 } 5475 for (PackageParser.Package pkg : sortedPkgs) { 5476 long usableSpace = dataDir.getUsableSpace(); 5477 if (usableSpace < lowThreshold) { 5478 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5479 break; 5480 } 5481 performBootDexOpt(pkg, ++i, total); 5482 } 5483 } 5484 } 5485 5486 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5487 // Filter out packages that aren't recently used. 5488 // 5489 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5490 // should do a full dexopt. 5491 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5492 int total = pkgs.size(); 5493 int skipped = 0; 5494 long now = System.currentTimeMillis(); 5495 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5496 PackageParser.Package pkg = i.next(); 5497 long then = pkg.mLastPackageUsageTimeInMills; 5498 if (then + mDexOptLRUThresholdInMills < now) { 5499 if (DEBUG_DEXOPT) { 5500 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5501 ((then == 0) ? "never" : new Date(then))); 5502 } 5503 i.remove(); 5504 skipped++; 5505 } 5506 } 5507 if (DEBUG_DEXOPT) { 5508 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5509 } 5510 } 5511 } 5512 5513 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5514 List<ResolveInfo> ris = null; 5515 try { 5516 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5517 intent, null, 0, UserHandle.USER_OWNER); 5518 } catch (RemoteException e) { 5519 } 5520 ArraySet<String> pkgNames = new ArraySet<String>(); 5521 if (ris != null) { 5522 for (ResolveInfo ri : ris) { 5523 pkgNames.add(ri.activityInfo.packageName); 5524 } 5525 } 5526 return pkgNames; 5527 } 5528 5529 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5530 if (DEBUG_DEXOPT) { 5531 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5532 } 5533 if (!isFirstBoot()) { 5534 try { 5535 ActivityManagerNative.getDefault().showBootMessage( 5536 mContext.getResources().getString(R.string.android_upgrading_apk, 5537 curr, total), true); 5538 } catch (RemoteException e) { 5539 } 5540 } 5541 PackageParser.Package p = pkg; 5542 synchronized (mInstallLock) { 5543 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5544 false /* force dex */, false /* defer */, true /* include dependencies */); 5545 } 5546 } 5547 5548 @Override 5549 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5550 return performDexOpt(packageName, instructionSet, false); 5551 } 5552 5553 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5554 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5555 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5556 if (!dexopt && !updateUsage) { 5557 // We aren't going to dexopt or update usage, so bail early. 5558 return false; 5559 } 5560 PackageParser.Package p; 5561 final String targetInstructionSet; 5562 synchronized (mPackages) { 5563 p = mPackages.get(packageName); 5564 if (p == null) { 5565 return false; 5566 } 5567 if (updateUsage) { 5568 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5569 } 5570 mPackageUsage.write(false); 5571 if (!dexopt) { 5572 // We aren't going to dexopt, so bail early. 5573 return false; 5574 } 5575 5576 targetInstructionSet = instructionSet != null ? instructionSet : 5577 getPrimaryInstructionSet(p.applicationInfo); 5578 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5579 return false; 5580 } 5581 } 5582 5583 synchronized (mInstallLock) { 5584 final String[] instructionSets = new String[] { targetInstructionSet }; 5585 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5586 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5587 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5588 } 5589 } 5590 5591 public ArraySet<String> getPackagesThatNeedDexOpt() { 5592 ArraySet<String> pkgs = null; 5593 synchronized (mPackages) { 5594 for (PackageParser.Package p : mPackages.values()) { 5595 if (DEBUG_DEXOPT) { 5596 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5597 } 5598 if (!p.mDexOptPerformed.isEmpty()) { 5599 continue; 5600 } 5601 if (pkgs == null) { 5602 pkgs = new ArraySet<String>(); 5603 } 5604 pkgs.add(p.packageName); 5605 } 5606 } 5607 return pkgs; 5608 } 5609 5610 public void shutdown() { 5611 mPackageUsage.write(true); 5612 } 5613 5614 @Override 5615 public void forceDexOpt(String packageName) { 5616 enforceSystemOrRoot("forceDexOpt"); 5617 5618 PackageParser.Package pkg; 5619 synchronized (mPackages) { 5620 pkg = mPackages.get(packageName); 5621 if (pkg == null) { 5622 throw new IllegalArgumentException("Missing package: " + packageName); 5623 } 5624 } 5625 5626 synchronized (mInstallLock) { 5627 final String[] instructionSets = new String[] { 5628 getPrimaryInstructionSet(pkg.applicationInfo) }; 5629 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5630 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5631 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5632 throw new IllegalStateException("Failed to dexopt: " + res); 5633 } 5634 } 5635 } 5636 5637 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5638 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5639 Slog.w(TAG, "Unable to update from " + oldPkg.name 5640 + " to " + newPkg.packageName 5641 + ": old package not in system partition"); 5642 return false; 5643 } else if (mPackages.get(oldPkg.name) != null) { 5644 Slog.w(TAG, "Unable to update from " + oldPkg.name 5645 + " to " + newPkg.packageName 5646 + ": old package still exists"); 5647 return false; 5648 } 5649 return true; 5650 } 5651 5652 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5653 int[] users = sUserManager.getUserIds(); 5654 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5655 if (res < 0) { 5656 return res; 5657 } 5658 for (int user : users) { 5659 if (user != 0) { 5660 res = mInstaller.createUserData(volumeUuid, packageName, 5661 UserHandle.getUid(user, uid), user, seinfo); 5662 if (res < 0) { 5663 return res; 5664 } 5665 } 5666 } 5667 return res; 5668 } 5669 5670 private int removeDataDirsLI(String volumeUuid, String packageName) { 5671 int[] users = sUserManager.getUserIds(); 5672 int res = 0; 5673 for (int user : users) { 5674 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5675 if (resInner < 0) { 5676 res = resInner; 5677 } 5678 } 5679 5680 return res; 5681 } 5682 5683 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5684 int[] users = sUserManager.getUserIds(); 5685 int res = 0; 5686 for (int user : users) { 5687 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5688 if (resInner < 0) { 5689 res = resInner; 5690 } 5691 } 5692 return res; 5693 } 5694 5695 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5696 PackageParser.Package changingLib) { 5697 if (file.path != null) { 5698 usesLibraryFiles.add(file.path); 5699 return; 5700 } 5701 PackageParser.Package p = mPackages.get(file.apk); 5702 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5703 // If we are doing this while in the middle of updating a library apk, 5704 // then we need to make sure to use that new apk for determining the 5705 // dependencies here. (We haven't yet finished committing the new apk 5706 // to the package manager state.) 5707 if (p == null || p.packageName.equals(changingLib.packageName)) { 5708 p = changingLib; 5709 } 5710 } 5711 if (p != null) { 5712 usesLibraryFiles.addAll(p.getAllCodePaths()); 5713 } 5714 } 5715 5716 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5717 PackageParser.Package changingLib) throws PackageManagerException { 5718 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5719 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5720 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5721 for (int i=0; i<N; i++) { 5722 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5723 if (file == null) { 5724 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5725 "Package " + pkg.packageName + " requires unavailable shared library " 5726 + pkg.usesLibraries.get(i) + "; failing!"); 5727 } 5728 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5729 } 5730 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5731 for (int i=0; i<N; i++) { 5732 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5733 if (file == null) { 5734 Slog.w(TAG, "Package " + pkg.packageName 5735 + " desires unavailable shared library " 5736 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5737 } else { 5738 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5739 } 5740 } 5741 N = usesLibraryFiles.size(); 5742 if (N > 0) { 5743 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5744 } else { 5745 pkg.usesLibraryFiles = null; 5746 } 5747 } 5748 } 5749 5750 private static boolean hasString(List<String> list, List<String> which) { 5751 if (list == null) { 5752 return false; 5753 } 5754 for (int i=list.size()-1; i>=0; i--) { 5755 for (int j=which.size()-1; j>=0; j--) { 5756 if (which.get(j).equals(list.get(i))) { 5757 return true; 5758 } 5759 } 5760 } 5761 return false; 5762 } 5763 5764 private void updateAllSharedLibrariesLPw() { 5765 for (PackageParser.Package pkg : mPackages.values()) { 5766 try { 5767 updateSharedLibrariesLPw(pkg, null); 5768 } catch (PackageManagerException e) { 5769 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5770 } 5771 } 5772 } 5773 5774 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5775 PackageParser.Package changingPkg) { 5776 ArrayList<PackageParser.Package> res = null; 5777 for (PackageParser.Package pkg : mPackages.values()) { 5778 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5779 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5780 if (res == null) { 5781 res = new ArrayList<PackageParser.Package>(); 5782 } 5783 res.add(pkg); 5784 try { 5785 updateSharedLibrariesLPw(pkg, changingPkg); 5786 } catch (PackageManagerException e) { 5787 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5788 } 5789 } 5790 } 5791 return res; 5792 } 5793 5794 /** 5795 * Derive the value of the {@code cpuAbiOverride} based on the provided 5796 * value and an optional stored value from the package settings. 5797 */ 5798 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5799 String cpuAbiOverride = null; 5800 5801 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5802 cpuAbiOverride = null; 5803 } else if (abiOverride != null) { 5804 cpuAbiOverride = abiOverride; 5805 } else if (settings != null) { 5806 cpuAbiOverride = settings.cpuAbiOverrideString; 5807 } 5808 5809 return cpuAbiOverride; 5810 } 5811 5812 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5813 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5814 boolean success = false; 5815 try { 5816 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5817 currentTime, user); 5818 success = true; 5819 return res; 5820 } finally { 5821 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5822 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5823 } 5824 } 5825 } 5826 5827 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5828 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5829 final File scanFile = new File(pkg.codePath); 5830 if (pkg.applicationInfo.getCodePath() == null || 5831 pkg.applicationInfo.getResourcePath() == null) { 5832 // Bail out. The resource and code paths haven't been set. 5833 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5834 "Code and resource paths haven't been set correctly"); 5835 } 5836 5837 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5838 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5839 } else { 5840 // Only allow system apps to be flagged as core apps. 5841 pkg.coreApp = false; 5842 } 5843 5844 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5845 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5846 } 5847 5848 if (mCustomResolverComponentName != null && 5849 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5850 setUpCustomResolverActivity(pkg); 5851 } 5852 5853 if (pkg.packageName.equals("android")) { 5854 synchronized (mPackages) { 5855 if (mAndroidApplication != null) { 5856 Slog.w(TAG, "*************************************************"); 5857 Slog.w(TAG, "Core android package being redefined. Skipping."); 5858 Slog.w(TAG, " file=" + scanFile); 5859 Slog.w(TAG, "*************************************************"); 5860 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5861 "Core android package being redefined. Skipping."); 5862 } 5863 5864 // Set up information for our fall-back user intent resolution activity. 5865 mPlatformPackage = pkg; 5866 pkg.mVersionCode = mSdkVersion; 5867 mAndroidApplication = pkg.applicationInfo; 5868 5869 if (!mResolverReplaced) { 5870 mResolveActivity.applicationInfo = mAndroidApplication; 5871 mResolveActivity.name = ResolverActivity.class.getName(); 5872 mResolveActivity.packageName = mAndroidApplication.packageName; 5873 mResolveActivity.processName = "system:ui"; 5874 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5875 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5876 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5877 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5878 mResolveActivity.exported = true; 5879 mResolveActivity.enabled = true; 5880 mResolveInfo.activityInfo = mResolveActivity; 5881 mResolveInfo.priority = 0; 5882 mResolveInfo.preferredOrder = 0; 5883 mResolveInfo.match = 0; 5884 mResolveComponentName = new ComponentName( 5885 mAndroidApplication.packageName, mResolveActivity.name); 5886 } 5887 } 5888 } 5889 5890 if (DEBUG_PACKAGE_SCANNING) { 5891 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5892 Log.d(TAG, "Scanning package " + pkg.packageName); 5893 } 5894 5895 if (mPackages.containsKey(pkg.packageName) 5896 || mSharedLibraries.containsKey(pkg.packageName)) { 5897 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5898 "Application package " + pkg.packageName 5899 + " already installed. Skipping duplicate."); 5900 } 5901 5902 // If we're only installing presumed-existing packages, require that the 5903 // scanned APK is both already known and at the path previously established 5904 // for it. Previously unknown packages we pick up normally, but if we have an 5905 // a priori expectation about this package's install presence, enforce it. 5906 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5907 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5908 if (known != null) { 5909 if (DEBUG_PACKAGE_SCANNING) { 5910 Log.d(TAG, "Examining " + pkg.codePath 5911 + " and requiring known paths " + known.codePathString 5912 + " & " + known.resourcePathString); 5913 } 5914 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5915 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5916 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5917 "Application package " + pkg.packageName 5918 + " found at " + pkg.applicationInfo.getCodePath() 5919 + " but expected at " + known.codePathString + "; ignoring."); 5920 } 5921 } 5922 } 5923 5924 // Initialize package source and resource directories 5925 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5926 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5927 5928 SharedUserSetting suid = null; 5929 PackageSetting pkgSetting = null; 5930 5931 if (!isSystemApp(pkg)) { 5932 // Only system apps can use these features. 5933 pkg.mOriginalPackages = null; 5934 pkg.mRealPackage = null; 5935 pkg.mAdoptPermissions = null; 5936 } 5937 5938 // writer 5939 synchronized (mPackages) { 5940 if (pkg.mSharedUserId != null) { 5941 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5942 if (suid == null) { 5943 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5944 "Creating application package " + pkg.packageName 5945 + " for shared user failed"); 5946 } 5947 if (DEBUG_PACKAGE_SCANNING) { 5948 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5949 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5950 + "): packages=" + suid.packages); 5951 } 5952 } 5953 5954 // Check if we are renaming from an original package name. 5955 PackageSetting origPackage = null; 5956 String realName = null; 5957 if (pkg.mOriginalPackages != null) { 5958 // This package may need to be renamed to a previously 5959 // installed name. Let's check on that... 5960 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5961 if (pkg.mOriginalPackages.contains(renamed)) { 5962 // This package had originally been installed as the 5963 // original name, and we have already taken care of 5964 // transitioning to the new one. Just update the new 5965 // one to continue using the old name. 5966 realName = pkg.mRealPackage; 5967 if (!pkg.packageName.equals(renamed)) { 5968 // Callers into this function may have already taken 5969 // care of renaming the package; only do it here if 5970 // it is not already done. 5971 pkg.setPackageName(renamed); 5972 } 5973 5974 } else { 5975 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5976 if ((origPackage = mSettings.peekPackageLPr( 5977 pkg.mOriginalPackages.get(i))) != null) { 5978 // We do have the package already installed under its 5979 // original name... should we use it? 5980 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5981 // New package is not compatible with original. 5982 origPackage = null; 5983 continue; 5984 } else if (origPackage.sharedUser != null) { 5985 // Make sure uid is compatible between packages. 5986 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5987 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5988 + " to " + pkg.packageName + ": old uid " 5989 + origPackage.sharedUser.name 5990 + " differs from " + pkg.mSharedUserId); 5991 origPackage = null; 5992 continue; 5993 } 5994 } else { 5995 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5996 + pkg.packageName + " to old name " + origPackage.name); 5997 } 5998 break; 5999 } 6000 } 6001 } 6002 } 6003 6004 if (mTransferedPackages.contains(pkg.packageName)) { 6005 Slog.w(TAG, "Package " + pkg.packageName 6006 + " was transferred to another, but its .apk remains"); 6007 } 6008 6009 // Just create the setting, don't add it yet. For already existing packages 6010 // the PkgSetting exists already and doesn't have to be created. 6011 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6012 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6013 pkg.applicationInfo.primaryCpuAbi, 6014 pkg.applicationInfo.secondaryCpuAbi, 6015 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6016 user, false); 6017 if (pkgSetting == null) { 6018 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6019 "Creating application package " + pkg.packageName + " failed"); 6020 } 6021 6022 if (pkgSetting.origPackage != null) { 6023 // If we are first transitioning from an original package, 6024 // fix up the new package's name now. We need to do this after 6025 // looking up the package under its new name, so getPackageLP 6026 // can take care of fiddling things correctly. 6027 pkg.setPackageName(origPackage.name); 6028 6029 // File a report about this. 6030 String msg = "New package " + pkgSetting.realName 6031 + " renamed to replace old package " + pkgSetting.name; 6032 reportSettingsProblem(Log.WARN, msg); 6033 6034 // Make a note of it. 6035 mTransferedPackages.add(origPackage.name); 6036 6037 // No longer need to retain this. 6038 pkgSetting.origPackage = null; 6039 } 6040 6041 if (realName != null) { 6042 // Make a note of it. 6043 mTransferedPackages.add(pkg.packageName); 6044 } 6045 6046 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6047 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6048 } 6049 6050 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6051 // Check all shared libraries and map to their actual file path. 6052 // We only do this here for apps not on a system dir, because those 6053 // are the only ones that can fail an install due to this. We 6054 // will take care of the system apps by updating all of their 6055 // library paths after the scan is done. 6056 updateSharedLibrariesLPw(pkg, null); 6057 } 6058 6059 if (mFoundPolicyFile) { 6060 SELinuxMMAC.assignSeinfoValue(pkg); 6061 } 6062 6063 pkg.applicationInfo.uid = pkgSetting.appId; 6064 pkg.mExtras = pkgSetting; 6065 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 6066 try { 6067 verifySignaturesLP(pkgSetting, pkg); 6068 // We just determined the app is signed correctly, so bring 6069 // over the latest parsed certs. 6070 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6071 } catch (PackageManagerException e) { 6072 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6073 throw e; 6074 } 6075 // The signature has changed, but this package is in the system 6076 // image... let's recover! 6077 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6078 // However... if this package is part of a shared user, but it 6079 // doesn't match the signature of the shared user, let's fail. 6080 // What this means is that you can't change the signatures 6081 // associated with an overall shared user, which doesn't seem all 6082 // that unreasonable. 6083 if (pkgSetting.sharedUser != null) { 6084 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6085 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6086 throw new PackageManagerException( 6087 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6088 "Signature mismatch for shared user : " 6089 + pkgSetting.sharedUser); 6090 } 6091 } 6092 // File a report about this. 6093 String msg = "System package " + pkg.packageName 6094 + " signature changed; retaining data."; 6095 reportSettingsProblem(Log.WARN, msg); 6096 } 6097 } else { 6098 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6099 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6100 + pkg.packageName + " upgrade keys do not match the " 6101 + "previously installed version"); 6102 } else { 6103 // We just determined the app is signed correctly, so bring 6104 // over the latest parsed certs. 6105 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6106 } 6107 } 6108 // Verify that this new package doesn't have any content providers 6109 // that conflict with existing packages. Only do this if the 6110 // package isn't already installed, since we don't want to break 6111 // things that are installed. 6112 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6113 final int N = pkg.providers.size(); 6114 int i; 6115 for (i=0; i<N; i++) { 6116 PackageParser.Provider p = pkg.providers.get(i); 6117 if (p.info.authority != null) { 6118 String names[] = p.info.authority.split(";"); 6119 for (int j = 0; j < names.length; j++) { 6120 if (mProvidersByAuthority.containsKey(names[j])) { 6121 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6122 final String otherPackageName = 6123 ((other != null && other.getComponentName() != null) ? 6124 other.getComponentName().getPackageName() : "?"); 6125 throw new PackageManagerException( 6126 INSTALL_FAILED_CONFLICTING_PROVIDER, 6127 "Can't install because provider name " + names[j] 6128 + " (in package " + pkg.applicationInfo.packageName 6129 + ") is already used by " + otherPackageName); 6130 } 6131 } 6132 } 6133 } 6134 } 6135 6136 if (pkg.mAdoptPermissions != null) { 6137 // This package wants to adopt ownership of permissions from 6138 // another package. 6139 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6140 final String origName = pkg.mAdoptPermissions.get(i); 6141 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6142 if (orig != null) { 6143 if (verifyPackageUpdateLPr(orig, pkg)) { 6144 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6145 + pkg.packageName); 6146 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6147 } 6148 } 6149 } 6150 } 6151 } 6152 6153 final String pkgName = pkg.packageName; 6154 6155 final long scanFileTime = scanFile.lastModified(); 6156 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6157 pkg.applicationInfo.processName = fixProcessName( 6158 pkg.applicationInfo.packageName, 6159 pkg.applicationInfo.processName, 6160 pkg.applicationInfo.uid); 6161 6162 File dataPath; 6163 if (mPlatformPackage == pkg) { 6164 // The system package is special. 6165 dataPath = new File(Environment.getDataDirectory(), "system"); 6166 6167 pkg.applicationInfo.dataDir = dataPath.getPath(); 6168 6169 } else { 6170 // This is a normal package, need to make its data directory. 6171 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6172 UserHandle.USER_OWNER); 6173 6174 boolean uidError = false; 6175 if (dataPath.exists()) { 6176 int currentUid = 0; 6177 try { 6178 StructStat stat = Os.stat(dataPath.getPath()); 6179 currentUid = stat.st_uid; 6180 } catch (ErrnoException e) { 6181 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6182 } 6183 6184 // If we have mismatched owners for the data path, we have a problem. 6185 if (currentUid != pkg.applicationInfo.uid) { 6186 boolean recovered = false; 6187 if (currentUid == 0) { 6188 // The directory somehow became owned by root. Wow. 6189 // This is probably because the system was stopped while 6190 // installd was in the middle of messing with its libs 6191 // directory. Ask installd to fix that. 6192 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6193 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6194 if (ret >= 0) { 6195 recovered = true; 6196 String msg = "Package " + pkg.packageName 6197 + " unexpectedly changed to uid 0; recovered to " + 6198 + pkg.applicationInfo.uid; 6199 reportSettingsProblem(Log.WARN, msg); 6200 } 6201 } 6202 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6203 || (scanFlags&SCAN_BOOTING) != 0)) { 6204 // If this is a system app, we can at least delete its 6205 // current data so the application will still work. 6206 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6207 if (ret >= 0) { 6208 // TODO: Kill the processes first 6209 // Old data gone! 6210 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6211 ? "System package " : "Third party package "; 6212 String msg = prefix + pkg.packageName 6213 + " has changed from uid: " 6214 + currentUid + " to " 6215 + pkg.applicationInfo.uid + "; old data erased"; 6216 reportSettingsProblem(Log.WARN, msg); 6217 recovered = true; 6218 6219 // And now re-install the app. 6220 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6221 pkg.applicationInfo.seinfo); 6222 if (ret == -1) { 6223 // Ack should not happen! 6224 msg = prefix + pkg.packageName 6225 + " could not have data directory re-created after delete."; 6226 reportSettingsProblem(Log.WARN, msg); 6227 throw new PackageManagerException( 6228 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6229 } 6230 } 6231 if (!recovered) { 6232 mHasSystemUidErrors = true; 6233 } 6234 } else if (!recovered) { 6235 // If we allow this install to proceed, we will be broken. 6236 // Abort, abort! 6237 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6238 "scanPackageLI"); 6239 } 6240 if (!recovered) { 6241 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6242 + pkg.applicationInfo.uid + "/fs_" 6243 + currentUid; 6244 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6245 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6246 String msg = "Package " + pkg.packageName 6247 + " has mismatched uid: " 6248 + currentUid + " on disk, " 6249 + pkg.applicationInfo.uid + " in settings"; 6250 // writer 6251 synchronized (mPackages) { 6252 mSettings.mReadMessages.append(msg); 6253 mSettings.mReadMessages.append('\n'); 6254 uidError = true; 6255 if (!pkgSetting.uidError) { 6256 reportSettingsProblem(Log.ERROR, msg); 6257 } 6258 } 6259 } 6260 } 6261 pkg.applicationInfo.dataDir = dataPath.getPath(); 6262 if (mShouldRestoreconData) { 6263 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6264 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6265 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6266 } 6267 } else { 6268 if (DEBUG_PACKAGE_SCANNING) { 6269 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6270 Log.v(TAG, "Want this data dir: " + dataPath); 6271 } 6272 //invoke installer to do the actual installation 6273 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6274 pkg.applicationInfo.seinfo); 6275 if (ret < 0) { 6276 // Error from installer 6277 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6278 "Unable to create data dirs [errorCode=" + ret + "]"); 6279 } 6280 6281 if (dataPath.exists()) { 6282 pkg.applicationInfo.dataDir = dataPath.getPath(); 6283 } else { 6284 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6285 pkg.applicationInfo.dataDir = null; 6286 } 6287 } 6288 6289 pkgSetting.uidError = uidError; 6290 } 6291 6292 final String path = scanFile.getPath(); 6293 final String codePath = pkg.applicationInfo.getCodePath(); 6294 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6295 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6296 setBundledAppAbisAndRoots(pkg, pkgSetting); 6297 6298 // If we haven't found any native libraries for the app, check if it has 6299 // renderscript code. We'll need to force the app to 32 bit if it has 6300 // renderscript bitcode. 6301 if (pkg.applicationInfo.primaryCpuAbi == null 6302 && pkg.applicationInfo.secondaryCpuAbi == null 6303 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6304 NativeLibraryHelper.Handle handle = null; 6305 try { 6306 handle = NativeLibraryHelper.Handle.create(scanFile); 6307 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6308 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6309 } 6310 } catch (IOException ioe) { 6311 Slog.w(TAG, "Error scanning system app : " + ioe); 6312 } finally { 6313 IoUtils.closeQuietly(handle); 6314 } 6315 } 6316 6317 setNativeLibraryPaths(pkg); 6318 } else { 6319 // TODO: We can probably be smarter about this stuff. For installed apps, 6320 // we can calculate this information at install time once and for all. For 6321 // system apps, we can probably assume that this information doesn't change 6322 // after the first boot scan. As things stand, we do lots of unnecessary work. 6323 6324 // Give ourselves some initial paths; we'll come back for another 6325 // pass once we've determined ABI below. 6326 setNativeLibraryPaths(pkg); 6327 6328 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6329 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6330 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6331 6332 NativeLibraryHelper.Handle handle = null; 6333 try { 6334 handle = NativeLibraryHelper.Handle.create(scanFile); 6335 // TODO(multiArch): This can be null for apps that didn't go through the 6336 // usual installation process. We can calculate it again, like we 6337 // do during install time. 6338 // 6339 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6340 // unnecessary. 6341 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6342 6343 // Null out the abis so that they can be recalculated. 6344 pkg.applicationInfo.primaryCpuAbi = null; 6345 pkg.applicationInfo.secondaryCpuAbi = null; 6346 if (isMultiArch(pkg.applicationInfo)) { 6347 // Warn if we've set an abiOverride for multi-lib packages.. 6348 // By definition, we need to copy both 32 and 64 bit libraries for 6349 // such packages. 6350 if (pkg.cpuAbiOverride != null 6351 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6352 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6353 } 6354 6355 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6356 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6357 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6358 if (isAsec) { 6359 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6360 } else { 6361 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6362 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6363 useIsaSpecificSubdirs); 6364 } 6365 } 6366 6367 maybeThrowExceptionForMultiArchCopy( 6368 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6369 6370 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6371 if (isAsec) { 6372 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6373 } else { 6374 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6375 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6376 useIsaSpecificSubdirs); 6377 } 6378 } 6379 6380 maybeThrowExceptionForMultiArchCopy( 6381 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6382 6383 if (abi64 >= 0) { 6384 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6385 } 6386 6387 if (abi32 >= 0) { 6388 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6389 if (abi64 >= 0) { 6390 pkg.applicationInfo.secondaryCpuAbi = abi; 6391 } else { 6392 pkg.applicationInfo.primaryCpuAbi = abi; 6393 } 6394 } 6395 } else { 6396 String[] abiList = (cpuAbiOverride != null) ? 6397 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6398 6399 // Enable gross and lame hacks for apps that are built with old 6400 // SDK tools. We must scan their APKs for renderscript bitcode and 6401 // not launch them if it's present. Don't bother checking on devices 6402 // that don't have 64 bit support. 6403 boolean needsRenderScriptOverride = false; 6404 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6405 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6406 abiList = Build.SUPPORTED_32_BIT_ABIS; 6407 needsRenderScriptOverride = true; 6408 } 6409 6410 final int copyRet; 6411 if (isAsec) { 6412 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6413 } else { 6414 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6415 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6416 } 6417 6418 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6419 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6420 "Error unpackaging native libs for app, errorCode=" + copyRet); 6421 } 6422 6423 if (copyRet >= 0) { 6424 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6425 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6426 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6427 } else if (needsRenderScriptOverride) { 6428 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6429 } 6430 } 6431 } catch (IOException ioe) { 6432 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6433 } finally { 6434 IoUtils.closeQuietly(handle); 6435 } 6436 6437 // Now that we've calculated the ABIs and determined if it's an internal app, 6438 // we will go ahead and populate the nativeLibraryPath. 6439 setNativeLibraryPaths(pkg); 6440 6441 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6442 final int[] userIds = sUserManager.getUserIds(); 6443 synchronized (mInstallLock) { 6444 // Create a native library symlink only if we have native libraries 6445 // and if the native libraries are 32 bit libraries. We do not provide 6446 // this symlink for 64 bit libraries. 6447 if (pkg.applicationInfo.primaryCpuAbi != null && 6448 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6449 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6450 for (int userId : userIds) { 6451 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6452 nativeLibPath, userId) < 0) { 6453 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6454 "Failed linking native library dir (user=" + userId + ")"); 6455 } 6456 } 6457 } 6458 } 6459 } 6460 6461 // This is a special case for the "system" package, where the ABI is 6462 // dictated by the zygote configuration (and init.rc). We should keep track 6463 // of this ABI so that we can deal with "normal" applications that run under 6464 // the same UID correctly. 6465 if (mPlatformPackage == pkg) { 6466 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6467 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6468 } 6469 6470 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6471 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6472 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6473 // Copy the derived override back to the parsed package, so that we can 6474 // update the package settings accordingly. 6475 pkg.cpuAbiOverride = cpuAbiOverride; 6476 6477 if (DEBUG_ABI_SELECTION) { 6478 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6479 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6480 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6481 } 6482 6483 // Push the derived path down into PackageSettings so we know what to 6484 // clean up at uninstall time. 6485 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6486 6487 if (DEBUG_ABI_SELECTION) { 6488 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6489 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6490 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6491 } 6492 6493 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6494 // We don't do this here during boot because we can do it all 6495 // at once after scanning all existing packages. 6496 // 6497 // We also do this *before* we perform dexopt on this package, so that 6498 // we can avoid redundant dexopts, and also to make sure we've got the 6499 // code and package path correct. 6500 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6501 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6502 } 6503 6504 if ((scanFlags & SCAN_NO_DEX) == 0) { 6505 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6506 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6507 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6508 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6509 } 6510 } 6511 if (mFactoryTest && pkg.requestedPermissions.contains( 6512 android.Manifest.permission.FACTORY_TEST)) { 6513 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6514 } 6515 6516 ArrayList<PackageParser.Package> clientLibPkgs = null; 6517 6518 // writer 6519 synchronized (mPackages) { 6520 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6521 // Only system apps can add new shared libraries. 6522 if (pkg.libraryNames != null) { 6523 for (int i=0; i<pkg.libraryNames.size(); i++) { 6524 String name = pkg.libraryNames.get(i); 6525 boolean allowed = false; 6526 if (pkg.isUpdatedSystemApp()) { 6527 // New library entries can only be added through the 6528 // system image. This is important to get rid of a lot 6529 // of nasty edge cases: for example if we allowed a non- 6530 // system update of the app to add a library, then uninstalling 6531 // the update would make the library go away, and assumptions 6532 // we made such as through app install filtering would now 6533 // have allowed apps on the device which aren't compatible 6534 // with it. Better to just have the restriction here, be 6535 // conservative, and create many fewer cases that can negatively 6536 // impact the user experience. 6537 final PackageSetting sysPs = mSettings 6538 .getDisabledSystemPkgLPr(pkg.packageName); 6539 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6540 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6541 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6542 allowed = true; 6543 allowed = true; 6544 break; 6545 } 6546 } 6547 } 6548 } else { 6549 allowed = true; 6550 } 6551 if (allowed) { 6552 if (!mSharedLibraries.containsKey(name)) { 6553 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6554 } else if (!name.equals(pkg.packageName)) { 6555 Slog.w(TAG, "Package " + pkg.packageName + " library " 6556 + name + " already exists; skipping"); 6557 } 6558 } else { 6559 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6560 + name + " that is not declared on system image; skipping"); 6561 } 6562 } 6563 if ((scanFlags&SCAN_BOOTING) == 0) { 6564 // If we are not booting, we need to update any applications 6565 // that are clients of our shared library. If we are booting, 6566 // this will all be done once the scan is complete. 6567 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6568 } 6569 } 6570 } 6571 } 6572 6573 // We also need to dexopt any apps that are dependent on this library. Note that 6574 // if these fail, we should abort the install since installing the library will 6575 // result in some apps being broken. 6576 if (clientLibPkgs != null) { 6577 if ((scanFlags & SCAN_NO_DEX) == 0) { 6578 for (int i = 0; i < clientLibPkgs.size(); i++) { 6579 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6580 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6581 null /* instruction sets */, forceDex, 6582 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6583 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6584 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6585 "scanPackageLI failed to dexopt clientLibPkgs"); 6586 } 6587 } 6588 } 6589 } 6590 6591 // Also need to kill any apps that are dependent on the library. 6592 if (clientLibPkgs != null) { 6593 for (int i=0; i<clientLibPkgs.size(); i++) { 6594 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6595 killApplication(clientPkg.applicationInfo.packageName, 6596 clientPkg.applicationInfo.uid, "update lib"); 6597 } 6598 } 6599 6600 // writer 6601 synchronized (mPackages) { 6602 // We don't expect installation to fail beyond this point 6603 6604 // Add the new setting to mSettings 6605 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6606 // Add the new setting to mPackages 6607 mPackages.put(pkg.applicationInfo.packageName, pkg); 6608 // Make sure we don't accidentally delete its data. 6609 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6610 while (iter.hasNext()) { 6611 PackageCleanItem item = iter.next(); 6612 if (pkgName.equals(item.packageName)) { 6613 iter.remove(); 6614 } 6615 } 6616 6617 // Take care of first install / last update times. 6618 if (currentTime != 0) { 6619 if (pkgSetting.firstInstallTime == 0) { 6620 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6621 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6622 pkgSetting.lastUpdateTime = currentTime; 6623 } 6624 } else if (pkgSetting.firstInstallTime == 0) { 6625 // We need *something*. Take time time stamp of the file. 6626 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6627 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6628 if (scanFileTime != pkgSetting.timeStamp) { 6629 // A package on the system image has changed; consider this 6630 // to be an update. 6631 pkgSetting.lastUpdateTime = scanFileTime; 6632 } 6633 } 6634 6635 // Add the package's KeySets to the global KeySetManagerService 6636 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6637 try { 6638 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6639 if (pkg.mKeySetMapping != null) { 6640 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6641 if (pkg.mUpgradeKeySets != null) { 6642 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6643 } 6644 } 6645 } catch (NullPointerException e) { 6646 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6647 } catch (IllegalArgumentException e) { 6648 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6649 } 6650 6651 int N = pkg.providers.size(); 6652 StringBuilder r = null; 6653 int i; 6654 for (i=0; i<N; i++) { 6655 PackageParser.Provider p = pkg.providers.get(i); 6656 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6657 p.info.processName, pkg.applicationInfo.uid); 6658 mProviders.addProvider(p); 6659 p.syncable = p.info.isSyncable; 6660 if (p.info.authority != null) { 6661 String names[] = p.info.authority.split(";"); 6662 p.info.authority = null; 6663 for (int j = 0; j < names.length; j++) { 6664 if (j == 1 && p.syncable) { 6665 // We only want the first authority for a provider to possibly be 6666 // syncable, so if we already added this provider using a different 6667 // authority clear the syncable flag. We copy the provider before 6668 // changing it because the mProviders object contains a reference 6669 // to a provider that we don't want to change. 6670 // Only do this for the second authority since the resulting provider 6671 // object can be the same for all future authorities for this provider. 6672 p = new PackageParser.Provider(p); 6673 p.syncable = false; 6674 } 6675 if (!mProvidersByAuthority.containsKey(names[j])) { 6676 mProvidersByAuthority.put(names[j], p); 6677 if (p.info.authority == null) { 6678 p.info.authority = names[j]; 6679 } else { 6680 p.info.authority = p.info.authority + ";" + names[j]; 6681 } 6682 if (DEBUG_PACKAGE_SCANNING) { 6683 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6684 Log.d(TAG, "Registered content provider: " + names[j] 6685 + ", className = " + p.info.name + ", isSyncable = " 6686 + p.info.isSyncable); 6687 } 6688 } else { 6689 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6690 Slog.w(TAG, "Skipping provider name " + names[j] + 6691 " (in package " + pkg.applicationInfo.packageName + 6692 "): name already used by " 6693 + ((other != null && other.getComponentName() != null) 6694 ? other.getComponentName().getPackageName() : "?")); 6695 } 6696 } 6697 } 6698 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6699 if (r == null) { 6700 r = new StringBuilder(256); 6701 } else { 6702 r.append(' '); 6703 } 6704 r.append(p.info.name); 6705 } 6706 } 6707 if (r != null) { 6708 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6709 } 6710 6711 N = pkg.services.size(); 6712 r = null; 6713 for (i=0; i<N; i++) { 6714 PackageParser.Service s = pkg.services.get(i); 6715 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6716 s.info.processName, pkg.applicationInfo.uid); 6717 mServices.addService(s); 6718 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6719 if (r == null) { 6720 r = new StringBuilder(256); 6721 } else { 6722 r.append(' '); 6723 } 6724 r.append(s.info.name); 6725 } 6726 } 6727 if (r != null) { 6728 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6729 } 6730 6731 N = pkg.receivers.size(); 6732 r = null; 6733 for (i=0; i<N; i++) { 6734 PackageParser.Activity a = pkg.receivers.get(i); 6735 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6736 a.info.processName, pkg.applicationInfo.uid); 6737 mReceivers.addActivity(a, "receiver"); 6738 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6739 if (r == null) { 6740 r = new StringBuilder(256); 6741 } else { 6742 r.append(' '); 6743 } 6744 r.append(a.info.name); 6745 } 6746 } 6747 if (r != null) { 6748 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6749 } 6750 6751 N = pkg.activities.size(); 6752 r = null; 6753 for (i=0; i<N; i++) { 6754 PackageParser.Activity a = pkg.activities.get(i); 6755 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6756 a.info.processName, pkg.applicationInfo.uid); 6757 mActivities.addActivity(a, "activity"); 6758 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6759 if (r == null) { 6760 r = new StringBuilder(256); 6761 } else { 6762 r.append(' '); 6763 } 6764 r.append(a.info.name); 6765 } 6766 } 6767 if (r != null) { 6768 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6769 } 6770 6771 N = pkg.permissionGroups.size(); 6772 r = null; 6773 for (i=0; i<N; i++) { 6774 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6775 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6776 if (cur == null) { 6777 mPermissionGroups.put(pg.info.name, pg); 6778 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6779 if (r == null) { 6780 r = new StringBuilder(256); 6781 } else { 6782 r.append(' '); 6783 } 6784 r.append(pg.info.name); 6785 } 6786 } else { 6787 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6788 + pg.info.packageName + " ignored: original from " 6789 + cur.info.packageName); 6790 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6791 if (r == null) { 6792 r = new StringBuilder(256); 6793 } else { 6794 r.append(' '); 6795 } 6796 r.append("DUP:"); 6797 r.append(pg.info.name); 6798 } 6799 } 6800 } 6801 if (r != null) { 6802 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6803 } 6804 6805 N = pkg.permissions.size(); 6806 r = null; 6807 for (i=0; i<N; i++) { 6808 PackageParser.Permission p = pkg.permissions.get(i); 6809 6810 // Now that permission groups have a special meaning, we ignore permission 6811 // groups for legacy apps to prevent unexpected behavior. In particular, 6812 // permissions for one app being granted to someone just becuase they happen 6813 // to be in a group defined by another app (before this had no implications). 6814 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6815 p.group = mPermissionGroups.get(p.info.group); 6816 // Warn for a permission in an unknown group. 6817 if (p.info.group != null && p.group == null) { 6818 Slog.w(TAG, "Permission " + p.info.name + " from package " 6819 + p.info.packageName + " in an unknown group " + p.info.group); 6820 } 6821 } 6822 6823 ArrayMap<String, BasePermission> permissionMap = 6824 p.tree ? mSettings.mPermissionTrees 6825 : mSettings.mPermissions; 6826 BasePermission bp = permissionMap.get(p.info.name); 6827 6828 // Allow system apps to redefine non-system permissions 6829 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6830 final boolean currentOwnerIsSystem = (bp.perm != null 6831 && isSystemApp(bp.perm.owner)); 6832 if (isSystemApp(p.owner)) { 6833 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6834 // It's a built-in permission and no owner, take ownership now 6835 bp.packageSetting = pkgSetting; 6836 bp.perm = p; 6837 bp.uid = pkg.applicationInfo.uid; 6838 bp.sourcePackage = p.info.packageName; 6839 } else if (!currentOwnerIsSystem) { 6840 String msg = "New decl " + p.owner + " of permission " 6841 + p.info.name + " is system; overriding " + bp.sourcePackage; 6842 reportSettingsProblem(Log.WARN, msg); 6843 bp = null; 6844 } 6845 } 6846 } 6847 6848 if (bp == null) { 6849 bp = new BasePermission(p.info.name, p.info.packageName, 6850 BasePermission.TYPE_NORMAL); 6851 permissionMap.put(p.info.name, bp); 6852 } 6853 6854 if (bp.perm == null) { 6855 if (bp.sourcePackage == null 6856 || bp.sourcePackage.equals(p.info.packageName)) { 6857 BasePermission tree = findPermissionTreeLP(p.info.name); 6858 if (tree == null 6859 || tree.sourcePackage.equals(p.info.packageName)) { 6860 bp.packageSetting = pkgSetting; 6861 bp.perm = p; 6862 bp.uid = pkg.applicationInfo.uid; 6863 bp.sourcePackage = p.info.packageName; 6864 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6865 if (r == null) { 6866 r = new StringBuilder(256); 6867 } else { 6868 r.append(' '); 6869 } 6870 r.append(p.info.name); 6871 } 6872 } else { 6873 Slog.w(TAG, "Permission " + p.info.name + " from package " 6874 + p.info.packageName + " ignored: base tree " 6875 + tree.name + " is from package " 6876 + tree.sourcePackage); 6877 } 6878 } else { 6879 Slog.w(TAG, "Permission " + p.info.name + " from package " 6880 + p.info.packageName + " ignored: original from " 6881 + bp.sourcePackage); 6882 } 6883 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6884 if (r == null) { 6885 r = new StringBuilder(256); 6886 } else { 6887 r.append(' '); 6888 } 6889 r.append("DUP:"); 6890 r.append(p.info.name); 6891 } 6892 if (bp.perm == p) { 6893 bp.protectionLevel = p.info.protectionLevel; 6894 } 6895 } 6896 6897 if (r != null) { 6898 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6899 } 6900 6901 N = pkg.instrumentation.size(); 6902 r = null; 6903 for (i=0; i<N; i++) { 6904 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6905 a.info.packageName = pkg.applicationInfo.packageName; 6906 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6907 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6908 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6909 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6910 a.info.dataDir = pkg.applicationInfo.dataDir; 6911 6912 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6913 // need other information about the application, like the ABI and what not ? 6914 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6915 mInstrumentation.put(a.getComponentName(), a); 6916 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6917 if (r == null) { 6918 r = new StringBuilder(256); 6919 } else { 6920 r.append(' '); 6921 } 6922 r.append(a.info.name); 6923 } 6924 } 6925 if (r != null) { 6926 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6927 } 6928 6929 if (pkg.protectedBroadcasts != null) { 6930 N = pkg.protectedBroadcasts.size(); 6931 for (i=0; i<N; i++) { 6932 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6933 } 6934 } 6935 6936 pkgSetting.setTimeStamp(scanFileTime); 6937 6938 // Create idmap files for pairs of (packages, overlay packages). 6939 // Note: "android", ie framework-res.apk, is handled by native layers. 6940 if (pkg.mOverlayTarget != null) { 6941 // This is an overlay package. 6942 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6943 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6944 mOverlays.put(pkg.mOverlayTarget, 6945 new ArrayMap<String, PackageParser.Package>()); 6946 } 6947 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6948 map.put(pkg.packageName, pkg); 6949 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6950 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6951 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6952 "scanPackageLI failed to createIdmap"); 6953 } 6954 } 6955 } else if (mOverlays.containsKey(pkg.packageName) && 6956 !pkg.packageName.equals("android")) { 6957 // This is a regular package, with one or more known overlay packages. 6958 createIdmapsForPackageLI(pkg); 6959 } 6960 } 6961 6962 return pkg; 6963 } 6964 6965 /** 6966 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6967 * i.e, so that all packages can be run inside a single process if required. 6968 * 6969 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6970 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6971 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6972 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6973 * updating a package that belongs to a shared user. 6974 * 6975 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6976 * adds unnecessary complexity. 6977 */ 6978 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6979 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6980 String requiredInstructionSet = null; 6981 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6982 requiredInstructionSet = VMRuntime.getInstructionSet( 6983 scannedPackage.applicationInfo.primaryCpuAbi); 6984 } 6985 6986 PackageSetting requirer = null; 6987 for (PackageSetting ps : packagesForUser) { 6988 // If packagesForUser contains scannedPackage, we skip it. This will happen 6989 // when scannedPackage is an update of an existing package. Without this check, 6990 // we will never be able to change the ABI of any package belonging to a shared 6991 // user, even if it's compatible with other packages. 6992 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6993 if (ps.primaryCpuAbiString == null) { 6994 continue; 6995 } 6996 6997 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6998 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6999 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7000 // this but there's not much we can do. 7001 String errorMessage = "Instruction set mismatch, " 7002 + ((requirer == null) ? "[caller]" : requirer) 7003 + " requires " + requiredInstructionSet + " whereas " + ps 7004 + " requires " + instructionSet; 7005 Slog.w(TAG, errorMessage); 7006 } 7007 7008 if (requiredInstructionSet == null) { 7009 requiredInstructionSet = instructionSet; 7010 requirer = ps; 7011 } 7012 } 7013 } 7014 7015 if (requiredInstructionSet != null) { 7016 String adjustedAbi; 7017 if (requirer != null) { 7018 // requirer != null implies that either scannedPackage was null or that scannedPackage 7019 // did not require an ABI, in which case we have to adjust scannedPackage to match 7020 // the ABI of the set (which is the same as requirer's ABI) 7021 adjustedAbi = requirer.primaryCpuAbiString; 7022 if (scannedPackage != null) { 7023 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7024 } 7025 } else { 7026 // requirer == null implies that we're updating all ABIs in the set to 7027 // match scannedPackage. 7028 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7029 } 7030 7031 for (PackageSetting ps : packagesForUser) { 7032 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7033 if (ps.primaryCpuAbiString != null) { 7034 continue; 7035 } 7036 7037 ps.primaryCpuAbiString = adjustedAbi; 7038 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7039 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7040 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7041 7042 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7043 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7044 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7045 ps.primaryCpuAbiString = null; 7046 ps.pkg.applicationInfo.primaryCpuAbi = null; 7047 return; 7048 } else { 7049 mInstaller.rmdex(ps.codePathString, 7050 getDexCodeInstructionSet(getPreferredInstructionSet())); 7051 } 7052 } 7053 } 7054 } 7055 } 7056 } 7057 7058 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7059 synchronized (mPackages) { 7060 mResolverReplaced = true; 7061 // Set up information for custom user intent resolution activity. 7062 mResolveActivity.applicationInfo = pkg.applicationInfo; 7063 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7064 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7065 mResolveActivity.processName = pkg.applicationInfo.packageName; 7066 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7067 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7068 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7069 mResolveActivity.theme = 0; 7070 mResolveActivity.exported = true; 7071 mResolveActivity.enabled = true; 7072 mResolveInfo.activityInfo = mResolveActivity; 7073 mResolveInfo.priority = 0; 7074 mResolveInfo.preferredOrder = 0; 7075 mResolveInfo.match = 0; 7076 mResolveComponentName = mCustomResolverComponentName; 7077 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7078 mResolveComponentName); 7079 } 7080 } 7081 7082 private static String calculateBundledApkRoot(final String codePathString) { 7083 final File codePath = new File(codePathString); 7084 final File codeRoot; 7085 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7086 codeRoot = Environment.getRootDirectory(); 7087 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7088 codeRoot = Environment.getOemDirectory(); 7089 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7090 codeRoot = Environment.getVendorDirectory(); 7091 } else { 7092 // Unrecognized code path; take its top real segment as the apk root: 7093 // e.g. /something/app/blah.apk => /something 7094 try { 7095 File f = codePath.getCanonicalFile(); 7096 File parent = f.getParentFile(); // non-null because codePath is a file 7097 File tmp; 7098 while ((tmp = parent.getParentFile()) != null) { 7099 f = parent; 7100 parent = tmp; 7101 } 7102 codeRoot = f; 7103 Slog.w(TAG, "Unrecognized code path " 7104 + codePath + " - using " + codeRoot); 7105 } catch (IOException e) { 7106 // Can't canonicalize the code path -- shenanigans? 7107 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7108 return Environment.getRootDirectory().getPath(); 7109 } 7110 } 7111 return codeRoot.getPath(); 7112 } 7113 7114 /** 7115 * Derive and set the location of native libraries for the given package, 7116 * which varies depending on where and how the package was installed. 7117 */ 7118 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7119 final ApplicationInfo info = pkg.applicationInfo; 7120 final String codePath = pkg.codePath; 7121 final File codeFile = new File(codePath); 7122 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7123 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7124 7125 info.nativeLibraryRootDir = null; 7126 info.nativeLibraryRootRequiresIsa = false; 7127 info.nativeLibraryDir = null; 7128 info.secondaryNativeLibraryDir = null; 7129 7130 if (isApkFile(codeFile)) { 7131 // Monolithic install 7132 if (bundledApp) { 7133 // If "/system/lib64/apkname" exists, assume that is the per-package 7134 // native library directory to use; otherwise use "/system/lib/apkname". 7135 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7136 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7137 getPrimaryInstructionSet(info)); 7138 7139 // This is a bundled system app so choose the path based on the ABI. 7140 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7141 // is just the default path. 7142 final String apkName = deriveCodePathName(codePath); 7143 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7144 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7145 apkName).getAbsolutePath(); 7146 7147 if (info.secondaryCpuAbi != null) { 7148 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7149 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7150 secondaryLibDir, apkName).getAbsolutePath(); 7151 } 7152 } else if (asecApp) { 7153 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7154 .getAbsolutePath(); 7155 } else { 7156 final String apkName = deriveCodePathName(codePath); 7157 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7158 .getAbsolutePath(); 7159 } 7160 7161 info.nativeLibraryRootRequiresIsa = false; 7162 info.nativeLibraryDir = info.nativeLibraryRootDir; 7163 } else { 7164 // Cluster install 7165 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7166 info.nativeLibraryRootRequiresIsa = true; 7167 7168 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7169 getPrimaryInstructionSet(info)).getAbsolutePath(); 7170 7171 if (info.secondaryCpuAbi != null) { 7172 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7173 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7174 } 7175 } 7176 } 7177 7178 /** 7179 * Calculate the abis and roots for a bundled app. These can uniquely 7180 * be determined from the contents of the system partition, i.e whether 7181 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7182 * of this information, and instead assume that the system was built 7183 * sensibly. 7184 */ 7185 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7186 PackageSetting pkgSetting) { 7187 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7188 7189 // If "/system/lib64/apkname" exists, assume that is the per-package 7190 // native library directory to use; otherwise use "/system/lib/apkname". 7191 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7192 setBundledAppAbi(pkg, apkRoot, apkName); 7193 // pkgSetting might be null during rescan following uninstall of updates 7194 // to a bundled app, so accommodate that possibility. The settings in 7195 // that case will be established later from the parsed package. 7196 // 7197 // If the settings aren't null, sync them up with what we've just derived. 7198 // note that apkRoot isn't stored in the package settings. 7199 if (pkgSetting != null) { 7200 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7201 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7202 } 7203 } 7204 7205 /** 7206 * Deduces the ABI of a bundled app and sets the relevant fields on the 7207 * parsed pkg object. 7208 * 7209 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7210 * under which system libraries are installed. 7211 * @param apkName the name of the installed package. 7212 */ 7213 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7214 final File codeFile = new File(pkg.codePath); 7215 7216 final boolean has64BitLibs; 7217 final boolean has32BitLibs; 7218 if (isApkFile(codeFile)) { 7219 // Monolithic install 7220 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7221 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7222 } else { 7223 // Cluster install 7224 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7225 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7226 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7227 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7228 has64BitLibs = (new File(rootDir, isa)).exists(); 7229 } else { 7230 has64BitLibs = false; 7231 } 7232 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7233 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7234 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7235 has32BitLibs = (new File(rootDir, isa)).exists(); 7236 } else { 7237 has32BitLibs = false; 7238 } 7239 } 7240 7241 if (has64BitLibs && !has32BitLibs) { 7242 // The package has 64 bit libs, but not 32 bit libs. Its primary 7243 // ABI should be 64 bit. We can safely assume here that the bundled 7244 // native libraries correspond to the most preferred ABI in the list. 7245 7246 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7247 pkg.applicationInfo.secondaryCpuAbi = null; 7248 } else if (has32BitLibs && !has64BitLibs) { 7249 // The package has 32 bit libs but not 64 bit libs. Its primary 7250 // ABI should be 32 bit. 7251 7252 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7253 pkg.applicationInfo.secondaryCpuAbi = null; 7254 } else if (has32BitLibs && has64BitLibs) { 7255 // The application has both 64 and 32 bit bundled libraries. We check 7256 // here that the app declares multiArch support, and warn if it doesn't. 7257 // 7258 // We will be lenient here and record both ABIs. The primary will be the 7259 // ABI that's higher on the list, i.e, a device that's configured to prefer 7260 // 64 bit apps will see a 64 bit primary ABI, 7261 7262 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7263 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7264 } 7265 7266 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7267 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7268 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7269 } else { 7270 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7271 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7272 } 7273 } else { 7274 pkg.applicationInfo.primaryCpuAbi = null; 7275 pkg.applicationInfo.secondaryCpuAbi = null; 7276 } 7277 } 7278 7279 private void killApplication(String pkgName, int appId, String reason) { 7280 // Request the ActivityManager to kill the process(only for existing packages) 7281 // so that we do not end up in a confused state while the user is still using the older 7282 // version of the application while the new one gets installed. 7283 IActivityManager am = ActivityManagerNative.getDefault(); 7284 if (am != null) { 7285 try { 7286 am.killApplicationWithAppId(pkgName, appId, reason); 7287 } catch (RemoteException e) { 7288 } 7289 } 7290 } 7291 7292 void removePackageLI(PackageSetting ps, boolean chatty) { 7293 if (DEBUG_INSTALL) { 7294 if (chatty) 7295 Log.d(TAG, "Removing package " + ps.name); 7296 } 7297 7298 // writer 7299 synchronized (mPackages) { 7300 mPackages.remove(ps.name); 7301 final PackageParser.Package pkg = ps.pkg; 7302 if (pkg != null) { 7303 cleanPackageDataStructuresLILPw(pkg, chatty); 7304 } 7305 } 7306 } 7307 7308 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7309 if (DEBUG_INSTALL) { 7310 if (chatty) 7311 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7312 } 7313 7314 // writer 7315 synchronized (mPackages) { 7316 mPackages.remove(pkg.applicationInfo.packageName); 7317 cleanPackageDataStructuresLILPw(pkg, chatty); 7318 } 7319 } 7320 7321 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7322 int N = pkg.providers.size(); 7323 StringBuilder r = null; 7324 int i; 7325 for (i=0; i<N; i++) { 7326 PackageParser.Provider p = pkg.providers.get(i); 7327 mProviders.removeProvider(p); 7328 if (p.info.authority == null) { 7329 7330 /* There was another ContentProvider with this authority when 7331 * this app was installed so this authority is null, 7332 * Ignore it as we don't have to unregister the provider. 7333 */ 7334 continue; 7335 } 7336 String names[] = p.info.authority.split(";"); 7337 for (int j = 0; j < names.length; j++) { 7338 if (mProvidersByAuthority.get(names[j]) == p) { 7339 mProvidersByAuthority.remove(names[j]); 7340 if (DEBUG_REMOVE) { 7341 if (chatty) 7342 Log.d(TAG, "Unregistered content provider: " + names[j] 7343 + ", className = " + p.info.name + ", isSyncable = " 7344 + p.info.isSyncable); 7345 } 7346 } 7347 } 7348 if (DEBUG_REMOVE && chatty) { 7349 if (r == null) { 7350 r = new StringBuilder(256); 7351 } else { 7352 r.append(' '); 7353 } 7354 r.append(p.info.name); 7355 } 7356 } 7357 if (r != null) { 7358 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7359 } 7360 7361 N = pkg.services.size(); 7362 r = null; 7363 for (i=0; i<N; i++) { 7364 PackageParser.Service s = pkg.services.get(i); 7365 mServices.removeService(s); 7366 if (chatty) { 7367 if (r == null) { 7368 r = new StringBuilder(256); 7369 } else { 7370 r.append(' '); 7371 } 7372 r.append(s.info.name); 7373 } 7374 } 7375 if (r != null) { 7376 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7377 } 7378 7379 N = pkg.receivers.size(); 7380 r = null; 7381 for (i=0; i<N; i++) { 7382 PackageParser.Activity a = pkg.receivers.get(i); 7383 mReceivers.removeActivity(a, "receiver"); 7384 if (DEBUG_REMOVE && chatty) { 7385 if (r == null) { 7386 r = new StringBuilder(256); 7387 } else { 7388 r.append(' '); 7389 } 7390 r.append(a.info.name); 7391 } 7392 } 7393 if (r != null) { 7394 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7395 } 7396 7397 N = pkg.activities.size(); 7398 r = null; 7399 for (i=0; i<N; i++) { 7400 PackageParser.Activity a = pkg.activities.get(i); 7401 mActivities.removeActivity(a, "activity"); 7402 if (DEBUG_REMOVE && chatty) { 7403 if (r == null) { 7404 r = new StringBuilder(256); 7405 } else { 7406 r.append(' '); 7407 } 7408 r.append(a.info.name); 7409 } 7410 } 7411 if (r != null) { 7412 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7413 } 7414 7415 N = pkg.permissions.size(); 7416 r = null; 7417 for (i=0; i<N; i++) { 7418 PackageParser.Permission p = pkg.permissions.get(i); 7419 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7420 if (bp == null) { 7421 bp = mSettings.mPermissionTrees.get(p.info.name); 7422 } 7423 if (bp != null && bp.perm == p) { 7424 bp.perm = null; 7425 if (DEBUG_REMOVE && chatty) { 7426 if (r == null) { 7427 r = new StringBuilder(256); 7428 } else { 7429 r.append(' '); 7430 } 7431 r.append(p.info.name); 7432 } 7433 } 7434 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7435 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7436 if (appOpPerms != null) { 7437 appOpPerms.remove(pkg.packageName); 7438 } 7439 } 7440 } 7441 if (r != null) { 7442 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7443 } 7444 7445 N = pkg.requestedPermissions.size(); 7446 r = null; 7447 for (i=0; i<N; i++) { 7448 String perm = pkg.requestedPermissions.get(i); 7449 BasePermission bp = mSettings.mPermissions.get(perm); 7450 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7451 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7452 if (appOpPerms != null) { 7453 appOpPerms.remove(pkg.packageName); 7454 if (appOpPerms.isEmpty()) { 7455 mAppOpPermissionPackages.remove(perm); 7456 } 7457 } 7458 } 7459 } 7460 if (r != null) { 7461 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7462 } 7463 7464 N = pkg.instrumentation.size(); 7465 r = null; 7466 for (i=0; i<N; i++) { 7467 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7468 mInstrumentation.remove(a.getComponentName()); 7469 if (DEBUG_REMOVE && chatty) { 7470 if (r == null) { 7471 r = new StringBuilder(256); 7472 } else { 7473 r.append(' '); 7474 } 7475 r.append(a.info.name); 7476 } 7477 } 7478 if (r != null) { 7479 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7480 } 7481 7482 r = null; 7483 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7484 // Only system apps can hold shared libraries. 7485 if (pkg.libraryNames != null) { 7486 for (i=0; i<pkg.libraryNames.size(); i++) { 7487 String name = pkg.libraryNames.get(i); 7488 SharedLibraryEntry cur = mSharedLibraries.get(name); 7489 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7490 mSharedLibraries.remove(name); 7491 if (DEBUG_REMOVE && chatty) { 7492 if (r == null) { 7493 r = new StringBuilder(256); 7494 } else { 7495 r.append(' '); 7496 } 7497 r.append(name); 7498 } 7499 } 7500 } 7501 } 7502 } 7503 if (r != null) { 7504 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7505 } 7506 } 7507 7508 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7509 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7510 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7511 return true; 7512 } 7513 } 7514 return false; 7515 } 7516 7517 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7518 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7519 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7520 7521 private void updatePermissionsLPw(String changingPkg, 7522 PackageParser.Package pkgInfo, int flags) { 7523 // Make sure there are no dangling permission trees. 7524 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7525 while (it.hasNext()) { 7526 final BasePermission bp = it.next(); 7527 if (bp.packageSetting == null) { 7528 // We may not yet have parsed the package, so just see if 7529 // we still know about its settings. 7530 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7531 } 7532 if (bp.packageSetting == null) { 7533 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7534 + " from package " + bp.sourcePackage); 7535 it.remove(); 7536 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7537 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7538 Slog.i(TAG, "Removing old permission tree: " + bp.name 7539 + " from package " + bp.sourcePackage); 7540 flags |= UPDATE_PERMISSIONS_ALL; 7541 it.remove(); 7542 } 7543 } 7544 } 7545 7546 // Make sure all dynamic permissions have been assigned to a package, 7547 // and make sure there are no dangling permissions. 7548 it = mSettings.mPermissions.values().iterator(); 7549 while (it.hasNext()) { 7550 final BasePermission bp = it.next(); 7551 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7552 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7553 + bp.name + " pkg=" + bp.sourcePackage 7554 + " info=" + bp.pendingInfo); 7555 if (bp.packageSetting == null && bp.pendingInfo != null) { 7556 final BasePermission tree = findPermissionTreeLP(bp.name); 7557 if (tree != null && tree.perm != null) { 7558 bp.packageSetting = tree.packageSetting; 7559 bp.perm = new PackageParser.Permission(tree.perm.owner, 7560 new PermissionInfo(bp.pendingInfo)); 7561 bp.perm.info.packageName = tree.perm.info.packageName; 7562 bp.perm.info.name = bp.name; 7563 bp.uid = tree.uid; 7564 } 7565 } 7566 } 7567 if (bp.packageSetting == null) { 7568 // We may not yet have parsed the package, so just see if 7569 // we still know about its settings. 7570 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7571 } 7572 if (bp.packageSetting == null) { 7573 Slog.w(TAG, "Removing dangling permission: " + bp.name 7574 + " from package " + bp.sourcePackage); 7575 it.remove(); 7576 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7577 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7578 Slog.i(TAG, "Removing old permission: " + bp.name 7579 + " from package " + bp.sourcePackage); 7580 flags |= UPDATE_PERMISSIONS_ALL; 7581 it.remove(); 7582 } 7583 } 7584 } 7585 7586 // Now update the permissions for all packages, in particular 7587 // replace the granted permissions of the system packages. 7588 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7589 for (PackageParser.Package pkg : mPackages.values()) { 7590 if (pkg != pkgInfo) { 7591 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7592 changingPkg); 7593 } 7594 } 7595 } 7596 7597 if (pkgInfo != null) { 7598 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7599 } 7600 } 7601 7602 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7603 String packageOfInterest) { 7604 // IMPORTANT: There are two types of permissions: install and runtime. 7605 // Install time permissions are granted when the app is installed to 7606 // all device users and users added in the future. Runtime permissions 7607 // are granted at runtime explicitly to specific users. Normal and signature 7608 // protected permissions are install time permissions. Dangerous permissions 7609 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7610 // otherwise they are runtime permissions. This function does not manage 7611 // runtime permissions except for the case an app targeting Lollipop MR1 7612 // being upgraded to target a newer SDK, in which case dangerous permissions 7613 // are transformed from install time to runtime ones. 7614 7615 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7616 if (ps == null) { 7617 return; 7618 } 7619 7620 PermissionsState permissionsState = ps.getPermissionsState(); 7621 PermissionsState origPermissions = permissionsState; 7622 7623 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7624 7625 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7626 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7627 7628 boolean changedInstallPermission = false; 7629 7630 if (replace) { 7631 ps.installPermissionsFixed = false; 7632 if (!ps.isSharedUser()) { 7633 origPermissions = new PermissionsState(permissionsState); 7634 permissionsState.reset(); 7635 } 7636 } 7637 7638 permissionsState.setGlobalGids(mGlobalGids); 7639 7640 final int N = pkg.requestedPermissions.size(); 7641 for (int i=0; i<N; i++) { 7642 final String name = pkg.requestedPermissions.get(i); 7643 final BasePermission bp = mSettings.mPermissions.get(name); 7644 7645 if (DEBUG_INSTALL) { 7646 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7647 } 7648 7649 if (bp == null || bp.packageSetting == null) { 7650 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7651 Slog.w(TAG, "Unknown permission " + name 7652 + " in package " + pkg.packageName); 7653 } 7654 continue; 7655 } 7656 7657 final String perm = bp.name; 7658 boolean allowedSig = false; 7659 int grant = GRANT_DENIED; 7660 7661 // Keep track of app op permissions. 7662 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7663 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7664 if (pkgs == null) { 7665 pkgs = new ArraySet<>(); 7666 mAppOpPermissionPackages.put(bp.name, pkgs); 7667 } 7668 pkgs.add(pkg.packageName); 7669 } 7670 7671 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7672 switch (level) { 7673 case PermissionInfo.PROTECTION_NORMAL: { 7674 // For all apps normal permissions are install time ones. 7675 grant = GRANT_INSTALL; 7676 } break; 7677 7678 case PermissionInfo.PROTECTION_DANGEROUS: { 7679 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7680 // For legacy apps dangerous permissions are install time ones. 7681 grant = GRANT_INSTALL; 7682 } else if (ps.isSystem()) { 7683 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7684 if (origPermissions.hasInstallPermission(bp.name)) { 7685 // If a system app had an install permission, then the app was 7686 // upgraded and we grant the permissions as runtime to all users. 7687 grant = GRANT_UPGRADE; 7688 upgradeUserIds = currentUserIds; 7689 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7690 // If users changed since the last permissions update for a 7691 // system app, we grant the permission as runtime to the new users. 7692 grant = GRANT_UPGRADE; 7693 upgradeUserIds = currentUserIds; 7694 for (int userId : updatedUserIds) { 7695 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7696 } 7697 } else { 7698 // Otherwise, we grant the permission as runtime if the app 7699 // already had it, i.e. we preserve runtime permissions. 7700 grant = GRANT_RUNTIME; 7701 } 7702 } else if (origPermissions.hasInstallPermission(bp.name)) { 7703 // For legacy apps that became modern, install becomes runtime. 7704 grant = GRANT_UPGRADE; 7705 upgradeUserIds = currentUserIds; 7706 } else if (replace) { 7707 // For upgraded modern apps keep runtime permissions unchanged. 7708 grant = GRANT_RUNTIME; 7709 } 7710 } break; 7711 7712 case PermissionInfo.PROTECTION_SIGNATURE: { 7713 // For all apps signature permissions are install time ones. 7714 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7715 if (allowedSig) { 7716 grant = GRANT_INSTALL; 7717 } 7718 } break; 7719 } 7720 7721 if (DEBUG_INSTALL) { 7722 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7723 } 7724 7725 if (grant != GRANT_DENIED) { 7726 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7727 // If this is an existing, non-system package, then 7728 // we can't add any new permissions to it. 7729 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7730 // Except... if this is a permission that was added 7731 // to the platform (note: need to only do this when 7732 // updating the platform). 7733 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7734 grant = GRANT_DENIED; 7735 } 7736 } 7737 } 7738 7739 switch (grant) { 7740 case GRANT_INSTALL: { 7741 // Grant an install permission. 7742 if (permissionsState.grantInstallPermission(bp) != 7743 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7744 changedInstallPermission = true; 7745 } 7746 } break; 7747 7748 case GRANT_RUNTIME: { 7749 // Grant previously granted runtime permissions. 7750 for (int userId : UserManagerService.getInstance().getUserIds()) { 7751 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7752 PermissionState permissionState = origPermissions 7753 .getRuntimePermissionState(bp.name, userId); 7754 final int flags = permissionState.getFlags(); 7755 if (permissionsState.grantRuntimePermission(bp, userId) == 7756 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7757 // If we cannot put the permission as it was, we have to write. 7758 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7759 changedRuntimePermissionUserIds, userId); 7760 } else { 7761 // Propagate the permission flags. 7762 permissionsState.updatePermissionFlags(bp, userId, 7763 flags, flags); 7764 } 7765 } 7766 } 7767 } break; 7768 7769 case GRANT_UPGRADE: { 7770 // Grant runtime permissions for a previously held install permission. 7771 PermissionState permissionState = origPermissions 7772 .getInstallPermissionState(bp.name); 7773 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7774 7775 origPermissions.revokeInstallPermission(bp); 7776 // We will be transferring the permission flags, so clear them. 7777 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7778 PackageManager.MASK_PERMISSION_FLAGS, 0); 7779 7780 // If the permission is not to be promoted to runtime we ignore it and 7781 // also its other flags as they are not applicable to install permissions. 7782 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7783 for (int userId : upgradeUserIds) { 7784 if (permissionsState.grantRuntimePermission(bp, userId) != 7785 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7786 // Transfer the permission flags. 7787 permissionsState.updatePermissionFlags(bp, userId, 7788 flags, flags); 7789 // If we granted the permission, we have to write. 7790 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7791 changedRuntimePermissionUserIds, userId); 7792 } 7793 } 7794 } 7795 } break; 7796 7797 default: { 7798 if (packageOfInterest == null 7799 || packageOfInterest.equals(pkg.packageName)) { 7800 Slog.w(TAG, "Not granting permission " + perm 7801 + " to package " + pkg.packageName 7802 + " because it was previously installed without"); 7803 } 7804 } break; 7805 } 7806 } else { 7807 if (permissionsState.revokeInstallPermission(bp) != 7808 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7809 // Also drop the permission flags. 7810 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7811 PackageManager.MASK_PERMISSION_FLAGS, 0); 7812 changedInstallPermission = true; 7813 Slog.i(TAG, "Un-granting permission " + perm 7814 + " from package " + pkg.packageName 7815 + " (protectionLevel=" + bp.protectionLevel 7816 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7817 + ")"); 7818 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7819 // Don't print warning for app op permissions, since it is fine for them 7820 // not to be granted, there is a UI for the user to decide. 7821 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7822 Slog.w(TAG, "Not granting permission " + perm 7823 + " to package " + pkg.packageName 7824 + " (protectionLevel=" + bp.protectionLevel 7825 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7826 + ")"); 7827 } 7828 } 7829 } 7830 } 7831 7832 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7833 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7834 // This is the first that we have heard about this package, so the 7835 // permissions we have now selected are fixed until explicitly 7836 // changed. 7837 ps.installPermissionsFixed = true; 7838 } 7839 7840 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7841 7842 // Persist the runtime permissions state for users with changes. 7843 for (int userId : changedRuntimePermissionUserIds) { 7844 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7845 } 7846 } 7847 7848 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7849 boolean allowed = false; 7850 final int NP = PackageParser.NEW_PERMISSIONS.length; 7851 for (int ip=0; ip<NP; ip++) { 7852 final PackageParser.NewPermissionInfo npi 7853 = PackageParser.NEW_PERMISSIONS[ip]; 7854 if (npi.name.equals(perm) 7855 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7856 allowed = true; 7857 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7858 + pkg.packageName); 7859 break; 7860 } 7861 } 7862 return allowed; 7863 } 7864 7865 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7866 BasePermission bp, PermissionsState origPermissions) { 7867 boolean allowed; 7868 allowed = (compareSignatures( 7869 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7870 == PackageManager.SIGNATURE_MATCH) 7871 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7872 == PackageManager.SIGNATURE_MATCH); 7873 if (!allowed && (bp.protectionLevel 7874 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7875 if (isSystemApp(pkg)) { 7876 // For updated system applications, a system permission 7877 // is granted only if it had been defined by the original application. 7878 if (pkg.isUpdatedSystemApp()) { 7879 final PackageSetting sysPs = mSettings 7880 .getDisabledSystemPkgLPr(pkg.packageName); 7881 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7882 // If the original was granted this permission, we take 7883 // that grant decision as read and propagate it to the 7884 // update. 7885 if (sysPs.isPrivileged()) { 7886 allowed = true; 7887 } 7888 } else { 7889 // The system apk may have been updated with an older 7890 // version of the one on the data partition, but which 7891 // granted a new system permission that it didn't have 7892 // before. In this case we do want to allow the app to 7893 // now get the new permission if the ancestral apk is 7894 // privileged to get it. 7895 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7896 for (int j=0; 7897 j<sysPs.pkg.requestedPermissions.size(); j++) { 7898 if (perm.equals( 7899 sysPs.pkg.requestedPermissions.get(j))) { 7900 allowed = true; 7901 break; 7902 } 7903 } 7904 } 7905 } 7906 } else { 7907 allowed = isPrivilegedApp(pkg); 7908 } 7909 } 7910 } 7911 if (!allowed && (bp.protectionLevel 7912 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7913 // For development permissions, a development permission 7914 // is granted only if it was already granted. 7915 allowed = origPermissions.hasInstallPermission(perm); 7916 } 7917 return allowed; 7918 } 7919 7920 final class ActivityIntentResolver 7921 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7922 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7923 boolean defaultOnly, int userId) { 7924 if (!sUserManager.exists(userId)) return null; 7925 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7926 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7927 } 7928 7929 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7930 int userId) { 7931 if (!sUserManager.exists(userId)) return null; 7932 mFlags = flags; 7933 return super.queryIntent(intent, resolvedType, 7934 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7935 } 7936 7937 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7938 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7939 if (!sUserManager.exists(userId)) return null; 7940 if (packageActivities == null) { 7941 return null; 7942 } 7943 mFlags = flags; 7944 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7945 final int N = packageActivities.size(); 7946 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7947 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7948 7949 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7950 for (int i = 0; i < N; ++i) { 7951 intentFilters = packageActivities.get(i).intents; 7952 if (intentFilters != null && intentFilters.size() > 0) { 7953 PackageParser.ActivityIntentInfo[] array = 7954 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7955 intentFilters.toArray(array); 7956 listCut.add(array); 7957 } 7958 } 7959 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7960 } 7961 7962 public final void addActivity(PackageParser.Activity a, String type) { 7963 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7964 mActivities.put(a.getComponentName(), a); 7965 if (DEBUG_SHOW_INFO) 7966 Log.v( 7967 TAG, " " + type + " " + 7968 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7969 if (DEBUG_SHOW_INFO) 7970 Log.v(TAG, " Class=" + a.info.name); 7971 final int NI = a.intents.size(); 7972 for (int j=0; j<NI; j++) { 7973 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7974 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7975 intent.setPriority(0); 7976 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7977 + a.className + " with priority > 0, forcing to 0"); 7978 } 7979 if (DEBUG_SHOW_INFO) { 7980 Log.v(TAG, " IntentFilter:"); 7981 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7982 } 7983 if (!intent.debugCheck()) { 7984 Log.w(TAG, "==> For Activity " + a.info.name); 7985 } 7986 addFilter(intent); 7987 } 7988 } 7989 7990 public final void removeActivity(PackageParser.Activity a, String type) { 7991 mActivities.remove(a.getComponentName()); 7992 if (DEBUG_SHOW_INFO) { 7993 Log.v(TAG, " " + type + " " 7994 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7995 : a.info.name) + ":"); 7996 Log.v(TAG, " Class=" + a.info.name); 7997 } 7998 final int NI = a.intents.size(); 7999 for (int j=0; j<NI; j++) { 8000 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8001 if (DEBUG_SHOW_INFO) { 8002 Log.v(TAG, " IntentFilter:"); 8003 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8004 } 8005 removeFilter(intent); 8006 } 8007 } 8008 8009 @Override 8010 protected boolean allowFilterResult( 8011 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8012 ActivityInfo filterAi = filter.activity.info; 8013 for (int i=dest.size()-1; i>=0; i--) { 8014 ActivityInfo destAi = dest.get(i).activityInfo; 8015 if (destAi.name == filterAi.name 8016 && destAi.packageName == filterAi.packageName) { 8017 return false; 8018 } 8019 } 8020 return true; 8021 } 8022 8023 @Override 8024 protected ActivityIntentInfo[] newArray(int size) { 8025 return new ActivityIntentInfo[size]; 8026 } 8027 8028 @Override 8029 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8030 if (!sUserManager.exists(userId)) return true; 8031 PackageParser.Package p = filter.activity.owner; 8032 if (p != null) { 8033 PackageSetting ps = (PackageSetting)p.mExtras; 8034 if (ps != null) { 8035 // System apps are never considered stopped for purposes of 8036 // filtering, because there may be no way for the user to 8037 // actually re-launch them. 8038 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8039 && ps.getStopped(userId); 8040 } 8041 } 8042 return false; 8043 } 8044 8045 @Override 8046 protected boolean isPackageForFilter(String packageName, 8047 PackageParser.ActivityIntentInfo info) { 8048 return packageName.equals(info.activity.owner.packageName); 8049 } 8050 8051 @Override 8052 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8053 int match, int userId) { 8054 if (!sUserManager.exists(userId)) return null; 8055 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8056 return null; 8057 } 8058 final PackageParser.Activity activity = info.activity; 8059 if (mSafeMode && (activity.info.applicationInfo.flags 8060 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8061 return null; 8062 } 8063 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8064 if (ps == null) { 8065 return null; 8066 } 8067 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8068 ps.readUserState(userId), userId); 8069 if (ai == null) { 8070 return null; 8071 } 8072 final ResolveInfo res = new ResolveInfo(); 8073 res.activityInfo = ai; 8074 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8075 res.filter = info; 8076 } 8077 if (info != null) { 8078 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8079 } 8080 res.priority = info.getPriority(); 8081 res.preferredOrder = activity.owner.mPreferredOrder; 8082 //System.out.println("Result: " + res.activityInfo.className + 8083 // " = " + res.priority); 8084 res.match = match; 8085 res.isDefault = info.hasDefault; 8086 res.labelRes = info.labelRes; 8087 res.nonLocalizedLabel = info.nonLocalizedLabel; 8088 if (userNeedsBadging(userId)) { 8089 res.noResourceId = true; 8090 } else { 8091 res.icon = info.icon; 8092 } 8093 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8094 return res; 8095 } 8096 8097 @Override 8098 protected void sortResults(List<ResolveInfo> results) { 8099 Collections.sort(results, mResolvePrioritySorter); 8100 } 8101 8102 @Override 8103 protected void dumpFilter(PrintWriter out, String prefix, 8104 PackageParser.ActivityIntentInfo filter) { 8105 out.print(prefix); out.print( 8106 Integer.toHexString(System.identityHashCode(filter.activity))); 8107 out.print(' '); 8108 filter.activity.printComponentShortName(out); 8109 out.print(" filter "); 8110 out.println(Integer.toHexString(System.identityHashCode(filter))); 8111 } 8112 8113 @Override 8114 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8115 return filter.activity; 8116 } 8117 8118 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8119 PackageParser.Activity activity = (PackageParser.Activity)label; 8120 out.print(prefix); out.print( 8121 Integer.toHexString(System.identityHashCode(activity))); 8122 out.print(' '); 8123 activity.printComponentShortName(out); 8124 if (count > 1) { 8125 out.print(" ("); out.print(count); out.print(" filters)"); 8126 } 8127 out.println(); 8128 } 8129 8130// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8131// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8132// final List<ResolveInfo> retList = Lists.newArrayList(); 8133// while (i.hasNext()) { 8134// final ResolveInfo resolveInfo = i.next(); 8135// if (isEnabledLP(resolveInfo.activityInfo)) { 8136// retList.add(resolveInfo); 8137// } 8138// } 8139// return retList; 8140// } 8141 8142 // Keys are String (activity class name), values are Activity. 8143 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8144 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8145 private int mFlags; 8146 } 8147 8148 private final class ServiceIntentResolver 8149 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8150 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8151 boolean defaultOnly, int userId) { 8152 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8153 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8154 } 8155 8156 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8157 int userId) { 8158 if (!sUserManager.exists(userId)) return null; 8159 mFlags = flags; 8160 return super.queryIntent(intent, resolvedType, 8161 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8162 } 8163 8164 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8165 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8166 if (!sUserManager.exists(userId)) return null; 8167 if (packageServices == null) { 8168 return null; 8169 } 8170 mFlags = flags; 8171 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8172 final int N = packageServices.size(); 8173 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8174 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8175 8176 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8177 for (int i = 0; i < N; ++i) { 8178 intentFilters = packageServices.get(i).intents; 8179 if (intentFilters != null && intentFilters.size() > 0) { 8180 PackageParser.ServiceIntentInfo[] array = 8181 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8182 intentFilters.toArray(array); 8183 listCut.add(array); 8184 } 8185 } 8186 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8187 } 8188 8189 public final void addService(PackageParser.Service s) { 8190 mServices.put(s.getComponentName(), s); 8191 if (DEBUG_SHOW_INFO) { 8192 Log.v(TAG, " " 8193 + (s.info.nonLocalizedLabel != null 8194 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8195 Log.v(TAG, " Class=" + s.info.name); 8196 } 8197 final int NI = s.intents.size(); 8198 int j; 8199 for (j=0; j<NI; j++) { 8200 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8201 if (DEBUG_SHOW_INFO) { 8202 Log.v(TAG, " IntentFilter:"); 8203 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8204 } 8205 if (!intent.debugCheck()) { 8206 Log.w(TAG, "==> For Service " + s.info.name); 8207 } 8208 addFilter(intent); 8209 } 8210 } 8211 8212 public final void removeService(PackageParser.Service s) { 8213 mServices.remove(s.getComponentName()); 8214 if (DEBUG_SHOW_INFO) { 8215 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8216 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8217 Log.v(TAG, " Class=" + s.info.name); 8218 } 8219 final int NI = s.intents.size(); 8220 int j; 8221 for (j=0; j<NI; j++) { 8222 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8223 if (DEBUG_SHOW_INFO) { 8224 Log.v(TAG, " IntentFilter:"); 8225 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8226 } 8227 removeFilter(intent); 8228 } 8229 } 8230 8231 @Override 8232 protected boolean allowFilterResult( 8233 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8234 ServiceInfo filterSi = filter.service.info; 8235 for (int i=dest.size()-1; i>=0; i--) { 8236 ServiceInfo destAi = dest.get(i).serviceInfo; 8237 if (destAi.name == filterSi.name 8238 && destAi.packageName == filterSi.packageName) { 8239 return false; 8240 } 8241 } 8242 return true; 8243 } 8244 8245 @Override 8246 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8247 return new PackageParser.ServiceIntentInfo[size]; 8248 } 8249 8250 @Override 8251 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8252 if (!sUserManager.exists(userId)) return true; 8253 PackageParser.Package p = filter.service.owner; 8254 if (p != null) { 8255 PackageSetting ps = (PackageSetting)p.mExtras; 8256 if (ps != null) { 8257 // System apps are never considered stopped for purposes of 8258 // filtering, because there may be no way for the user to 8259 // actually re-launch them. 8260 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8261 && ps.getStopped(userId); 8262 } 8263 } 8264 return false; 8265 } 8266 8267 @Override 8268 protected boolean isPackageForFilter(String packageName, 8269 PackageParser.ServiceIntentInfo info) { 8270 return packageName.equals(info.service.owner.packageName); 8271 } 8272 8273 @Override 8274 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8275 int match, int userId) { 8276 if (!sUserManager.exists(userId)) return null; 8277 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8278 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8279 return null; 8280 } 8281 final PackageParser.Service service = info.service; 8282 if (mSafeMode && (service.info.applicationInfo.flags 8283 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8284 return null; 8285 } 8286 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8287 if (ps == null) { 8288 return null; 8289 } 8290 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8291 ps.readUserState(userId), userId); 8292 if (si == null) { 8293 return null; 8294 } 8295 final ResolveInfo res = new ResolveInfo(); 8296 res.serviceInfo = si; 8297 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8298 res.filter = filter; 8299 } 8300 res.priority = info.getPriority(); 8301 res.preferredOrder = service.owner.mPreferredOrder; 8302 res.match = match; 8303 res.isDefault = info.hasDefault; 8304 res.labelRes = info.labelRes; 8305 res.nonLocalizedLabel = info.nonLocalizedLabel; 8306 res.icon = info.icon; 8307 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8308 return res; 8309 } 8310 8311 @Override 8312 protected void sortResults(List<ResolveInfo> results) { 8313 Collections.sort(results, mResolvePrioritySorter); 8314 } 8315 8316 @Override 8317 protected void dumpFilter(PrintWriter out, String prefix, 8318 PackageParser.ServiceIntentInfo filter) { 8319 out.print(prefix); out.print( 8320 Integer.toHexString(System.identityHashCode(filter.service))); 8321 out.print(' '); 8322 filter.service.printComponentShortName(out); 8323 out.print(" filter "); 8324 out.println(Integer.toHexString(System.identityHashCode(filter))); 8325 } 8326 8327 @Override 8328 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8329 return filter.service; 8330 } 8331 8332 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8333 PackageParser.Service service = (PackageParser.Service)label; 8334 out.print(prefix); out.print( 8335 Integer.toHexString(System.identityHashCode(service))); 8336 out.print(' '); 8337 service.printComponentShortName(out); 8338 if (count > 1) { 8339 out.print(" ("); out.print(count); out.print(" filters)"); 8340 } 8341 out.println(); 8342 } 8343 8344// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8345// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8346// final List<ResolveInfo> retList = Lists.newArrayList(); 8347// while (i.hasNext()) { 8348// final ResolveInfo resolveInfo = (ResolveInfo) i; 8349// if (isEnabledLP(resolveInfo.serviceInfo)) { 8350// retList.add(resolveInfo); 8351// } 8352// } 8353// return retList; 8354// } 8355 8356 // Keys are String (activity class name), values are Activity. 8357 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8358 = new ArrayMap<ComponentName, PackageParser.Service>(); 8359 private int mFlags; 8360 }; 8361 8362 private final class ProviderIntentResolver 8363 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8364 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8365 boolean defaultOnly, int userId) { 8366 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8367 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8368 } 8369 8370 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8371 int userId) { 8372 if (!sUserManager.exists(userId)) 8373 return null; 8374 mFlags = flags; 8375 return super.queryIntent(intent, resolvedType, 8376 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8377 } 8378 8379 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8380 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8381 if (!sUserManager.exists(userId)) 8382 return null; 8383 if (packageProviders == null) { 8384 return null; 8385 } 8386 mFlags = flags; 8387 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8388 final int N = packageProviders.size(); 8389 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8390 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8391 8392 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8393 for (int i = 0; i < N; ++i) { 8394 intentFilters = packageProviders.get(i).intents; 8395 if (intentFilters != null && intentFilters.size() > 0) { 8396 PackageParser.ProviderIntentInfo[] array = 8397 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8398 intentFilters.toArray(array); 8399 listCut.add(array); 8400 } 8401 } 8402 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8403 } 8404 8405 public final void addProvider(PackageParser.Provider p) { 8406 if (mProviders.containsKey(p.getComponentName())) { 8407 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8408 return; 8409 } 8410 8411 mProviders.put(p.getComponentName(), p); 8412 if (DEBUG_SHOW_INFO) { 8413 Log.v(TAG, " " 8414 + (p.info.nonLocalizedLabel != null 8415 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8416 Log.v(TAG, " Class=" + p.info.name); 8417 } 8418 final int NI = p.intents.size(); 8419 int j; 8420 for (j = 0; j < NI; j++) { 8421 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8422 if (DEBUG_SHOW_INFO) { 8423 Log.v(TAG, " IntentFilter:"); 8424 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8425 } 8426 if (!intent.debugCheck()) { 8427 Log.w(TAG, "==> For Provider " + p.info.name); 8428 } 8429 addFilter(intent); 8430 } 8431 } 8432 8433 public final void removeProvider(PackageParser.Provider p) { 8434 mProviders.remove(p.getComponentName()); 8435 if (DEBUG_SHOW_INFO) { 8436 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8437 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8438 Log.v(TAG, " Class=" + p.info.name); 8439 } 8440 final int NI = p.intents.size(); 8441 int j; 8442 for (j = 0; j < NI; j++) { 8443 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8444 if (DEBUG_SHOW_INFO) { 8445 Log.v(TAG, " IntentFilter:"); 8446 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8447 } 8448 removeFilter(intent); 8449 } 8450 } 8451 8452 @Override 8453 protected boolean allowFilterResult( 8454 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8455 ProviderInfo filterPi = filter.provider.info; 8456 for (int i = dest.size() - 1; i >= 0; i--) { 8457 ProviderInfo destPi = dest.get(i).providerInfo; 8458 if (destPi.name == filterPi.name 8459 && destPi.packageName == filterPi.packageName) { 8460 return false; 8461 } 8462 } 8463 return true; 8464 } 8465 8466 @Override 8467 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8468 return new PackageParser.ProviderIntentInfo[size]; 8469 } 8470 8471 @Override 8472 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8473 if (!sUserManager.exists(userId)) 8474 return true; 8475 PackageParser.Package p = filter.provider.owner; 8476 if (p != null) { 8477 PackageSetting ps = (PackageSetting) p.mExtras; 8478 if (ps != null) { 8479 // System apps are never considered stopped for purposes of 8480 // filtering, because there may be no way for the user to 8481 // actually re-launch them. 8482 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8483 && ps.getStopped(userId); 8484 } 8485 } 8486 return false; 8487 } 8488 8489 @Override 8490 protected boolean isPackageForFilter(String packageName, 8491 PackageParser.ProviderIntentInfo info) { 8492 return packageName.equals(info.provider.owner.packageName); 8493 } 8494 8495 @Override 8496 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8497 int match, int userId) { 8498 if (!sUserManager.exists(userId)) 8499 return null; 8500 final PackageParser.ProviderIntentInfo info = filter; 8501 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8502 return null; 8503 } 8504 final PackageParser.Provider provider = info.provider; 8505 if (mSafeMode && (provider.info.applicationInfo.flags 8506 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8507 return null; 8508 } 8509 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8510 if (ps == null) { 8511 return null; 8512 } 8513 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8514 ps.readUserState(userId), userId); 8515 if (pi == null) { 8516 return null; 8517 } 8518 final ResolveInfo res = new ResolveInfo(); 8519 res.providerInfo = pi; 8520 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8521 res.filter = filter; 8522 } 8523 res.priority = info.getPriority(); 8524 res.preferredOrder = provider.owner.mPreferredOrder; 8525 res.match = match; 8526 res.isDefault = info.hasDefault; 8527 res.labelRes = info.labelRes; 8528 res.nonLocalizedLabel = info.nonLocalizedLabel; 8529 res.icon = info.icon; 8530 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8531 return res; 8532 } 8533 8534 @Override 8535 protected void sortResults(List<ResolveInfo> results) { 8536 Collections.sort(results, mResolvePrioritySorter); 8537 } 8538 8539 @Override 8540 protected void dumpFilter(PrintWriter out, String prefix, 8541 PackageParser.ProviderIntentInfo filter) { 8542 out.print(prefix); 8543 out.print( 8544 Integer.toHexString(System.identityHashCode(filter.provider))); 8545 out.print(' '); 8546 filter.provider.printComponentShortName(out); 8547 out.print(" filter "); 8548 out.println(Integer.toHexString(System.identityHashCode(filter))); 8549 } 8550 8551 @Override 8552 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8553 return filter.provider; 8554 } 8555 8556 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8557 PackageParser.Provider provider = (PackageParser.Provider)label; 8558 out.print(prefix); out.print( 8559 Integer.toHexString(System.identityHashCode(provider))); 8560 out.print(' '); 8561 provider.printComponentShortName(out); 8562 if (count > 1) { 8563 out.print(" ("); out.print(count); out.print(" filters)"); 8564 } 8565 out.println(); 8566 } 8567 8568 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8569 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8570 private int mFlags; 8571 }; 8572 8573 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8574 new Comparator<ResolveInfo>() { 8575 public int compare(ResolveInfo r1, ResolveInfo r2) { 8576 int v1 = r1.priority; 8577 int v2 = r2.priority; 8578 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8579 if (v1 != v2) { 8580 return (v1 > v2) ? -1 : 1; 8581 } 8582 v1 = r1.preferredOrder; 8583 v2 = r2.preferredOrder; 8584 if (v1 != v2) { 8585 return (v1 > v2) ? -1 : 1; 8586 } 8587 if (r1.isDefault != r2.isDefault) { 8588 return r1.isDefault ? -1 : 1; 8589 } 8590 v1 = r1.match; 8591 v2 = r2.match; 8592 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8593 if (v1 != v2) { 8594 return (v1 > v2) ? -1 : 1; 8595 } 8596 if (r1.system != r2.system) { 8597 return r1.system ? -1 : 1; 8598 } 8599 return 0; 8600 } 8601 }; 8602 8603 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8604 new Comparator<ProviderInfo>() { 8605 public int compare(ProviderInfo p1, ProviderInfo p2) { 8606 final int v1 = p1.initOrder; 8607 final int v2 = p2.initOrder; 8608 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8609 } 8610 }; 8611 8612 final void sendPackageBroadcast(final String action, final String pkg, 8613 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8614 final int[] userIds) { 8615 mHandler.post(new Runnable() { 8616 @Override 8617 public void run() { 8618 try { 8619 final IActivityManager am = ActivityManagerNative.getDefault(); 8620 if (am == null) return; 8621 final int[] resolvedUserIds; 8622 if (userIds == null) { 8623 resolvedUserIds = am.getRunningUserIds(); 8624 } else { 8625 resolvedUserIds = userIds; 8626 } 8627 for (int id : resolvedUserIds) { 8628 final Intent intent = new Intent(action, 8629 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8630 if (extras != null) { 8631 intent.putExtras(extras); 8632 } 8633 if (targetPkg != null) { 8634 intent.setPackage(targetPkg); 8635 } 8636 // Modify the UID when posting to other users 8637 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8638 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8639 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8640 intent.putExtra(Intent.EXTRA_UID, uid); 8641 } 8642 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8643 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8644 if (DEBUG_BROADCASTS) { 8645 RuntimeException here = new RuntimeException("here"); 8646 here.fillInStackTrace(); 8647 Slog.d(TAG, "Sending to user " + id + ": " 8648 + intent.toShortString(false, true, false, false) 8649 + " " + intent.getExtras(), here); 8650 } 8651 am.broadcastIntent(null, intent, null, finishedReceiver, 8652 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8653 finishedReceiver != null, false, id); 8654 } 8655 } catch (RemoteException ex) { 8656 } 8657 } 8658 }); 8659 } 8660 8661 /** 8662 * Check if the external storage media is available. This is true if there 8663 * is a mounted external storage medium or if the external storage is 8664 * emulated. 8665 */ 8666 private boolean isExternalMediaAvailable() { 8667 return mMediaMounted || Environment.isExternalStorageEmulated(); 8668 } 8669 8670 @Override 8671 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8672 // writer 8673 synchronized (mPackages) { 8674 if (!isExternalMediaAvailable()) { 8675 // If the external storage is no longer mounted at this point, 8676 // the caller may not have been able to delete all of this 8677 // packages files and can not delete any more. Bail. 8678 return null; 8679 } 8680 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8681 if (lastPackage != null) { 8682 pkgs.remove(lastPackage); 8683 } 8684 if (pkgs.size() > 0) { 8685 return pkgs.get(0); 8686 } 8687 } 8688 return null; 8689 } 8690 8691 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8692 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8693 userId, andCode ? 1 : 0, packageName); 8694 if (mSystemReady) { 8695 msg.sendToTarget(); 8696 } else { 8697 if (mPostSystemReadyMessages == null) { 8698 mPostSystemReadyMessages = new ArrayList<>(); 8699 } 8700 mPostSystemReadyMessages.add(msg); 8701 } 8702 } 8703 8704 void startCleaningPackages() { 8705 // reader 8706 synchronized (mPackages) { 8707 if (!isExternalMediaAvailable()) { 8708 return; 8709 } 8710 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8711 return; 8712 } 8713 } 8714 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8715 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8716 IActivityManager am = ActivityManagerNative.getDefault(); 8717 if (am != null) { 8718 try { 8719 am.startService(null, intent, null, UserHandle.USER_OWNER); 8720 } catch (RemoteException e) { 8721 } 8722 } 8723 } 8724 8725 @Override 8726 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8727 int installFlags, String installerPackageName, VerificationParams verificationParams, 8728 String packageAbiOverride) { 8729 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8730 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8731 } 8732 8733 @Override 8734 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8735 int installFlags, String installerPackageName, VerificationParams verificationParams, 8736 String packageAbiOverride, int userId) { 8737 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8738 8739 final int callingUid = Binder.getCallingUid(); 8740 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8741 8742 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8743 try { 8744 if (observer != null) { 8745 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8746 } 8747 } catch (RemoteException re) { 8748 } 8749 return; 8750 } 8751 8752 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8753 installFlags |= PackageManager.INSTALL_FROM_ADB; 8754 8755 } else { 8756 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8757 // about installerPackageName. 8758 8759 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8760 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8761 } 8762 8763 UserHandle user; 8764 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8765 user = UserHandle.ALL; 8766 } else { 8767 user = new UserHandle(userId); 8768 } 8769 8770 // Only system components can circumvent runtime permissions when installing. 8771 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8772 && mContext.checkCallingOrSelfPermission(Manifest.permission 8773 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8774 throw new SecurityException("You need the " 8775 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8776 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8777 } 8778 8779 verificationParams.setInstallerUid(callingUid); 8780 8781 final File originFile = new File(originPath); 8782 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8783 8784 final Message msg = mHandler.obtainMessage(INIT_COPY); 8785 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8786 null, verificationParams, user, packageAbiOverride); 8787 mHandler.sendMessage(msg); 8788 } 8789 8790 void installStage(String packageName, File stagedDir, String stagedCid, 8791 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8792 String installerPackageName, int installerUid, UserHandle user) { 8793 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8794 params.referrerUri, installerUid, null); 8795 8796 final OriginInfo origin; 8797 if (stagedDir != null) { 8798 origin = OriginInfo.fromStagedFile(stagedDir); 8799 } else { 8800 origin = OriginInfo.fromStagedContainer(stagedCid); 8801 } 8802 8803 final Message msg = mHandler.obtainMessage(INIT_COPY); 8804 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8805 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8806 mHandler.sendMessage(msg); 8807 } 8808 8809 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8810 Bundle extras = new Bundle(1); 8811 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8812 8813 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8814 packageName, extras, null, null, new int[] {userId}); 8815 try { 8816 IActivityManager am = ActivityManagerNative.getDefault(); 8817 final boolean isSystem = 8818 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8819 if (isSystem && am.isUserRunning(userId, false)) { 8820 // The just-installed/enabled app is bundled on the system, so presumed 8821 // to be able to run automatically without needing an explicit launch. 8822 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8823 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8824 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8825 .setPackage(packageName); 8826 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8827 android.app.AppOpsManager.OP_NONE, false, false, userId); 8828 } 8829 } catch (RemoteException e) { 8830 // shouldn't happen 8831 Slog.w(TAG, "Unable to bootstrap installed package", e); 8832 } 8833 } 8834 8835 @Override 8836 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8837 int userId) { 8838 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8839 PackageSetting pkgSetting; 8840 final int uid = Binder.getCallingUid(); 8841 enforceCrossUserPermission(uid, userId, true, true, 8842 "setApplicationHiddenSetting for user " + userId); 8843 8844 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8845 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8846 return false; 8847 } 8848 8849 long callingId = Binder.clearCallingIdentity(); 8850 try { 8851 boolean sendAdded = false; 8852 boolean sendRemoved = false; 8853 // writer 8854 synchronized (mPackages) { 8855 pkgSetting = mSettings.mPackages.get(packageName); 8856 if (pkgSetting == null) { 8857 return false; 8858 } 8859 if (pkgSetting.getHidden(userId) != hidden) { 8860 pkgSetting.setHidden(hidden, userId); 8861 mSettings.writePackageRestrictionsLPr(userId); 8862 if (hidden) { 8863 sendRemoved = true; 8864 } else { 8865 sendAdded = true; 8866 } 8867 } 8868 } 8869 if (sendAdded) { 8870 sendPackageAddedForUser(packageName, pkgSetting, userId); 8871 return true; 8872 } 8873 if (sendRemoved) { 8874 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8875 "hiding pkg"); 8876 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8877 } 8878 } finally { 8879 Binder.restoreCallingIdentity(callingId); 8880 } 8881 return false; 8882 } 8883 8884 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8885 int userId) { 8886 final PackageRemovedInfo info = new PackageRemovedInfo(); 8887 info.removedPackage = packageName; 8888 info.removedUsers = new int[] {userId}; 8889 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8890 info.sendBroadcast(false, false, false); 8891 } 8892 8893 /** 8894 * Returns true if application is not found or there was an error. Otherwise it returns 8895 * the hidden state of the package for the given user. 8896 */ 8897 @Override 8898 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8899 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8900 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8901 false, "getApplicationHidden for user " + userId); 8902 PackageSetting pkgSetting; 8903 long callingId = Binder.clearCallingIdentity(); 8904 try { 8905 // writer 8906 synchronized (mPackages) { 8907 pkgSetting = mSettings.mPackages.get(packageName); 8908 if (pkgSetting == null) { 8909 return true; 8910 } 8911 return pkgSetting.getHidden(userId); 8912 } 8913 } finally { 8914 Binder.restoreCallingIdentity(callingId); 8915 } 8916 } 8917 8918 /** 8919 * @hide 8920 */ 8921 @Override 8922 public int installExistingPackageAsUser(String packageName, int userId) { 8923 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8924 null); 8925 PackageSetting pkgSetting; 8926 final int uid = Binder.getCallingUid(); 8927 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8928 + userId); 8929 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8930 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8931 } 8932 8933 long callingId = Binder.clearCallingIdentity(); 8934 try { 8935 boolean sendAdded = false; 8936 8937 // writer 8938 synchronized (mPackages) { 8939 pkgSetting = mSettings.mPackages.get(packageName); 8940 if (pkgSetting == null) { 8941 return PackageManager.INSTALL_FAILED_INVALID_URI; 8942 } 8943 if (!pkgSetting.getInstalled(userId)) { 8944 pkgSetting.setInstalled(true, userId); 8945 pkgSetting.setHidden(false, userId); 8946 mSettings.writePackageRestrictionsLPr(userId); 8947 sendAdded = true; 8948 } 8949 } 8950 8951 if (sendAdded) { 8952 sendPackageAddedForUser(packageName, pkgSetting, userId); 8953 } 8954 } finally { 8955 Binder.restoreCallingIdentity(callingId); 8956 } 8957 8958 return PackageManager.INSTALL_SUCCEEDED; 8959 } 8960 8961 boolean isUserRestricted(int userId, String restrictionKey) { 8962 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8963 if (restrictions.getBoolean(restrictionKey, false)) { 8964 Log.w(TAG, "User is restricted: " + restrictionKey); 8965 return true; 8966 } 8967 return false; 8968 } 8969 8970 @Override 8971 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8972 mContext.enforceCallingOrSelfPermission( 8973 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8974 "Only package verification agents can verify applications"); 8975 8976 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8977 final PackageVerificationResponse response = new PackageVerificationResponse( 8978 verificationCode, Binder.getCallingUid()); 8979 msg.arg1 = id; 8980 msg.obj = response; 8981 mHandler.sendMessage(msg); 8982 } 8983 8984 @Override 8985 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8986 long millisecondsToDelay) { 8987 mContext.enforceCallingOrSelfPermission( 8988 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8989 "Only package verification agents can extend verification timeouts"); 8990 8991 final PackageVerificationState state = mPendingVerification.get(id); 8992 final PackageVerificationResponse response = new PackageVerificationResponse( 8993 verificationCodeAtTimeout, Binder.getCallingUid()); 8994 8995 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8996 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8997 } 8998 if (millisecondsToDelay < 0) { 8999 millisecondsToDelay = 0; 9000 } 9001 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9002 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9003 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9004 } 9005 9006 if ((state != null) && !state.timeoutExtended()) { 9007 state.extendTimeout(); 9008 9009 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9010 msg.arg1 = id; 9011 msg.obj = response; 9012 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9013 } 9014 } 9015 9016 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9017 int verificationCode, UserHandle user) { 9018 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9019 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9020 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9021 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9022 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9023 9024 mContext.sendBroadcastAsUser(intent, user, 9025 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9026 } 9027 9028 private ComponentName matchComponentForVerifier(String packageName, 9029 List<ResolveInfo> receivers) { 9030 ActivityInfo targetReceiver = null; 9031 9032 final int NR = receivers.size(); 9033 for (int i = 0; i < NR; i++) { 9034 final ResolveInfo info = receivers.get(i); 9035 if (info.activityInfo == null) { 9036 continue; 9037 } 9038 9039 if (packageName.equals(info.activityInfo.packageName)) { 9040 targetReceiver = info.activityInfo; 9041 break; 9042 } 9043 } 9044 9045 if (targetReceiver == null) { 9046 return null; 9047 } 9048 9049 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9050 } 9051 9052 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9053 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9054 if (pkgInfo.verifiers.length == 0) { 9055 return null; 9056 } 9057 9058 final int N = pkgInfo.verifiers.length; 9059 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9060 for (int i = 0; i < N; i++) { 9061 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9062 9063 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9064 receivers); 9065 if (comp == null) { 9066 continue; 9067 } 9068 9069 final int verifierUid = getUidForVerifier(verifierInfo); 9070 if (verifierUid == -1) { 9071 continue; 9072 } 9073 9074 if (DEBUG_VERIFY) { 9075 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9076 + " with the correct signature"); 9077 } 9078 sufficientVerifiers.add(comp); 9079 verificationState.addSufficientVerifier(verifierUid); 9080 } 9081 9082 return sufficientVerifiers; 9083 } 9084 9085 private int getUidForVerifier(VerifierInfo verifierInfo) { 9086 synchronized (mPackages) { 9087 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9088 if (pkg == null) { 9089 return -1; 9090 } else if (pkg.mSignatures.length != 1) { 9091 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9092 + " has more than one signature; ignoring"); 9093 return -1; 9094 } 9095 9096 /* 9097 * If the public key of the package's signature does not match 9098 * our expected public key, then this is a different package and 9099 * we should skip. 9100 */ 9101 9102 final byte[] expectedPublicKey; 9103 try { 9104 final Signature verifierSig = pkg.mSignatures[0]; 9105 final PublicKey publicKey = verifierSig.getPublicKey(); 9106 expectedPublicKey = publicKey.getEncoded(); 9107 } catch (CertificateException e) { 9108 return -1; 9109 } 9110 9111 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9112 9113 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9114 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9115 + " does not have the expected public key; ignoring"); 9116 return -1; 9117 } 9118 9119 return pkg.applicationInfo.uid; 9120 } 9121 } 9122 9123 @Override 9124 public void finishPackageInstall(int token) { 9125 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9126 9127 if (DEBUG_INSTALL) { 9128 Slog.v(TAG, "BM finishing package install for " + token); 9129 } 9130 9131 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9132 mHandler.sendMessage(msg); 9133 } 9134 9135 /** 9136 * Get the verification agent timeout. 9137 * 9138 * @return verification timeout in milliseconds 9139 */ 9140 private long getVerificationTimeout() { 9141 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9142 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9143 DEFAULT_VERIFICATION_TIMEOUT); 9144 } 9145 9146 /** 9147 * Get the default verification agent response code. 9148 * 9149 * @return default verification response code 9150 */ 9151 private int getDefaultVerificationResponse() { 9152 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9153 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9154 DEFAULT_VERIFICATION_RESPONSE); 9155 } 9156 9157 /** 9158 * Check whether or not package verification has been enabled. 9159 * 9160 * @return true if verification should be performed 9161 */ 9162 private boolean isVerificationEnabled(int userId, int installFlags) { 9163 if (!DEFAULT_VERIFY_ENABLE) { 9164 return false; 9165 } 9166 9167 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9168 9169 // Check if installing from ADB 9170 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9171 // Do not run verification in a test harness environment 9172 if (ActivityManager.isRunningInTestHarness()) { 9173 return false; 9174 } 9175 if (ensureVerifyAppsEnabled) { 9176 return true; 9177 } 9178 // Check if the developer does not want package verification for ADB installs 9179 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9180 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9181 return false; 9182 } 9183 } 9184 9185 if (ensureVerifyAppsEnabled) { 9186 return true; 9187 } 9188 9189 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9190 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9191 } 9192 9193 @Override 9194 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9195 throws RemoteException { 9196 mContext.enforceCallingOrSelfPermission( 9197 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9198 "Only intentfilter verification agents can verify applications"); 9199 9200 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9201 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9202 Binder.getCallingUid(), verificationCode, failedDomains); 9203 msg.arg1 = id; 9204 msg.obj = response; 9205 mHandler.sendMessage(msg); 9206 } 9207 9208 @Override 9209 public int getIntentVerificationStatus(String packageName, int userId) { 9210 synchronized (mPackages) { 9211 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9212 } 9213 } 9214 9215 @Override 9216 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9217 boolean result = false; 9218 synchronized (mPackages) { 9219 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9220 } 9221 if (result) { 9222 scheduleWritePackageRestrictionsLocked(userId); 9223 } 9224 return result; 9225 } 9226 9227 @Override 9228 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9229 synchronized (mPackages) { 9230 return mSettings.getIntentFilterVerificationsLPr(packageName); 9231 } 9232 } 9233 9234 @Override 9235 public List<IntentFilter> getAllIntentFilters(String packageName) { 9236 if (TextUtils.isEmpty(packageName)) { 9237 return Collections.<IntentFilter>emptyList(); 9238 } 9239 synchronized (mPackages) { 9240 PackageParser.Package pkg = mPackages.get(packageName); 9241 if (pkg == null || pkg.activities == null) { 9242 return Collections.<IntentFilter>emptyList(); 9243 } 9244 final int count = pkg.activities.size(); 9245 ArrayList<IntentFilter> result = new ArrayList<>(); 9246 for (int n=0; n<count; n++) { 9247 PackageParser.Activity activity = pkg.activities.get(n); 9248 if (activity.intents != null || activity.intents.size() > 0) { 9249 result.addAll(activity.intents); 9250 } 9251 } 9252 return result; 9253 } 9254 } 9255 9256 @Override 9257 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9258 synchronized (mPackages) { 9259 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9260 if (packageName != null) { 9261 result |= updateIntentVerificationStatus(packageName, 9262 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9263 UserHandle.myUserId()); 9264 } 9265 return result; 9266 } 9267 } 9268 9269 @Override 9270 public String getDefaultBrowserPackageName(int userId) { 9271 synchronized (mPackages) { 9272 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9273 } 9274 } 9275 9276 /** 9277 * Get the "allow unknown sources" setting. 9278 * 9279 * @return the current "allow unknown sources" setting 9280 */ 9281 private int getUnknownSourcesSettings() { 9282 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9283 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9284 -1); 9285 } 9286 9287 @Override 9288 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9289 final int uid = Binder.getCallingUid(); 9290 // writer 9291 synchronized (mPackages) { 9292 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9293 if (targetPackageSetting == null) { 9294 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9295 } 9296 9297 PackageSetting installerPackageSetting; 9298 if (installerPackageName != null) { 9299 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9300 if (installerPackageSetting == null) { 9301 throw new IllegalArgumentException("Unknown installer package: " 9302 + installerPackageName); 9303 } 9304 } else { 9305 installerPackageSetting = null; 9306 } 9307 9308 Signature[] callerSignature; 9309 Object obj = mSettings.getUserIdLPr(uid); 9310 if (obj != null) { 9311 if (obj instanceof SharedUserSetting) { 9312 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9313 } else if (obj instanceof PackageSetting) { 9314 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9315 } else { 9316 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9317 } 9318 } else { 9319 throw new SecurityException("Unknown calling uid " + uid); 9320 } 9321 9322 // Verify: can't set installerPackageName to a package that is 9323 // not signed with the same cert as the caller. 9324 if (installerPackageSetting != null) { 9325 if (compareSignatures(callerSignature, 9326 installerPackageSetting.signatures.mSignatures) 9327 != PackageManager.SIGNATURE_MATCH) { 9328 throw new SecurityException( 9329 "Caller does not have same cert as new installer package " 9330 + installerPackageName); 9331 } 9332 } 9333 9334 // Verify: if target already has an installer package, it must 9335 // be signed with the same cert as the caller. 9336 if (targetPackageSetting.installerPackageName != null) { 9337 PackageSetting setting = mSettings.mPackages.get( 9338 targetPackageSetting.installerPackageName); 9339 // If the currently set package isn't valid, then it's always 9340 // okay to change it. 9341 if (setting != null) { 9342 if (compareSignatures(callerSignature, 9343 setting.signatures.mSignatures) 9344 != PackageManager.SIGNATURE_MATCH) { 9345 throw new SecurityException( 9346 "Caller does not have same cert as old installer package " 9347 + targetPackageSetting.installerPackageName); 9348 } 9349 } 9350 } 9351 9352 // Okay! 9353 targetPackageSetting.installerPackageName = installerPackageName; 9354 scheduleWriteSettingsLocked(); 9355 } 9356 } 9357 9358 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9359 // Queue up an async operation since the package installation may take a little while. 9360 mHandler.post(new Runnable() { 9361 public void run() { 9362 mHandler.removeCallbacks(this); 9363 // Result object to be returned 9364 PackageInstalledInfo res = new PackageInstalledInfo(); 9365 res.returnCode = currentStatus; 9366 res.uid = -1; 9367 res.pkg = null; 9368 res.removedInfo = new PackageRemovedInfo(); 9369 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9370 args.doPreInstall(res.returnCode); 9371 synchronized (mInstallLock) { 9372 installPackageLI(args, res); 9373 } 9374 args.doPostInstall(res.returnCode, res.uid); 9375 } 9376 9377 // A restore should be performed at this point if (a) the install 9378 // succeeded, (b) the operation is not an update, and (c) the new 9379 // package has not opted out of backup participation. 9380 final boolean update = res.removedInfo.removedPackage != null; 9381 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9382 boolean doRestore = !update 9383 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9384 9385 // Set up the post-install work request bookkeeping. This will be used 9386 // and cleaned up by the post-install event handling regardless of whether 9387 // there's a restore pass performed. Token values are >= 1. 9388 int token; 9389 if (mNextInstallToken < 0) mNextInstallToken = 1; 9390 token = mNextInstallToken++; 9391 9392 PostInstallData data = new PostInstallData(args, res); 9393 mRunningInstalls.put(token, data); 9394 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9395 9396 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9397 // Pass responsibility to the Backup Manager. It will perform a 9398 // restore if appropriate, then pass responsibility back to the 9399 // Package Manager to run the post-install observer callbacks 9400 // and broadcasts. 9401 IBackupManager bm = IBackupManager.Stub.asInterface( 9402 ServiceManager.getService(Context.BACKUP_SERVICE)); 9403 if (bm != null) { 9404 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9405 + " to BM for possible restore"); 9406 try { 9407 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9408 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9409 } else { 9410 doRestore = false; 9411 } 9412 } catch (RemoteException e) { 9413 // can't happen; the backup manager is local 9414 } catch (Exception e) { 9415 Slog.e(TAG, "Exception trying to enqueue restore", e); 9416 doRestore = false; 9417 } 9418 } else { 9419 Slog.e(TAG, "Backup Manager not found!"); 9420 doRestore = false; 9421 } 9422 } 9423 9424 if (!doRestore) { 9425 // No restore possible, or the Backup Manager was mysteriously not 9426 // available -- just fire the post-install work request directly. 9427 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9428 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9429 mHandler.sendMessage(msg); 9430 } 9431 } 9432 }); 9433 } 9434 9435 private abstract class HandlerParams { 9436 private static final int MAX_RETRIES = 4; 9437 9438 /** 9439 * Number of times startCopy() has been attempted and had a non-fatal 9440 * error. 9441 */ 9442 private int mRetries = 0; 9443 9444 /** User handle for the user requesting the information or installation. */ 9445 private final UserHandle mUser; 9446 9447 HandlerParams(UserHandle user) { 9448 mUser = user; 9449 } 9450 9451 UserHandle getUser() { 9452 return mUser; 9453 } 9454 9455 final boolean startCopy() { 9456 boolean res; 9457 try { 9458 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9459 9460 if (++mRetries > MAX_RETRIES) { 9461 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9462 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9463 handleServiceError(); 9464 return false; 9465 } else { 9466 handleStartCopy(); 9467 res = true; 9468 } 9469 } catch (RemoteException e) { 9470 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9471 mHandler.sendEmptyMessage(MCS_RECONNECT); 9472 res = false; 9473 } 9474 handleReturnCode(); 9475 return res; 9476 } 9477 9478 final void serviceError() { 9479 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9480 handleServiceError(); 9481 handleReturnCode(); 9482 } 9483 9484 abstract void handleStartCopy() throws RemoteException; 9485 abstract void handleServiceError(); 9486 abstract void handleReturnCode(); 9487 } 9488 9489 class MeasureParams extends HandlerParams { 9490 private final PackageStats mStats; 9491 private boolean mSuccess; 9492 9493 private final IPackageStatsObserver mObserver; 9494 9495 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9496 super(new UserHandle(stats.userHandle)); 9497 mObserver = observer; 9498 mStats = stats; 9499 } 9500 9501 @Override 9502 public String toString() { 9503 return "MeasureParams{" 9504 + Integer.toHexString(System.identityHashCode(this)) 9505 + " " + mStats.packageName + "}"; 9506 } 9507 9508 @Override 9509 void handleStartCopy() throws RemoteException { 9510 synchronized (mInstallLock) { 9511 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9512 } 9513 9514 if (mSuccess) { 9515 final boolean mounted; 9516 if (Environment.isExternalStorageEmulated()) { 9517 mounted = true; 9518 } else { 9519 final String status = Environment.getExternalStorageState(); 9520 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9521 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9522 } 9523 9524 if (mounted) { 9525 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9526 9527 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9528 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9529 9530 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9531 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9532 9533 // Always subtract cache size, since it's a subdirectory 9534 mStats.externalDataSize -= mStats.externalCacheSize; 9535 9536 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9537 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9538 9539 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9540 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9541 } 9542 } 9543 } 9544 9545 @Override 9546 void handleReturnCode() { 9547 if (mObserver != null) { 9548 try { 9549 mObserver.onGetStatsCompleted(mStats, mSuccess); 9550 } catch (RemoteException e) { 9551 Slog.i(TAG, "Observer no longer exists."); 9552 } 9553 } 9554 } 9555 9556 @Override 9557 void handleServiceError() { 9558 Slog.e(TAG, "Could not measure application " + mStats.packageName 9559 + " external storage"); 9560 } 9561 } 9562 9563 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9564 throws RemoteException { 9565 long result = 0; 9566 for (File path : paths) { 9567 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9568 } 9569 return result; 9570 } 9571 9572 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9573 for (File path : paths) { 9574 try { 9575 mcs.clearDirectory(path.getAbsolutePath()); 9576 } catch (RemoteException e) { 9577 } 9578 } 9579 } 9580 9581 static class OriginInfo { 9582 /** 9583 * Location where install is coming from, before it has been 9584 * copied/renamed into place. This could be a single monolithic APK 9585 * file, or a cluster directory. This location may be untrusted. 9586 */ 9587 final File file; 9588 final String cid; 9589 9590 /** 9591 * Flag indicating that {@link #file} or {@link #cid} has already been 9592 * staged, meaning downstream users don't need to defensively copy the 9593 * contents. 9594 */ 9595 final boolean staged; 9596 9597 /** 9598 * Flag indicating that {@link #file} or {@link #cid} is an already 9599 * installed app that is being moved. 9600 */ 9601 final boolean existing; 9602 9603 final String resolvedPath; 9604 final File resolvedFile; 9605 9606 static OriginInfo fromNothing() { 9607 return new OriginInfo(null, null, false, false); 9608 } 9609 9610 static OriginInfo fromUntrustedFile(File file) { 9611 return new OriginInfo(file, null, false, false); 9612 } 9613 9614 static OriginInfo fromExistingFile(File file) { 9615 return new OriginInfo(file, null, false, true); 9616 } 9617 9618 static OriginInfo fromStagedFile(File file) { 9619 return new OriginInfo(file, null, true, false); 9620 } 9621 9622 static OriginInfo fromStagedContainer(String cid) { 9623 return new OriginInfo(null, cid, true, false); 9624 } 9625 9626 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9627 this.file = file; 9628 this.cid = cid; 9629 this.staged = staged; 9630 this.existing = existing; 9631 9632 if (cid != null) { 9633 resolvedPath = PackageHelper.getSdDir(cid); 9634 resolvedFile = new File(resolvedPath); 9635 } else if (file != null) { 9636 resolvedPath = file.getAbsolutePath(); 9637 resolvedFile = file; 9638 } else { 9639 resolvedPath = null; 9640 resolvedFile = null; 9641 } 9642 } 9643 } 9644 9645 class MoveInfo { 9646 final int moveId; 9647 final String fromUuid; 9648 final String toUuid; 9649 final String packageName; 9650 final String dataAppName; 9651 final int appId; 9652 final String seinfo; 9653 9654 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9655 String dataAppName, int appId, String seinfo) { 9656 this.moveId = moveId; 9657 this.fromUuid = fromUuid; 9658 this.toUuid = toUuid; 9659 this.packageName = packageName; 9660 this.dataAppName = dataAppName; 9661 this.appId = appId; 9662 this.seinfo = seinfo; 9663 } 9664 } 9665 9666 class InstallParams extends HandlerParams { 9667 final OriginInfo origin; 9668 final MoveInfo move; 9669 final IPackageInstallObserver2 observer; 9670 int installFlags; 9671 final String installerPackageName; 9672 final String volumeUuid; 9673 final VerificationParams verificationParams; 9674 private InstallArgs mArgs; 9675 private int mRet; 9676 final String packageAbiOverride; 9677 9678 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9679 int installFlags, String installerPackageName, String volumeUuid, 9680 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9681 super(user); 9682 this.origin = origin; 9683 this.move = move; 9684 this.observer = observer; 9685 this.installFlags = installFlags; 9686 this.installerPackageName = installerPackageName; 9687 this.volumeUuid = volumeUuid; 9688 this.verificationParams = verificationParams; 9689 this.packageAbiOverride = packageAbiOverride; 9690 } 9691 9692 @Override 9693 public String toString() { 9694 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9695 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9696 } 9697 9698 public ManifestDigest getManifestDigest() { 9699 if (verificationParams == null) { 9700 return null; 9701 } 9702 return verificationParams.getManifestDigest(); 9703 } 9704 9705 private int installLocationPolicy(PackageInfoLite pkgLite) { 9706 String packageName = pkgLite.packageName; 9707 int installLocation = pkgLite.installLocation; 9708 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9709 // reader 9710 synchronized (mPackages) { 9711 PackageParser.Package pkg = mPackages.get(packageName); 9712 if (pkg != null) { 9713 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9714 // Check for downgrading. 9715 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9716 try { 9717 checkDowngrade(pkg, pkgLite); 9718 } catch (PackageManagerException e) { 9719 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9720 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9721 } 9722 } 9723 // Check for updated system application. 9724 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9725 if (onSd) { 9726 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9727 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9728 } 9729 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9730 } else { 9731 if (onSd) { 9732 // Install flag overrides everything. 9733 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9734 } 9735 // If current upgrade specifies particular preference 9736 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9737 // Application explicitly specified internal. 9738 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9739 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9740 // App explictly prefers external. Let policy decide 9741 } else { 9742 // Prefer previous location 9743 if (isExternal(pkg)) { 9744 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9745 } 9746 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9747 } 9748 } 9749 } else { 9750 // Invalid install. Return error code 9751 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9752 } 9753 } 9754 } 9755 // All the special cases have been taken care of. 9756 // Return result based on recommended install location. 9757 if (onSd) { 9758 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9759 } 9760 return pkgLite.recommendedInstallLocation; 9761 } 9762 9763 /* 9764 * Invoke remote method to get package information and install 9765 * location values. Override install location based on default 9766 * policy if needed and then create install arguments based 9767 * on the install location. 9768 */ 9769 public void handleStartCopy() throws RemoteException { 9770 int ret = PackageManager.INSTALL_SUCCEEDED; 9771 9772 // If we're already staged, we've firmly committed to an install location 9773 if (origin.staged) { 9774 if (origin.file != null) { 9775 installFlags |= PackageManager.INSTALL_INTERNAL; 9776 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9777 } else if (origin.cid != null) { 9778 installFlags |= PackageManager.INSTALL_EXTERNAL; 9779 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9780 } else { 9781 throw new IllegalStateException("Invalid stage location"); 9782 } 9783 } 9784 9785 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9786 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9787 9788 PackageInfoLite pkgLite = null; 9789 9790 if (onInt && onSd) { 9791 // Check if both bits are set. 9792 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9793 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9794 } else { 9795 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9796 packageAbiOverride); 9797 9798 /* 9799 * If we have too little free space, try to free cache 9800 * before giving up. 9801 */ 9802 if (!origin.staged && pkgLite.recommendedInstallLocation 9803 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9804 // TODO: focus freeing disk space on the target device 9805 final StorageManager storage = StorageManager.from(mContext); 9806 final long lowThreshold = storage.getStorageLowBytes( 9807 Environment.getDataDirectory()); 9808 9809 final long sizeBytes = mContainerService.calculateInstalledSize( 9810 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9811 9812 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9813 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9814 installFlags, packageAbiOverride); 9815 } 9816 9817 /* 9818 * The cache free must have deleted the file we 9819 * downloaded to install. 9820 * 9821 * TODO: fix the "freeCache" call to not delete 9822 * the file we care about. 9823 */ 9824 if (pkgLite.recommendedInstallLocation 9825 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9826 pkgLite.recommendedInstallLocation 9827 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9828 } 9829 } 9830 } 9831 9832 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9833 int loc = pkgLite.recommendedInstallLocation; 9834 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9835 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9836 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9837 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9838 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9839 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9840 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9841 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9842 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9843 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9844 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9845 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9846 } else { 9847 // Override with defaults if needed. 9848 loc = installLocationPolicy(pkgLite); 9849 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9850 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9851 } else if (!onSd && !onInt) { 9852 // Override install location with flags 9853 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9854 // Set the flag to install on external media. 9855 installFlags |= PackageManager.INSTALL_EXTERNAL; 9856 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9857 } else { 9858 // Make sure the flag for installing on external 9859 // media is unset 9860 installFlags |= PackageManager.INSTALL_INTERNAL; 9861 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9862 } 9863 } 9864 } 9865 } 9866 9867 final InstallArgs args = createInstallArgs(this); 9868 mArgs = args; 9869 9870 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9871 /* 9872 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9873 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9874 */ 9875 int userIdentifier = getUser().getIdentifier(); 9876 if (userIdentifier == UserHandle.USER_ALL 9877 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9878 userIdentifier = UserHandle.USER_OWNER; 9879 } 9880 9881 /* 9882 * Determine if we have any installed package verifiers. If we 9883 * do, then we'll defer to them to verify the packages. 9884 */ 9885 final int requiredUid = mRequiredVerifierPackage == null ? -1 9886 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9887 if (!origin.existing && requiredUid != -1 9888 && isVerificationEnabled(userIdentifier, installFlags)) { 9889 final Intent verification = new Intent( 9890 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9891 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9892 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9893 PACKAGE_MIME_TYPE); 9894 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9895 9896 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9897 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9898 0 /* TODO: Which userId? */); 9899 9900 if (DEBUG_VERIFY) { 9901 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9902 + verification.toString() + " with " + pkgLite.verifiers.length 9903 + " optional verifiers"); 9904 } 9905 9906 final int verificationId = mPendingVerificationToken++; 9907 9908 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9909 9910 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9911 installerPackageName); 9912 9913 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9914 installFlags); 9915 9916 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9917 pkgLite.packageName); 9918 9919 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9920 pkgLite.versionCode); 9921 9922 if (verificationParams != null) { 9923 if (verificationParams.getVerificationURI() != null) { 9924 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9925 verificationParams.getVerificationURI()); 9926 } 9927 if (verificationParams.getOriginatingURI() != null) { 9928 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9929 verificationParams.getOriginatingURI()); 9930 } 9931 if (verificationParams.getReferrer() != null) { 9932 verification.putExtra(Intent.EXTRA_REFERRER, 9933 verificationParams.getReferrer()); 9934 } 9935 if (verificationParams.getOriginatingUid() >= 0) { 9936 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9937 verificationParams.getOriginatingUid()); 9938 } 9939 if (verificationParams.getInstallerUid() >= 0) { 9940 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9941 verificationParams.getInstallerUid()); 9942 } 9943 } 9944 9945 final PackageVerificationState verificationState = new PackageVerificationState( 9946 requiredUid, args); 9947 9948 mPendingVerification.append(verificationId, verificationState); 9949 9950 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9951 receivers, verificationState); 9952 9953 /* 9954 * If any sufficient verifiers were listed in the package 9955 * manifest, attempt to ask them. 9956 */ 9957 if (sufficientVerifiers != null) { 9958 final int N = sufficientVerifiers.size(); 9959 if (N == 0) { 9960 Slog.i(TAG, "Additional verifiers required, but none installed."); 9961 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9962 } else { 9963 for (int i = 0; i < N; i++) { 9964 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9965 9966 final Intent sufficientIntent = new Intent(verification); 9967 sufficientIntent.setComponent(verifierComponent); 9968 9969 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9970 } 9971 } 9972 } 9973 9974 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9975 mRequiredVerifierPackage, receivers); 9976 if (ret == PackageManager.INSTALL_SUCCEEDED 9977 && mRequiredVerifierPackage != null) { 9978 /* 9979 * Send the intent to the required verification agent, 9980 * but only start the verification timeout after the 9981 * target BroadcastReceivers have run. 9982 */ 9983 verification.setComponent(requiredVerifierComponent); 9984 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9985 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9986 new BroadcastReceiver() { 9987 @Override 9988 public void onReceive(Context context, Intent intent) { 9989 final Message msg = mHandler 9990 .obtainMessage(CHECK_PENDING_VERIFICATION); 9991 msg.arg1 = verificationId; 9992 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9993 } 9994 }, null, 0, null, null); 9995 9996 /* 9997 * We don't want the copy to proceed until verification 9998 * succeeds, so null out this field. 9999 */ 10000 mArgs = null; 10001 } 10002 } else { 10003 /* 10004 * No package verification is enabled, so immediately start 10005 * the remote call to initiate copy using temporary file. 10006 */ 10007 ret = args.copyApk(mContainerService, true); 10008 } 10009 } 10010 10011 mRet = ret; 10012 } 10013 10014 @Override 10015 void handleReturnCode() { 10016 // If mArgs is null, then MCS couldn't be reached. When it 10017 // reconnects, it will try again to install. At that point, this 10018 // will succeed. 10019 if (mArgs != null) { 10020 processPendingInstall(mArgs, mRet); 10021 } 10022 } 10023 10024 @Override 10025 void handleServiceError() { 10026 mArgs = createInstallArgs(this); 10027 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10028 } 10029 10030 public boolean isForwardLocked() { 10031 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10032 } 10033 } 10034 10035 /** 10036 * Used during creation of InstallArgs 10037 * 10038 * @param installFlags package installation flags 10039 * @return true if should be installed on external storage 10040 */ 10041 private static boolean installOnExternalAsec(int installFlags) { 10042 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10043 return false; 10044 } 10045 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10046 return true; 10047 } 10048 return false; 10049 } 10050 10051 /** 10052 * Used during creation of InstallArgs 10053 * 10054 * @param installFlags package installation flags 10055 * @return true if should be installed as forward locked 10056 */ 10057 private static boolean installForwardLocked(int installFlags) { 10058 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10059 } 10060 10061 private InstallArgs createInstallArgs(InstallParams params) { 10062 if (params.move != null) { 10063 return new MoveInstallArgs(params); 10064 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10065 return new AsecInstallArgs(params); 10066 } else { 10067 return new FileInstallArgs(params); 10068 } 10069 } 10070 10071 /** 10072 * Create args that describe an existing installed package. Typically used 10073 * when cleaning up old installs, or used as a move source. 10074 */ 10075 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10076 String resourcePath, String[] instructionSets) { 10077 final boolean isInAsec; 10078 if (installOnExternalAsec(installFlags)) { 10079 /* Apps on SD card are always in ASEC containers. */ 10080 isInAsec = true; 10081 } else if (installForwardLocked(installFlags) 10082 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10083 /* 10084 * Forward-locked apps are only in ASEC containers if they're the 10085 * new style 10086 */ 10087 isInAsec = true; 10088 } else { 10089 isInAsec = false; 10090 } 10091 10092 if (isInAsec) { 10093 return new AsecInstallArgs(codePath, instructionSets, 10094 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10095 } else { 10096 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10097 } 10098 } 10099 10100 static abstract class InstallArgs { 10101 /** @see InstallParams#origin */ 10102 final OriginInfo origin; 10103 /** @see InstallParams#move */ 10104 final MoveInfo move; 10105 10106 final IPackageInstallObserver2 observer; 10107 // Always refers to PackageManager flags only 10108 final int installFlags; 10109 final String installerPackageName; 10110 final String volumeUuid; 10111 final ManifestDigest manifestDigest; 10112 final UserHandle user; 10113 final String abiOverride; 10114 10115 // The list of instruction sets supported by this app. This is currently 10116 // only used during the rmdex() phase to clean up resources. We can get rid of this 10117 // if we move dex files under the common app path. 10118 /* nullable */ String[] instructionSets; 10119 10120 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10121 int installFlags, String installerPackageName, String volumeUuid, 10122 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10123 String abiOverride) { 10124 this.origin = origin; 10125 this.move = move; 10126 this.installFlags = installFlags; 10127 this.observer = observer; 10128 this.installerPackageName = installerPackageName; 10129 this.volumeUuid = volumeUuid; 10130 this.manifestDigest = manifestDigest; 10131 this.user = user; 10132 this.instructionSets = instructionSets; 10133 this.abiOverride = abiOverride; 10134 } 10135 10136 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10137 abstract int doPreInstall(int status); 10138 10139 /** 10140 * Rename package into final resting place. All paths on the given 10141 * scanned package should be updated to reflect the rename. 10142 */ 10143 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10144 abstract int doPostInstall(int status, int uid); 10145 10146 /** @see PackageSettingBase#codePathString */ 10147 abstract String getCodePath(); 10148 /** @see PackageSettingBase#resourcePathString */ 10149 abstract String getResourcePath(); 10150 10151 // Need installer lock especially for dex file removal. 10152 abstract void cleanUpResourcesLI(); 10153 abstract boolean doPostDeleteLI(boolean delete); 10154 10155 /** 10156 * Called before the source arguments are copied. This is used mostly 10157 * for MoveParams when it needs to read the source file to put it in the 10158 * destination. 10159 */ 10160 int doPreCopy() { 10161 return PackageManager.INSTALL_SUCCEEDED; 10162 } 10163 10164 /** 10165 * Called after the source arguments are copied. This is used mostly for 10166 * MoveParams when it needs to read the source file to put it in the 10167 * destination. 10168 * 10169 * @return 10170 */ 10171 int doPostCopy(int uid) { 10172 return PackageManager.INSTALL_SUCCEEDED; 10173 } 10174 10175 protected boolean isFwdLocked() { 10176 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10177 } 10178 10179 protected boolean isExternalAsec() { 10180 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10181 } 10182 10183 UserHandle getUser() { 10184 return user; 10185 } 10186 } 10187 10188 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10189 if (!allCodePaths.isEmpty()) { 10190 if (instructionSets == null) { 10191 throw new IllegalStateException("instructionSet == null"); 10192 } 10193 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10194 for (String codePath : allCodePaths) { 10195 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10196 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10197 if (retCode < 0) { 10198 Slog.w(TAG, "Couldn't remove dex file for package: " 10199 + " at location " + codePath + ", retcode=" + retCode); 10200 // we don't consider this to be a failure of the core package deletion 10201 } 10202 } 10203 } 10204 } 10205 } 10206 10207 /** 10208 * Logic to handle installation of non-ASEC applications, including copying 10209 * and renaming logic. 10210 */ 10211 class FileInstallArgs extends InstallArgs { 10212 private File codeFile; 10213 private File resourceFile; 10214 10215 // Example topology: 10216 // /data/app/com.example/base.apk 10217 // /data/app/com.example/split_foo.apk 10218 // /data/app/com.example/lib/arm/libfoo.so 10219 // /data/app/com.example/lib/arm64/libfoo.so 10220 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10221 10222 /** New install */ 10223 FileInstallArgs(InstallParams params) { 10224 super(params.origin, params.move, params.observer, params.installFlags, 10225 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10226 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10227 if (isFwdLocked()) { 10228 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10229 } 10230 } 10231 10232 /** Existing install */ 10233 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10234 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10235 null); 10236 this.codeFile = (codePath != null) ? new File(codePath) : null; 10237 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10238 } 10239 10240 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10241 if (origin.staged) { 10242 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10243 codeFile = origin.file; 10244 resourceFile = origin.file; 10245 return PackageManager.INSTALL_SUCCEEDED; 10246 } 10247 10248 try { 10249 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10250 codeFile = tempDir; 10251 resourceFile = tempDir; 10252 } catch (IOException e) { 10253 Slog.w(TAG, "Failed to create copy file: " + e); 10254 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10255 } 10256 10257 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10258 @Override 10259 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10260 if (!FileUtils.isValidExtFilename(name)) { 10261 throw new IllegalArgumentException("Invalid filename: " + name); 10262 } 10263 try { 10264 final File file = new File(codeFile, name); 10265 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10266 O_RDWR | O_CREAT, 0644); 10267 Os.chmod(file.getAbsolutePath(), 0644); 10268 return new ParcelFileDescriptor(fd); 10269 } catch (ErrnoException e) { 10270 throw new RemoteException("Failed to open: " + e.getMessage()); 10271 } 10272 } 10273 }; 10274 10275 int ret = PackageManager.INSTALL_SUCCEEDED; 10276 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10277 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10278 Slog.e(TAG, "Failed to copy package"); 10279 return ret; 10280 } 10281 10282 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10283 NativeLibraryHelper.Handle handle = null; 10284 try { 10285 handle = NativeLibraryHelper.Handle.create(codeFile); 10286 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10287 abiOverride); 10288 } catch (IOException e) { 10289 Slog.e(TAG, "Copying native libraries failed", e); 10290 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10291 } finally { 10292 IoUtils.closeQuietly(handle); 10293 } 10294 10295 return ret; 10296 } 10297 10298 int doPreInstall(int status) { 10299 if (status != PackageManager.INSTALL_SUCCEEDED) { 10300 cleanUp(); 10301 } 10302 return status; 10303 } 10304 10305 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10306 if (status != PackageManager.INSTALL_SUCCEEDED) { 10307 cleanUp(); 10308 return false; 10309 } 10310 10311 final File targetDir = codeFile.getParentFile(); 10312 final File beforeCodeFile = codeFile; 10313 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10314 10315 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10316 try { 10317 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10318 } catch (ErrnoException e) { 10319 Slog.d(TAG, "Failed to rename", e); 10320 return false; 10321 } 10322 10323 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10324 Slog.d(TAG, "Failed to restorecon"); 10325 return false; 10326 } 10327 10328 // Reflect the rename internally 10329 codeFile = afterCodeFile; 10330 resourceFile = afterCodeFile; 10331 10332 // Reflect the rename in scanned details 10333 pkg.codePath = afterCodeFile.getAbsolutePath(); 10334 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10335 pkg.baseCodePath); 10336 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10337 pkg.splitCodePaths); 10338 10339 // Reflect the rename in app info 10340 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10341 pkg.applicationInfo.setCodePath(pkg.codePath); 10342 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10343 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10344 pkg.applicationInfo.setResourcePath(pkg.codePath); 10345 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10346 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10347 10348 return true; 10349 } 10350 10351 int doPostInstall(int status, int uid) { 10352 if (status != PackageManager.INSTALL_SUCCEEDED) { 10353 cleanUp(); 10354 } 10355 return status; 10356 } 10357 10358 @Override 10359 String getCodePath() { 10360 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10361 } 10362 10363 @Override 10364 String getResourcePath() { 10365 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10366 } 10367 10368 private boolean cleanUp() { 10369 if (codeFile == null || !codeFile.exists()) { 10370 return false; 10371 } 10372 10373 if (codeFile.isDirectory()) { 10374 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10375 } else { 10376 codeFile.delete(); 10377 } 10378 10379 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10380 resourceFile.delete(); 10381 } 10382 10383 return true; 10384 } 10385 10386 void cleanUpResourcesLI() { 10387 // Try enumerating all code paths before deleting 10388 List<String> allCodePaths = Collections.EMPTY_LIST; 10389 if (codeFile != null && codeFile.exists()) { 10390 try { 10391 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10392 allCodePaths = pkg.getAllCodePaths(); 10393 } catch (PackageParserException e) { 10394 // Ignored; we tried our best 10395 } 10396 } 10397 10398 cleanUp(); 10399 removeDexFiles(allCodePaths, instructionSets); 10400 } 10401 10402 boolean doPostDeleteLI(boolean delete) { 10403 // XXX err, shouldn't we respect the delete flag? 10404 cleanUpResourcesLI(); 10405 return true; 10406 } 10407 } 10408 10409 private boolean isAsecExternal(String cid) { 10410 final String asecPath = PackageHelper.getSdFilesystem(cid); 10411 return !asecPath.startsWith(mAsecInternalPath); 10412 } 10413 10414 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10415 PackageManagerException { 10416 if (copyRet < 0) { 10417 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10418 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10419 throw new PackageManagerException(copyRet, message); 10420 } 10421 } 10422 } 10423 10424 /** 10425 * Extract the MountService "container ID" from the full code path of an 10426 * .apk. 10427 */ 10428 static String cidFromCodePath(String fullCodePath) { 10429 int eidx = fullCodePath.lastIndexOf("/"); 10430 String subStr1 = fullCodePath.substring(0, eidx); 10431 int sidx = subStr1.lastIndexOf("/"); 10432 return subStr1.substring(sidx+1, eidx); 10433 } 10434 10435 /** 10436 * Logic to handle installation of ASEC applications, including copying and 10437 * renaming logic. 10438 */ 10439 class AsecInstallArgs extends InstallArgs { 10440 static final String RES_FILE_NAME = "pkg.apk"; 10441 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10442 10443 String cid; 10444 String packagePath; 10445 String resourcePath; 10446 10447 /** New install */ 10448 AsecInstallArgs(InstallParams params) { 10449 super(params.origin, params.move, params.observer, params.installFlags, 10450 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10451 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10452 } 10453 10454 /** Existing install */ 10455 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10456 boolean isExternal, boolean isForwardLocked) { 10457 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10458 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10459 instructionSets, null); 10460 // Hackily pretend we're still looking at a full code path 10461 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10462 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10463 } 10464 10465 // Extract cid from fullCodePath 10466 int eidx = fullCodePath.lastIndexOf("/"); 10467 String subStr1 = fullCodePath.substring(0, eidx); 10468 int sidx = subStr1.lastIndexOf("/"); 10469 cid = subStr1.substring(sidx+1, eidx); 10470 setMountPath(subStr1); 10471 } 10472 10473 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10474 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10475 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10476 instructionSets, null); 10477 this.cid = cid; 10478 setMountPath(PackageHelper.getSdDir(cid)); 10479 } 10480 10481 void createCopyFile() { 10482 cid = mInstallerService.allocateExternalStageCidLegacy(); 10483 } 10484 10485 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10486 if (origin.staged) { 10487 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10488 cid = origin.cid; 10489 setMountPath(PackageHelper.getSdDir(cid)); 10490 return PackageManager.INSTALL_SUCCEEDED; 10491 } 10492 10493 if (temp) { 10494 createCopyFile(); 10495 } else { 10496 /* 10497 * Pre-emptively destroy the container since it's destroyed if 10498 * copying fails due to it existing anyway. 10499 */ 10500 PackageHelper.destroySdDir(cid); 10501 } 10502 10503 final String newMountPath = imcs.copyPackageToContainer( 10504 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10505 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10506 10507 if (newMountPath != null) { 10508 setMountPath(newMountPath); 10509 return PackageManager.INSTALL_SUCCEEDED; 10510 } else { 10511 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10512 } 10513 } 10514 10515 @Override 10516 String getCodePath() { 10517 return packagePath; 10518 } 10519 10520 @Override 10521 String getResourcePath() { 10522 return resourcePath; 10523 } 10524 10525 int doPreInstall(int status) { 10526 if (status != PackageManager.INSTALL_SUCCEEDED) { 10527 // Destroy container 10528 PackageHelper.destroySdDir(cid); 10529 } else { 10530 boolean mounted = PackageHelper.isContainerMounted(cid); 10531 if (!mounted) { 10532 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10533 Process.SYSTEM_UID); 10534 if (newMountPath != null) { 10535 setMountPath(newMountPath); 10536 } else { 10537 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10538 } 10539 } 10540 } 10541 return status; 10542 } 10543 10544 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10545 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10546 String newMountPath = null; 10547 if (PackageHelper.isContainerMounted(cid)) { 10548 // Unmount the container 10549 if (!PackageHelper.unMountSdDir(cid)) { 10550 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10551 return false; 10552 } 10553 } 10554 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10555 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10556 " which might be stale. Will try to clean up."); 10557 // Clean up the stale container and proceed to recreate. 10558 if (!PackageHelper.destroySdDir(newCacheId)) { 10559 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10560 return false; 10561 } 10562 // Successfully cleaned up stale container. Try to rename again. 10563 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10564 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10565 + " inspite of cleaning it up."); 10566 return false; 10567 } 10568 } 10569 if (!PackageHelper.isContainerMounted(newCacheId)) { 10570 Slog.w(TAG, "Mounting container " + newCacheId); 10571 newMountPath = PackageHelper.mountSdDir(newCacheId, 10572 getEncryptKey(), Process.SYSTEM_UID); 10573 } else { 10574 newMountPath = PackageHelper.getSdDir(newCacheId); 10575 } 10576 if (newMountPath == null) { 10577 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10578 return false; 10579 } 10580 Log.i(TAG, "Succesfully renamed " + cid + 10581 " to " + newCacheId + 10582 " at new path: " + newMountPath); 10583 cid = newCacheId; 10584 10585 final File beforeCodeFile = new File(packagePath); 10586 setMountPath(newMountPath); 10587 final File afterCodeFile = new File(packagePath); 10588 10589 // Reflect the rename in scanned details 10590 pkg.codePath = afterCodeFile.getAbsolutePath(); 10591 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10592 pkg.baseCodePath); 10593 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10594 pkg.splitCodePaths); 10595 10596 // Reflect the rename in app info 10597 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10598 pkg.applicationInfo.setCodePath(pkg.codePath); 10599 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10600 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10601 pkg.applicationInfo.setResourcePath(pkg.codePath); 10602 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10603 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10604 10605 return true; 10606 } 10607 10608 private void setMountPath(String mountPath) { 10609 final File mountFile = new File(mountPath); 10610 10611 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10612 if (monolithicFile.exists()) { 10613 packagePath = monolithicFile.getAbsolutePath(); 10614 if (isFwdLocked()) { 10615 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10616 } else { 10617 resourcePath = packagePath; 10618 } 10619 } else { 10620 packagePath = mountFile.getAbsolutePath(); 10621 resourcePath = packagePath; 10622 } 10623 } 10624 10625 int doPostInstall(int status, int uid) { 10626 if (status != PackageManager.INSTALL_SUCCEEDED) { 10627 cleanUp(); 10628 } else { 10629 final int groupOwner; 10630 final String protectedFile; 10631 if (isFwdLocked()) { 10632 groupOwner = UserHandle.getSharedAppGid(uid); 10633 protectedFile = RES_FILE_NAME; 10634 } else { 10635 groupOwner = -1; 10636 protectedFile = null; 10637 } 10638 10639 if (uid < Process.FIRST_APPLICATION_UID 10640 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10641 Slog.e(TAG, "Failed to finalize " + cid); 10642 PackageHelper.destroySdDir(cid); 10643 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10644 } 10645 10646 boolean mounted = PackageHelper.isContainerMounted(cid); 10647 if (!mounted) { 10648 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10649 } 10650 } 10651 return status; 10652 } 10653 10654 private void cleanUp() { 10655 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10656 10657 // Destroy secure container 10658 PackageHelper.destroySdDir(cid); 10659 } 10660 10661 private List<String> getAllCodePaths() { 10662 final File codeFile = new File(getCodePath()); 10663 if (codeFile != null && codeFile.exists()) { 10664 try { 10665 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10666 return pkg.getAllCodePaths(); 10667 } catch (PackageParserException e) { 10668 // Ignored; we tried our best 10669 } 10670 } 10671 return Collections.EMPTY_LIST; 10672 } 10673 10674 void cleanUpResourcesLI() { 10675 // Enumerate all code paths before deleting 10676 cleanUpResourcesLI(getAllCodePaths()); 10677 } 10678 10679 private void cleanUpResourcesLI(List<String> allCodePaths) { 10680 cleanUp(); 10681 removeDexFiles(allCodePaths, instructionSets); 10682 } 10683 10684 String getPackageName() { 10685 return getAsecPackageName(cid); 10686 } 10687 10688 boolean doPostDeleteLI(boolean delete) { 10689 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10690 final List<String> allCodePaths = getAllCodePaths(); 10691 boolean mounted = PackageHelper.isContainerMounted(cid); 10692 if (mounted) { 10693 // Unmount first 10694 if (PackageHelper.unMountSdDir(cid)) { 10695 mounted = false; 10696 } 10697 } 10698 if (!mounted && delete) { 10699 cleanUpResourcesLI(allCodePaths); 10700 } 10701 return !mounted; 10702 } 10703 10704 @Override 10705 int doPreCopy() { 10706 if (isFwdLocked()) { 10707 if (!PackageHelper.fixSdPermissions(cid, 10708 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10709 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10710 } 10711 } 10712 10713 return PackageManager.INSTALL_SUCCEEDED; 10714 } 10715 10716 @Override 10717 int doPostCopy(int uid) { 10718 if (isFwdLocked()) { 10719 if (uid < Process.FIRST_APPLICATION_UID 10720 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10721 RES_FILE_NAME)) { 10722 Slog.e(TAG, "Failed to finalize " + cid); 10723 PackageHelper.destroySdDir(cid); 10724 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10725 } 10726 } 10727 10728 return PackageManager.INSTALL_SUCCEEDED; 10729 } 10730 } 10731 10732 /** 10733 * Logic to handle movement of existing installed applications. 10734 */ 10735 class MoveInstallArgs extends InstallArgs { 10736 private File codeFile; 10737 private File resourceFile; 10738 10739 /** New install */ 10740 MoveInstallArgs(InstallParams params) { 10741 super(params.origin, params.move, params.observer, params.installFlags, 10742 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10743 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10744 } 10745 10746 int copyApk(IMediaContainerService imcs, boolean temp) { 10747 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10748 + move.toUuid); 10749 synchronized (mInstaller) { 10750 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10751 move.dataAppName, move.appId, move.seinfo) != 0) { 10752 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10753 } 10754 } 10755 10756 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10757 resourceFile = codeFile; 10758 Slog.d(TAG, "codeFile after move is " + codeFile); 10759 10760 return PackageManager.INSTALL_SUCCEEDED; 10761 } 10762 10763 int doPreInstall(int status) { 10764 if (status != PackageManager.INSTALL_SUCCEEDED) { 10765 cleanUp(); 10766 } 10767 return status; 10768 } 10769 10770 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10771 if (status != PackageManager.INSTALL_SUCCEEDED) { 10772 cleanUp(); 10773 return false; 10774 } 10775 10776 // Reflect the move in app info 10777 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10778 pkg.applicationInfo.setCodePath(pkg.codePath); 10779 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10780 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10781 pkg.applicationInfo.setResourcePath(pkg.codePath); 10782 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10783 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10784 10785 return true; 10786 } 10787 10788 int doPostInstall(int status, int uid) { 10789 if (status != PackageManager.INSTALL_SUCCEEDED) { 10790 cleanUp(); 10791 } 10792 return status; 10793 } 10794 10795 @Override 10796 String getCodePath() { 10797 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10798 } 10799 10800 @Override 10801 String getResourcePath() { 10802 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10803 } 10804 10805 private boolean cleanUp() { 10806 if (codeFile == null || !codeFile.exists()) { 10807 return false; 10808 } 10809 10810 if (codeFile.isDirectory()) { 10811 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10812 } else { 10813 codeFile.delete(); 10814 } 10815 10816 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10817 resourceFile.delete(); 10818 } 10819 10820 return true; 10821 } 10822 10823 void cleanUpResourcesLI() { 10824 cleanUp(); 10825 } 10826 10827 boolean doPostDeleteLI(boolean delete) { 10828 // XXX err, shouldn't we respect the delete flag? 10829 cleanUpResourcesLI(); 10830 return true; 10831 } 10832 } 10833 10834 static String getAsecPackageName(String packageCid) { 10835 int idx = packageCid.lastIndexOf("-"); 10836 if (idx == -1) { 10837 return packageCid; 10838 } 10839 return packageCid.substring(0, idx); 10840 } 10841 10842 // Utility method used to create code paths based on package name and available index. 10843 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10844 String idxStr = ""; 10845 int idx = 1; 10846 // Fall back to default value of idx=1 if prefix is not 10847 // part of oldCodePath 10848 if (oldCodePath != null) { 10849 String subStr = oldCodePath; 10850 // Drop the suffix right away 10851 if (suffix != null && subStr.endsWith(suffix)) { 10852 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10853 } 10854 // If oldCodePath already contains prefix find out the 10855 // ending index to either increment or decrement. 10856 int sidx = subStr.lastIndexOf(prefix); 10857 if (sidx != -1) { 10858 subStr = subStr.substring(sidx + prefix.length()); 10859 if (subStr != null) { 10860 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10861 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10862 } 10863 try { 10864 idx = Integer.parseInt(subStr); 10865 if (idx <= 1) { 10866 idx++; 10867 } else { 10868 idx--; 10869 } 10870 } catch(NumberFormatException e) { 10871 } 10872 } 10873 } 10874 } 10875 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10876 return prefix + idxStr; 10877 } 10878 10879 private File getNextCodePath(File targetDir, String packageName) { 10880 int suffix = 1; 10881 File result; 10882 do { 10883 result = new File(targetDir, packageName + "-" + suffix); 10884 suffix++; 10885 } while (result.exists()); 10886 return result; 10887 } 10888 10889 // Utility method that returns the relative package path with respect 10890 // to the installation directory. Like say for /data/data/com.test-1.apk 10891 // string com.test-1 is returned. 10892 static String deriveCodePathName(String codePath) { 10893 if (codePath == null) { 10894 return null; 10895 } 10896 final File codeFile = new File(codePath); 10897 final String name = codeFile.getName(); 10898 if (codeFile.isDirectory()) { 10899 return name; 10900 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10901 final int lastDot = name.lastIndexOf('.'); 10902 return name.substring(0, lastDot); 10903 } else { 10904 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10905 return null; 10906 } 10907 } 10908 10909 class PackageInstalledInfo { 10910 String name; 10911 int uid; 10912 // The set of users that originally had this package installed. 10913 int[] origUsers; 10914 // The set of users that now have this package installed. 10915 int[] newUsers; 10916 PackageParser.Package pkg; 10917 int returnCode; 10918 String returnMsg; 10919 PackageRemovedInfo removedInfo; 10920 10921 public void setError(int code, String msg) { 10922 returnCode = code; 10923 returnMsg = msg; 10924 Slog.w(TAG, msg); 10925 } 10926 10927 public void setError(String msg, PackageParserException e) { 10928 returnCode = e.error; 10929 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10930 Slog.w(TAG, msg, e); 10931 } 10932 10933 public void setError(String msg, PackageManagerException e) { 10934 returnCode = e.error; 10935 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10936 Slog.w(TAG, msg, e); 10937 } 10938 10939 // In some error cases we want to convey more info back to the observer 10940 String origPackage; 10941 String origPermission; 10942 } 10943 10944 /* 10945 * Install a non-existing package. 10946 */ 10947 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10948 UserHandle user, String installerPackageName, String volumeUuid, 10949 PackageInstalledInfo res) { 10950 // Remember this for later, in case we need to rollback this install 10951 String pkgName = pkg.packageName; 10952 10953 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10954 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10955 UserHandle.USER_OWNER).exists(); 10956 synchronized(mPackages) { 10957 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10958 // A package with the same name is already installed, though 10959 // it has been renamed to an older name. The package we 10960 // are trying to install should be installed as an update to 10961 // the existing one, but that has not been requested, so bail. 10962 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10963 + " without first uninstalling package running as " 10964 + mSettings.mRenamedPackages.get(pkgName)); 10965 return; 10966 } 10967 if (mPackages.containsKey(pkgName)) { 10968 // Don't allow installation over an existing package with the same name. 10969 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10970 + " without first uninstalling."); 10971 return; 10972 } 10973 } 10974 10975 try { 10976 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10977 System.currentTimeMillis(), user); 10978 10979 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10980 // delete the partially installed application. the data directory will have to be 10981 // restored if it was already existing 10982 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10983 // remove package from internal structures. Note that we want deletePackageX to 10984 // delete the package data and cache directories that it created in 10985 // scanPackageLocked, unless those directories existed before we even tried to 10986 // install. 10987 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10988 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10989 res.removedInfo, true); 10990 } 10991 10992 } catch (PackageManagerException e) { 10993 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10994 } 10995 } 10996 10997 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10998 // Upgrade keysets are being used. Determine if new package has a superset of the 10999 // required keys. 11000 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11001 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11002 for (int i = 0; i < upgradeKeySets.length; i++) { 11003 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11004 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11005 return true; 11006 } 11007 } 11008 return false; 11009 } 11010 11011 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11012 UserHandle user, String installerPackageName, String volumeUuid, 11013 PackageInstalledInfo res) { 11014 final PackageParser.Package oldPackage; 11015 final String pkgName = pkg.packageName; 11016 final int[] allUsers; 11017 final boolean[] perUserInstalled; 11018 final boolean weFroze; 11019 11020 // First find the old package info and check signatures 11021 synchronized(mPackages) { 11022 oldPackage = mPackages.get(pkgName); 11023 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11024 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11025 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11026 // default to original signature matching 11027 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11028 != PackageManager.SIGNATURE_MATCH) { 11029 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11030 "New package has a different signature: " + pkgName); 11031 return; 11032 } 11033 } else { 11034 if(!checkUpgradeKeySetLP(ps, pkg)) { 11035 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11036 "New package not signed by keys specified by upgrade-keysets: " 11037 + pkgName); 11038 return; 11039 } 11040 } 11041 11042 // In case of rollback, remember per-user/profile install state 11043 allUsers = sUserManager.getUserIds(); 11044 perUserInstalled = new boolean[allUsers.length]; 11045 for (int i = 0; i < allUsers.length; i++) { 11046 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11047 } 11048 11049 // Mark the app as frozen to prevent launching during the upgrade 11050 // process, and then kill all running instances 11051 if (!ps.frozen) { 11052 ps.frozen = true; 11053 weFroze = true; 11054 } else { 11055 weFroze = false; 11056 } 11057 } 11058 11059 // Now that we're guarded by frozen state, kill app during upgrade 11060 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11061 11062 try { 11063 boolean sysPkg = (isSystemApp(oldPackage)); 11064 if (sysPkg) { 11065 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11066 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11067 } else { 11068 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11069 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11070 } 11071 } finally { 11072 // Regardless of success or failure of upgrade steps above, always 11073 // unfreeze the package if we froze it 11074 if (weFroze) { 11075 unfreezePackage(pkgName); 11076 } 11077 } 11078 } 11079 11080 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11081 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11082 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11083 String volumeUuid, PackageInstalledInfo res) { 11084 String pkgName = deletedPackage.packageName; 11085 boolean deletedPkg = true; 11086 boolean updatedSettings = false; 11087 11088 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11089 + deletedPackage); 11090 long origUpdateTime; 11091 if (pkg.mExtras != null) { 11092 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11093 } else { 11094 origUpdateTime = 0; 11095 } 11096 11097 // First delete the existing package while retaining the data directory 11098 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11099 res.removedInfo, true)) { 11100 // If the existing package wasn't successfully deleted 11101 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11102 deletedPkg = false; 11103 } else { 11104 // Successfully deleted the old package; proceed with replace. 11105 11106 // If deleted package lived in a container, give users a chance to 11107 // relinquish resources before killing. 11108 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11109 if (DEBUG_INSTALL) { 11110 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11111 } 11112 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11113 final ArrayList<String> pkgList = new ArrayList<String>(1); 11114 pkgList.add(deletedPackage.applicationInfo.packageName); 11115 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11116 } 11117 11118 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11119 try { 11120 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11121 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11122 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11123 perUserInstalled, res, user); 11124 updatedSettings = true; 11125 } catch (PackageManagerException e) { 11126 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11127 } 11128 } 11129 11130 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11131 // remove package from internal structures. Note that we want deletePackageX to 11132 // delete the package data and cache directories that it created in 11133 // scanPackageLocked, unless those directories existed before we even tried to 11134 // install. 11135 if(updatedSettings) { 11136 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11137 deletePackageLI( 11138 pkgName, null, true, allUsers, perUserInstalled, 11139 PackageManager.DELETE_KEEP_DATA, 11140 res.removedInfo, true); 11141 } 11142 // Since we failed to install the new package we need to restore the old 11143 // package that we deleted. 11144 if (deletedPkg) { 11145 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11146 File restoreFile = new File(deletedPackage.codePath); 11147 // Parse old package 11148 boolean oldExternal = isExternal(deletedPackage); 11149 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11150 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11151 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11152 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11153 try { 11154 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11155 } catch (PackageManagerException e) { 11156 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11157 + e.getMessage()); 11158 return; 11159 } 11160 // Restore of old package succeeded. Update permissions. 11161 // writer 11162 synchronized (mPackages) { 11163 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11164 UPDATE_PERMISSIONS_ALL); 11165 // can downgrade to reader 11166 mSettings.writeLPr(); 11167 } 11168 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11169 } 11170 } 11171 } 11172 11173 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11174 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11175 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11176 String volumeUuid, PackageInstalledInfo res) { 11177 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11178 + ", old=" + deletedPackage); 11179 boolean disabledSystem = false; 11180 boolean updatedSettings = false; 11181 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11182 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11183 != 0) { 11184 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11185 } 11186 String packageName = deletedPackage.packageName; 11187 if (packageName == null) { 11188 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11189 "Attempt to delete null packageName."); 11190 return; 11191 } 11192 PackageParser.Package oldPkg; 11193 PackageSetting oldPkgSetting; 11194 // reader 11195 synchronized (mPackages) { 11196 oldPkg = mPackages.get(packageName); 11197 oldPkgSetting = mSettings.mPackages.get(packageName); 11198 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11199 (oldPkgSetting == null)) { 11200 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11201 "Couldn't find package:" + packageName + " information"); 11202 return; 11203 } 11204 } 11205 11206 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11207 res.removedInfo.removedPackage = packageName; 11208 // Remove existing system package 11209 removePackageLI(oldPkgSetting, true); 11210 // writer 11211 synchronized (mPackages) { 11212 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11213 if (!disabledSystem && deletedPackage != null) { 11214 // We didn't need to disable the .apk as a current system package, 11215 // which means we are replacing another update that is already 11216 // installed. We need to make sure to delete the older one's .apk. 11217 res.removedInfo.args = createInstallArgsForExisting(0, 11218 deletedPackage.applicationInfo.getCodePath(), 11219 deletedPackage.applicationInfo.getResourcePath(), 11220 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11221 } else { 11222 res.removedInfo.args = null; 11223 } 11224 } 11225 11226 // Successfully disabled the old package. Now proceed with re-installation 11227 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11228 11229 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11230 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11231 11232 PackageParser.Package newPackage = null; 11233 try { 11234 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11235 if (newPackage.mExtras != null) { 11236 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11237 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11238 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11239 11240 // is the update attempting to change shared user? that isn't going to work... 11241 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11242 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11243 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11244 + " to " + newPkgSetting.sharedUser); 11245 updatedSettings = true; 11246 } 11247 } 11248 11249 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11250 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11251 perUserInstalled, res, user); 11252 updatedSettings = true; 11253 } 11254 11255 } catch (PackageManagerException e) { 11256 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11257 } 11258 11259 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11260 // Re installation failed. Restore old information 11261 // Remove new pkg information 11262 if (newPackage != null) { 11263 removeInstalledPackageLI(newPackage, true); 11264 } 11265 // Add back the old system package 11266 try { 11267 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11268 } catch (PackageManagerException e) { 11269 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11270 } 11271 // Restore the old system information in Settings 11272 synchronized (mPackages) { 11273 if (disabledSystem) { 11274 mSettings.enableSystemPackageLPw(packageName); 11275 } 11276 if (updatedSettings) { 11277 mSettings.setInstallerPackageName(packageName, 11278 oldPkgSetting.installerPackageName); 11279 } 11280 mSettings.writeLPr(); 11281 } 11282 } 11283 } 11284 11285 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11286 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11287 UserHandle user) { 11288 String pkgName = newPackage.packageName; 11289 synchronized (mPackages) { 11290 //write settings. the installStatus will be incomplete at this stage. 11291 //note that the new package setting would have already been 11292 //added to mPackages. It hasn't been persisted yet. 11293 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11294 mSettings.writeLPr(); 11295 } 11296 11297 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11298 11299 synchronized (mPackages) { 11300 updatePermissionsLPw(newPackage.packageName, newPackage, 11301 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11302 ? UPDATE_PERMISSIONS_ALL : 0)); 11303 // For system-bundled packages, we assume that installing an upgraded version 11304 // of the package implies that the user actually wants to run that new code, 11305 // so we enable the package. 11306 PackageSetting ps = mSettings.mPackages.get(pkgName); 11307 if (ps != null) { 11308 if (isSystemApp(newPackage)) { 11309 // NB: implicit assumption that system package upgrades apply to all users 11310 if (DEBUG_INSTALL) { 11311 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11312 } 11313 if (res.origUsers != null) { 11314 for (int userHandle : res.origUsers) { 11315 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11316 userHandle, installerPackageName); 11317 } 11318 } 11319 // Also convey the prior install/uninstall state 11320 if (allUsers != null && perUserInstalled != null) { 11321 for (int i = 0; i < allUsers.length; i++) { 11322 if (DEBUG_INSTALL) { 11323 Slog.d(TAG, " user " + allUsers[i] 11324 + " => " + perUserInstalled[i]); 11325 } 11326 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11327 } 11328 // these install state changes will be persisted in the 11329 // upcoming call to mSettings.writeLPr(). 11330 } 11331 } 11332 // It's implied that when a user requests installation, they want the app to be 11333 // installed and enabled. 11334 int userId = user.getIdentifier(); 11335 if (userId != UserHandle.USER_ALL) { 11336 ps.setInstalled(true, userId); 11337 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11338 } 11339 } 11340 res.name = pkgName; 11341 res.uid = newPackage.applicationInfo.uid; 11342 res.pkg = newPackage; 11343 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11344 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11345 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11346 //to update install status 11347 mSettings.writeLPr(); 11348 } 11349 } 11350 11351 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11352 final int installFlags = args.installFlags; 11353 final String installerPackageName = args.installerPackageName; 11354 final String volumeUuid = args.volumeUuid; 11355 final File tmpPackageFile = new File(args.getCodePath()); 11356 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11357 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11358 || (args.volumeUuid != null)); 11359 boolean replace = false; 11360 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11361 // Result object to be returned 11362 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11363 11364 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11365 // Retrieve PackageSettings and parse package 11366 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11367 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11368 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11369 PackageParser pp = new PackageParser(); 11370 pp.setSeparateProcesses(mSeparateProcesses); 11371 pp.setDisplayMetrics(mMetrics); 11372 11373 final PackageParser.Package pkg; 11374 try { 11375 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11376 } catch (PackageParserException e) { 11377 res.setError("Failed parse during installPackageLI", e); 11378 return; 11379 } 11380 11381 // Mark that we have an install time CPU ABI override. 11382 pkg.cpuAbiOverride = args.abiOverride; 11383 11384 String pkgName = res.name = pkg.packageName; 11385 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11386 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11387 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11388 return; 11389 } 11390 } 11391 11392 try { 11393 pp.collectCertificates(pkg, parseFlags); 11394 pp.collectManifestDigest(pkg); 11395 } catch (PackageParserException e) { 11396 res.setError("Failed collect during installPackageLI", e); 11397 return; 11398 } 11399 11400 /* If the installer passed in a manifest digest, compare it now. */ 11401 if (args.manifestDigest != null) { 11402 if (DEBUG_INSTALL) { 11403 final String parsedManifest = pkg.manifestDigest == null ? "null" 11404 : pkg.manifestDigest.toString(); 11405 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11406 + parsedManifest); 11407 } 11408 11409 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11410 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11411 return; 11412 } 11413 } else if (DEBUG_INSTALL) { 11414 final String parsedManifest = pkg.manifestDigest == null 11415 ? "null" : pkg.manifestDigest.toString(); 11416 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11417 } 11418 11419 // Get rid of all references to package scan path via parser. 11420 pp = null; 11421 String oldCodePath = null; 11422 boolean systemApp = false; 11423 synchronized (mPackages) { 11424 // Check if installing already existing package 11425 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11426 String oldName = mSettings.mRenamedPackages.get(pkgName); 11427 if (pkg.mOriginalPackages != null 11428 && pkg.mOriginalPackages.contains(oldName) 11429 && mPackages.containsKey(oldName)) { 11430 // This package is derived from an original package, 11431 // and this device has been updating from that original 11432 // name. We must continue using the original name, so 11433 // rename the new package here. 11434 pkg.setPackageName(oldName); 11435 pkgName = pkg.packageName; 11436 replace = true; 11437 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11438 + oldName + " pkgName=" + pkgName); 11439 } else if (mPackages.containsKey(pkgName)) { 11440 // This package, under its official name, already exists 11441 // on the device; we should replace it. 11442 replace = true; 11443 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11444 } 11445 } 11446 11447 PackageSetting ps = mSettings.mPackages.get(pkgName); 11448 if (ps != null) { 11449 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11450 11451 // Quick sanity check that we're signed correctly if updating; 11452 // we'll check this again later when scanning, but we want to 11453 // bail early here before tripping over redefined permissions. 11454 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11455 try { 11456 verifySignaturesLP(ps, pkg); 11457 } catch (PackageManagerException e) { 11458 res.setError(e.error, e.getMessage()); 11459 return; 11460 } 11461 } else { 11462 if (!checkUpgradeKeySetLP(ps, pkg)) { 11463 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11464 + pkg.packageName + " upgrade keys do not match the " 11465 + "previously installed version"); 11466 return; 11467 } 11468 } 11469 11470 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11471 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11472 systemApp = (ps.pkg.applicationInfo.flags & 11473 ApplicationInfo.FLAG_SYSTEM) != 0; 11474 } 11475 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11476 } 11477 11478 // Check whether the newly-scanned package wants to define an already-defined perm 11479 int N = pkg.permissions.size(); 11480 for (int i = N-1; i >= 0; i--) { 11481 PackageParser.Permission perm = pkg.permissions.get(i); 11482 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11483 if (bp != null) { 11484 // If the defining package is signed with our cert, it's okay. This 11485 // also includes the "updating the same package" case, of course. 11486 // "updating same package" could also involve key-rotation. 11487 final boolean sigsOk; 11488 if (!bp.sourcePackage.equals(pkg.packageName) 11489 || !(bp.packageSetting instanceof PackageSetting) 11490 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11491 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11492 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11493 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11494 } else { 11495 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11496 } 11497 if (!sigsOk) { 11498 // If the owning package is the system itself, we log but allow 11499 // install to proceed; we fail the install on all other permission 11500 // redefinitions. 11501 if (!bp.sourcePackage.equals("android")) { 11502 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11503 + pkg.packageName + " attempting to redeclare permission " 11504 + perm.info.name + " already owned by " + bp.sourcePackage); 11505 res.origPermission = perm.info.name; 11506 res.origPackage = bp.sourcePackage; 11507 return; 11508 } else { 11509 Slog.w(TAG, "Package " + pkg.packageName 11510 + " attempting to redeclare system permission " 11511 + perm.info.name + "; ignoring new declaration"); 11512 pkg.permissions.remove(i); 11513 } 11514 } 11515 } 11516 } 11517 11518 } 11519 11520 if (systemApp && onExternal) { 11521 // Disable updates to system apps on sdcard 11522 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11523 "Cannot install updates to system apps on sdcard"); 11524 return; 11525 } 11526 11527 if (args.move != null) { 11528 // We did an in-place move, so dex is ready to roll 11529 scanFlags |= SCAN_NO_DEX; 11530 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11531 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11532 scanFlags |= SCAN_NO_DEX; 11533 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11534 int result = mPackageDexOptimizer 11535 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11536 false /* defer */, false /* inclDependencies */); 11537 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11538 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11539 return; 11540 } 11541 } 11542 11543 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11544 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11545 return; 11546 } 11547 11548 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11549 11550 if (replace) { 11551 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11552 installerPackageName, volumeUuid, res); 11553 } else { 11554 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11555 args.user, installerPackageName, volumeUuid, res); 11556 } 11557 synchronized (mPackages) { 11558 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11559 if (ps != null) { 11560 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11561 } 11562 } 11563 } 11564 11565 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11566 if (mIntentFilterVerifierComponent == null) { 11567 Slog.d(TAG, "No IntentFilter verification will not be done as " 11568 + "there is no IntentFilterVerifier available!"); 11569 return; 11570 } 11571 11572 final int verifierUid = getPackageUid( 11573 mIntentFilterVerifierComponent.getPackageName(), 11574 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11575 11576 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11577 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11578 msg.obj = pkg; 11579 msg.arg1 = userId; 11580 msg.arg2 = verifierUid; 11581 11582 mHandler.sendMessage(msg); 11583 } 11584 11585 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11586 PackageParser.Package pkg) { 11587 int size = pkg.activities.size(); 11588 if (size == 0) { 11589 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11590 return; 11591 } 11592 11593 final boolean hasDomainURLs = hasDomainURLs(pkg); 11594 if (!hasDomainURLs) { 11595 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11596 return; 11597 } 11598 11599 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11600 + " Activities needs verification ..."); 11601 11602 final int verificationId = mIntentFilterVerificationToken++; 11603 int count = 0; 11604 final String packageName = pkg.packageName; 11605 ArrayList<String> allHosts = new ArrayList<>(); 11606 11607 synchronized (mPackages) { 11608 for (PackageParser.Activity a : pkg.activities) { 11609 for (ActivityIntentInfo filter : a.intents) { 11610 boolean needsFilterVerification = filter.needsVerification(); 11611 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11612 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11613 mIntentFilterVerifier.addOneIntentFilterVerification( 11614 verifierUid, userId, verificationId, filter, packageName); 11615 count++; 11616 } else if (!needsFilterVerification) { 11617 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11618 if (hasValidDomains(filter)) { 11619 ArrayList<String> hosts = filter.getHostsList(); 11620 if (hosts.size() > 0) { 11621 allHosts.addAll(hosts); 11622 } else { 11623 if (allHosts.isEmpty()) { 11624 allHosts.add("*"); 11625 } 11626 } 11627 } 11628 } else { 11629 Slog.d(TAG, "Verification already done for IntentFilter:" 11630 + filter.toString()); 11631 } 11632 } 11633 } 11634 } 11635 11636 if (count > 0) { 11637 mIntentFilterVerifier.startVerifications(userId); 11638 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11639 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11640 } else { 11641 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11642 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11643 packageName, allHosts) != null) { 11644 scheduleWriteSettingsLocked(); 11645 } 11646 } 11647 } 11648 11649 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11650 final ComponentName cn = filter.activity.getComponentName(); 11651 final String packageName = cn.getPackageName(); 11652 11653 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11654 packageName); 11655 if (ivi == null) { 11656 return true; 11657 } 11658 int status = ivi.getStatus(); 11659 switch (status) { 11660 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11661 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11662 return true; 11663 11664 default: 11665 // Nothing to do 11666 return false; 11667 } 11668 } 11669 11670 private static boolean isMultiArch(PackageSetting ps) { 11671 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11672 } 11673 11674 private static boolean isMultiArch(ApplicationInfo info) { 11675 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11676 } 11677 11678 private static boolean isExternal(PackageParser.Package pkg) { 11679 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11680 } 11681 11682 private static boolean isExternal(PackageSetting ps) { 11683 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11684 } 11685 11686 private static boolean isExternal(ApplicationInfo info) { 11687 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11688 } 11689 11690 private static boolean isSystemApp(PackageParser.Package pkg) { 11691 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11692 } 11693 11694 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11695 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11696 } 11697 11698 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11699 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11700 } 11701 11702 private static boolean isSystemApp(PackageSetting ps) { 11703 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11704 } 11705 11706 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11707 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11708 } 11709 11710 private int packageFlagsToInstallFlags(PackageSetting ps) { 11711 int installFlags = 0; 11712 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11713 // This existing package was an external ASEC install when we have 11714 // the external flag without a UUID 11715 installFlags |= PackageManager.INSTALL_EXTERNAL; 11716 } 11717 if (ps.isForwardLocked()) { 11718 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11719 } 11720 return installFlags; 11721 } 11722 11723 private void deleteTempPackageFiles() { 11724 final FilenameFilter filter = new FilenameFilter() { 11725 public boolean accept(File dir, String name) { 11726 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11727 } 11728 }; 11729 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11730 file.delete(); 11731 } 11732 } 11733 11734 @Override 11735 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11736 int flags) { 11737 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11738 flags); 11739 } 11740 11741 @Override 11742 public void deletePackage(final String packageName, 11743 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11744 mContext.enforceCallingOrSelfPermission( 11745 android.Manifest.permission.DELETE_PACKAGES, null); 11746 final int uid = Binder.getCallingUid(); 11747 if (UserHandle.getUserId(uid) != userId) { 11748 mContext.enforceCallingPermission( 11749 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11750 "deletePackage for user " + userId); 11751 } 11752 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11753 try { 11754 observer.onPackageDeleted(packageName, 11755 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11756 } catch (RemoteException re) { 11757 } 11758 return; 11759 } 11760 11761 boolean uninstallBlocked = false; 11762 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11763 int[] users = sUserManager.getUserIds(); 11764 for (int i = 0; i < users.length; ++i) { 11765 if (getBlockUninstallForUser(packageName, users[i])) { 11766 uninstallBlocked = true; 11767 break; 11768 } 11769 } 11770 } else { 11771 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11772 } 11773 if (uninstallBlocked) { 11774 try { 11775 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11776 null); 11777 } catch (RemoteException re) { 11778 } 11779 return; 11780 } 11781 11782 if (DEBUG_REMOVE) { 11783 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11784 } 11785 // Queue up an async operation since the package deletion may take a little while. 11786 mHandler.post(new Runnable() { 11787 public void run() { 11788 mHandler.removeCallbacks(this); 11789 final int returnCode = deletePackageX(packageName, userId, flags); 11790 if (observer != null) { 11791 try { 11792 observer.onPackageDeleted(packageName, returnCode, null); 11793 } catch (RemoteException e) { 11794 Log.i(TAG, "Observer no longer exists."); 11795 } //end catch 11796 } //end if 11797 } //end run 11798 }); 11799 } 11800 11801 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11802 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11803 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11804 try { 11805 if (dpm != null) { 11806 if (dpm.isDeviceOwner(packageName)) { 11807 return true; 11808 } 11809 int[] users; 11810 if (userId == UserHandle.USER_ALL) { 11811 users = sUserManager.getUserIds(); 11812 } else { 11813 users = new int[]{userId}; 11814 } 11815 for (int i = 0; i < users.length; ++i) { 11816 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11817 return true; 11818 } 11819 } 11820 } 11821 } catch (RemoteException e) { 11822 } 11823 return false; 11824 } 11825 11826 /** 11827 * This method is an internal method that could be get invoked either 11828 * to delete an installed package or to clean up a failed installation. 11829 * After deleting an installed package, a broadcast is sent to notify any 11830 * listeners that the package has been installed. For cleaning up a failed 11831 * installation, the broadcast is not necessary since the package's 11832 * installation wouldn't have sent the initial broadcast either 11833 * The key steps in deleting a package are 11834 * deleting the package information in internal structures like mPackages, 11835 * deleting the packages base directories through installd 11836 * updating mSettings to reflect current status 11837 * persisting settings for later use 11838 * sending a broadcast if necessary 11839 */ 11840 private int deletePackageX(String packageName, int userId, int flags) { 11841 final PackageRemovedInfo info = new PackageRemovedInfo(); 11842 final boolean res; 11843 11844 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11845 ? UserHandle.ALL : new UserHandle(userId); 11846 11847 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11848 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11849 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11850 } 11851 11852 boolean removedForAllUsers = false; 11853 boolean systemUpdate = false; 11854 11855 // for the uninstall-updates case and restricted profiles, remember the per- 11856 // userhandle installed state 11857 int[] allUsers; 11858 boolean[] perUserInstalled; 11859 synchronized (mPackages) { 11860 PackageSetting ps = mSettings.mPackages.get(packageName); 11861 allUsers = sUserManager.getUserIds(); 11862 perUserInstalled = new boolean[allUsers.length]; 11863 for (int i = 0; i < allUsers.length; i++) { 11864 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11865 } 11866 } 11867 11868 synchronized (mInstallLock) { 11869 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11870 res = deletePackageLI(packageName, removeForUser, 11871 true, allUsers, perUserInstalled, 11872 flags | REMOVE_CHATTY, info, true); 11873 systemUpdate = info.isRemovedPackageSystemUpdate; 11874 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11875 removedForAllUsers = true; 11876 } 11877 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11878 + " removedForAllUsers=" + removedForAllUsers); 11879 } 11880 11881 if (res) { 11882 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11883 11884 // If the removed package was a system update, the old system package 11885 // was re-enabled; we need to broadcast this information 11886 if (systemUpdate) { 11887 Bundle extras = new Bundle(1); 11888 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11889 ? info.removedAppId : info.uid); 11890 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11891 11892 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11893 extras, null, null, null); 11894 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11895 extras, null, null, null); 11896 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11897 null, packageName, null, null); 11898 } 11899 } 11900 // Force a gc here. 11901 Runtime.getRuntime().gc(); 11902 // Delete the resources here after sending the broadcast to let 11903 // other processes clean up before deleting resources. 11904 if (info.args != null) { 11905 synchronized (mInstallLock) { 11906 info.args.doPostDeleteLI(true); 11907 } 11908 } 11909 11910 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11911 } 11912 11913 class PackageRemovedInfo { 11914 String removedPackage; 11915 int uid = -1; 11916 int removedAppId = -1; 11917 int[] removedUsers = null; 11918 boolean isRemovedPackageSystemUpdate = false; 11919 // Clean up resources deleted packages. 11920 InstallArgs args = null; 11921 11922 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11923 Bundle extras = new Bundle(1); 11924 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11925 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11926 if (replacing) { 11927 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11928 } 11929 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11930 if (removedPackage != null) { 11931 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11932 extras, null, null, removedUsers); 11933 if (fullRemove && !replacing) { 11934 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11935 extras, null, null, removedUsers); 11936 } 11937 } 11938 if (removedAppId >= 0) { 11939 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11940 removedUsers); 11941 } 11942 } 11943 } 11944 11945 /* 11946 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11947 * flag is not set, the data directory is removed as well. 11948 * make sure this flag is set for partially installed apps. If not its meaningless to 11949 * delete a partially installed application. 11950 */ 11951 private void removePackageDataLI(PackageSetting ps, 11952 int[] allUserHandles, boolean[] perUserInstalled, 11953 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11954 String packageName = ps.name; 11955 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11956 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11957 // Retrieve object to delete permissions for shared user later on 11958 final PackageSetting deletedPs; 11959 // reader 11960 synchronized (mPackages) { 11961 deletedPs = mSettings.mPackages.get(packageName); 11962 if (outInfo != null) { 11963 outInfo.removedPackage = packageName; 11964 outInfo.removedUsers = deletedPs != null 11965 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11966 : null; 11967 } 11968 } 11969 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11970 removeDataDirsLI(ps.volumeUuid, packageName); 11971 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11972 } 11973 // writer 11974 synchronized (mPackages) { 11975 if (deletedPs != null) { 11976 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11977 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11978 clearDefaultBrowserIfNeeded(packageName); 11979 if (outInfo != null) { 11980 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11981 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11982 } 11983 updatePermissionsLPw(deletedPs.name, null, 0); 11984 if (deletedPs.sharedUser != null) { 11985 // Remove permissions associated with package. Since runtime 11986 // permissions are per user we have to kill the removed package 11987 // or packages running under the shared user of the removed 11988 // package if revoking the permissions requested only by the removed 11989 // package is successful and this causes a change in gids. 11990 for (int userId : UserManagerService.getInstance().getUserIds()) { 11991 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11992 userId); 11993 if (userIdToKill == UserHandle.USER_ALL 11994 || userIdToKill >= UserHandle.USER_OWNER) { 11995 // If gids changed for this user, kill all affected packages. 11996 mHandler.post(new Runnable() { 11997 @Override 11998 public void run() { 11999 // This has to happen with no lock held. 12000 killSettingPackagesForUser(deletedPs, userIdToKill, 12001 KILL_APP_REASON_GIDS_CHANGED); 12002 } 12003 }); 12004 break; 12005 } 12006 } 12007 } 12008 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12009 } 12010 // make sure to preserve per-user disabled state if this removal was just 12011 // a downgrade of a system app to the factory package 12012 if (allUserHandles != null && perUserInstalled != null) { 12013 if (DEBUG_REMOVE) { 12014 Slog.d(TAG, "Propagating install state across downgrade"); 12015 } 12016 for (int i = 0; i < allUserHandles.length; i++) { 12017 if (DEBUG_REMOVE) { 12018 Slog.d(TAG, " user " + allUserHandles[i] 12019 + " => " + perUserInstalled[i]); 12020 } 12021 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12022 } 12023 } 12024 } 12025 // can downgrade to reader 12026 if (writeSettings) { 12027 // Save settings now 12028 mSettings.writeLPr(); 12029 } 12030 } 12031 if (outInfo != null) { 12032 // A user ID was deleted here. Go through all users and remove it 12033 // from KeyStore. 12034 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12035 } 12036 } 12037 12038 static boolean locationIsPrivileged(File path) { 12039 try { 12040 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12041 .getCanonicalPath(); 12042 return path.getCanonicalPath().startsWith(privilegedAppDir); 12043 } catch (IOException e) { 12044 Slog.e(TAG, "Unable to access code path " + path); 12045 } 12046 return false; 12047 } 12048 12049 /* 12050 * Tries to delete system package. 12051 */ 12052 private boolean deleteSystemPackageLI(PackageSetting newPs, 12053 int[] allUserHandles, boolean[] perUserInstalled, 12054 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12055 final boolean applyUserRestrictions 12056 = (allUserHandles != null) && (perUserInstalled != null); 12057 PackageSetting disabledPs = null; 12058 // Confirm if the system package has been updated 12059 // An updated system app can be deleted. This will also have to restore 12060 // the system pkg from system partition 12061 // reader 12062 synchronized (mPackages) { 12063 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12064 } 12065 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12066 + " disabledPs=" + disabledPs); 12067 if (disabledPs == null) { 12068 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12069 return false; 12070 } else if (DEBUG_REMOVE) { 12071 Slog.d(TAG, "Deleting system pkg from data partition"); 12072 } 12073 if (DEBUG_REMOVE) { 12074 if (applyUserRestrictions) { 12075 Slog.d(TAG, "Remembering install states:"); 12076 for (int i = 0; i < allUserHandles.length; i++) { 12077 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12078 } 12079 } 12080 } 12081 // Delete the updated package 12082 outInfo.isRemovedPackageSystemUpdate = true; 12083 if (disabledPs.versionCode < newPs.versionCode) { 12084 // Delete data for downgrades 12085 flags &= ~PackageManager.DELETE_KEEP_DATA; 12086 } else { 12087 // Preserve data by setting flag 12088 flags |= PackageManager.DELETE_KEEP_DATA; 12089 } 12090 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12091 allUserHandles, perUserInstalled, outInfo, writeSettings); 12092 if (!ret) { 12093 return false; 12094 } 12095 // writer 12096 synchronized (mPackages) { 12097 // Reinstate the old system package 12098 mSettings.enableSystemPackageLPw(newPs.name); 12099 // Remove any native libraries from the upgraded package. 12100 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12101 } 12102 // Install the system package 12103 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12104 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12105 if (locationIsPrivileged(disabledPs.codePath)) { 12106 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12107 } 12108 12109 final PackageParser.Package newPkg; 12110 try { 12111 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12112 } catch (PackageManagerException e) { 12113 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12114 return false; 12115 } 12116 12117 // writer 12118 synchronized (mPackages) { 12119 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12120 updatePermissionsLPw(newPkg.packageName, newPkg, 12121 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12122 if (applyUserRestrictions) { 12123 if (DEBUG_REMOVE) { 12124 Slog.d(TAG, "Propagating install state across reinstall"); 12125 } 12126 for (int i = 0; i < allUserHandles.length; i++) { 12127 if (DEBUG_REMOVE) { 12128 Slog.d(TAG, " user " + allUserHandles[i] 12129 + " => " + perUserInstalled[i]); 12130 } 12131 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12132 } 12133 // Regardless of writeSettings we need to ensure that this restriction 12134 // state propagation is persisted 12135 mSettings.writeAllUsersPackageRestrictionsLPr(); 12136 } 12137 // can downgrade to reader here 12138 if (writeSettings) { 12139 mSettings.writeLPr(); 12140 } 12141 } 12142 return true; 12143 } 12144 12145 private boolean deleteInstalledPackageLI(PackageSetting ps, 12146 boolean deleteCodeAndResources, int flags, 12147 int[] allUserHandles, boolean[] perUserInstalled, 12148 PackageRemovedInfo outInfo, boolean writeSettings) { 12149 if (outInfo != null) { 12150 outInfo.uid = ps.appId; 12151 } 12152 12153 // Delete package data from internal structures and also remove data if flag is set 12154 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12155 12156 // Delete application code and resources 12157 if (deleteCodeAndResources && (outInfo != null)) { 12158 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12159 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12160 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12161 } 12162 return true; 12163 } 12164 12165 @Override 12166 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12167 int userId) { 12168 mContext.enforceCallingOrSelfPermission( 12169 android.Manifest.permission.DELETE_PACKAGES, null); 12170 synchronized (mPackages) { 12171 PackageSetting ps = mSettings.mPackages.get(packageName); 12172 if (ps == null) { 12173 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12174 return false; 12175 } 12176 if (!ps.getInstalled(userId)) { 12177 // Can't block uninstall for an app that is not installed or enabled. 12178 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12179 return false; 12180 } 12181 ps.setBlockUninstall(blockUninstall, userId); 12182 mSettings.writePackageRestrictionsLPr(userId); 12183 } 12184 return true; 12185 } 12186 12187 @Override 12188 public boolean getBlockUninstallForUser(String packageName, int userId) { 12189 synchronized (mPackages) { 12190 PackageSetting ps = mSettings.mPackages.get(packageName); 12191 if (ps == null) { 12192 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12193 return false; 12194 } 12195 return ps.getBlockUninstall(userId); 12196 } 12197 } 12198 12199 /* 12200 * This method handles package deletion in general 12201 */ 12202 private boolean deletePackageLI(String packageName, UserHandle user, 12203 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12204 int flags, PackageRemovedInfo outInfo, 12205 boolean writeSettings) { 12206 if (packageName == null) { 12207 Slog.w(TAG, "Attempt to delete null packageName."); 12208 return false; 12209 } 12210 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12211 PackageSetting ps; 12212 boolean dataOnly = false; 12213 int removeUser = -1; 12214 int appId = -1; 12215 synchronized (mPackages) { 12216 ps = mSettings.mPackages.get(packageName); 12217 if (ps == null) { 12218 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12219 return false; 12220 } 12221 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12222 && user.getIdentifier() != UserHandle.USER_ALL) { 12223 // The caller is asking that the package only be deleted for a single 12224 // user. To do this, we just mark its uninstalled state and delete 12225 // its data. If this is a system app, we only allow this to happen if 12226 // they have set the special DELETE_SYSTEM_APP which requests different 12227 // semantics than normal for uninstalling system apps. 12228 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12229 ps.setUserState(user.getIdentifier(), 12230 COMPONENT_ENABLED_STATE_DEFAULT, 12231 false, //installed 12232 true, //stopped 12233 true, //notLaunched 12234 false, //hidden 12235 null, null, null, 12236 false, // blockUninstall 12237 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12238 if (!isSystemApp(ps)) { 12239 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12240 // Other user still have this package installed, so all 12241 // we need to do is clear this user's data and save that 12242 // it is uninstalled. 12243 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12244 removeUser = user.getIdentifier(); 12245 appId = ps.appId; 12246 scheduleWritePackageRestrictionsLocked(removeUser); 12247 } else { 12248 // We need to set it back to 'installed' so the uninstall 12249 // broadcasts will be sent correctly. 12250 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12251 ps.setInstalled(true, user.getIdentifier()); 12252 } 12253 } else { 12254 // This is a system app, so we assume that the 12255 // other users still have this package installed, so all 12256 // we need to do is clear this user's data and save that 12257 // it is uninstalled. 12258 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12259 removeUser = user.getIdentifier(); 12260 appId = ps.appId; 12261 scheduleWritePackageRestrictionsLocked(removeUser); 12262 } 12263 } 12264 } 12265 12266 if (removeUser >= 0) { 12267 // From above, we determined that we are deleting this only 12268 // for a single user. Continue the work here. 12269 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12270 if (outInfo != null) { 12271 outInfo.removedPackage = packageName; 12272 outInfo.removedAppId = appId; 12273 outInfo.removedUsers = new int[] {removeUser}; 12274 } 12275 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12276 removeKeystoreDataIfNeeded(removeUser, appId); 12277 schedulePackageCleaning(packageName, removeUser, false); 12278 synchronized (mPackages) { 12279 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12280 scheduleWritePackageRestrictionsLocked(removeUser); 12281 } 12282 } 12283 return true; 12284 } 12285 12286 if (dataOnly) { 12287 // Delete application data first 12288 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12289 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12290 return true; 12291 } 12292 12293 boolean ret = false; 12294 if (isSystemApp(ps)) { 12295 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12296 // When an updated system application is deleted we delete the existing resources as well and 12297 // fall back to existing code in system partition 12298 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12299 flags, outInfo, writeSettings); 12300 } else { 12301 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12302 // Kill application pre-emptively especially for apps on sd. 12303 killApplication(packageName, ps.appId, "uninstall pkg"); 12304 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12305 allUserHandles, perUserInstalled, 12306 outInfo, writeSettings); 12307 } 12308 12309 return ret; 12310 } 12311 12312 private final class ClearStorageConnection implements ServiceConnection { 12313 IMediaContainerService mContainerService; 12314 12315 @Override 12316 public void onServiceConnected(ComponentName name, IBinder service) { 12317 synchronized (this) { 12318 mContainerService = IMediaContainerService.Stub.asInterface(service); 12319 notifyAll(); 12320 } 12321 } 12322 12323 @Override 12324 public void onServiceDisconnected(ComponentName name) { 12325 } 12326 } 12327 12328 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12329 final boolean mounted; 12330 if (Environment.isExternalStorageEmulated()) { 12331 mounted = true; 12332 } else { 12333 final String status = Environment.getExternalStorageState(); 12334 12335 mounted = status.equals(Environment.MEDIA_MOUNTED) 12336 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12337 } 12338 12339 if (!mounted) { 12340 return; 12341 } 12342 12343 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12344 int[] users; 12345 if (userId == UserHandle.USER_ALL) { 12346 users = sUserManager.getUserIds(); 12347 } else { 12348 users = new int[] { userId }; 12349 } 12350 final ClearStorageConnection conn = new ClearStorageConnection(); 12351 if (mContext.bindServiceAsUser( 12352 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12353 try { 12354 for (int curUser : users) { 12355 long timeout = SystemClock.uptimeMillis() + 5000; 12356 synchronized (conn) { 12357 long now = SystemClock.uptimeMillis(); 12358 while (conn.mContainerService == null && now < timeout) { 12359 try { 12360 conn.wait(timeout - now); 12361 } catch (InterruptedException e) { 12362 } 12363 } 12364 } 12365 if (conn.mContainerService == null) { 12366 return; 12367 } 12368 12369 final UserEnvironment userEnv = new UserEnvironment(curUser); 12370 clearDirectory(conn.mContainerService, 12371 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12372 if (allData) { 12373 clearDirectory(conn.mContainerService, 12374 userEnv.buildExternalStorageAppDataDirs(packageName)); 12375 clearDirectory(conn.mContainerService, 12376 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12377 } 12378 } 12379 } finally { 12380 mContext.unbindService(conn); 12381 } 12382 } 12383 } 12384 12385 @Override 12386 public void clearApplicationUserData(final String packageName, 12387 final IPackageDataObserver observer, final int userId) { 12388 mContext.enforceCallingOrSelfPermission( 12389 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12390 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12391 // Queue up an async operation since the package deletion may take a little while. 12392 mHandler.post(new Runnable() { 12393 public void run() { 12394 mHandler.removeCallbacks(this); 12395 final boolean succeeded; 12396 synchronized (mInstallLock) { 12397 succeeded = clearApplicationUserDataLI(packageName, userId); 12398 } 12399 clearExternalStorageDataSync(packageName, userId, true); 12400 if (succeeded) { 12401 // invoke DeviceStorageMonitor's update method to clear any notifications 12402 DeviceStorageMonitorInternal 12403 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12404 if (dsm != null) { 12405 dsm.checkMemory(); 12406 } 12407 } 12408 if(observer != null) { 12409 try { 12410 observer.onRemoveCompleted(packageName, succeeded); 12411 } catch (RemoteException e) { 12412 Log.i(TAG, "Observer no longer exists."); 12413 } 12414 } //end if observer 12415 } //end run 12416 }); 12417 } 12418 12419 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12420 if (packageName == null) { 12421 Slog.w(TAG, "Attempt to delete null packageName."); 12422 return false; 12423 } 12424 12425 // Try finding details about the requested package 12426 PackageParser.Package pkg; 12427 synchronized (mPackages) { 12428 pkg = mPackages.get(packageName); 12429 if (pkg == null) { 12430 final PackageSetting ps = mSettings.mPackages.get(packageName); 12431 if (ps != null) { 12432 pkg = ps.pkg; 12433 } 12434 } 12435 } 12436 12437 if (pkg == null) { 12438 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12439 } 12440 12441 // Always delete data directories for package, even if we found no other 12442 // record of app. This helps users recover from UID mismatches without 12443 // resorting to a full data wipe. 12444 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12445 if (retCode < 0) { 12446 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12447 return false; 12448 } 12449 12450 if (pkg == null) { 12451 return false; 12452 } 12453 12454 if (pkg != null && pkg.applicationInfo != null) { 12455 final int appId = pkg.applicationInfo.uid; 12456 removeKeystoreDataIfNeeded(userId, appId); 12457 } 12458 12459 // Create a native library symlink only if we have native libraries 12460 // and if the native libraries are 32 bit libraries. We do not provide 12461 // this symlink for 64 bit libraries. 12462 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12463 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12464 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12465 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12466 nativeLibPath, userId) < 0) { 12467 Slog.w(TAG, "Failed linking native library dir"); 12468 return false; 12469 } 12470 } 12471 12472 return true; 12473 } 12474 12475 /** 12476 * Remove entries from the keystore daemon. Will only remove it if the 12477 * {@code appId} is valid. 12478 */ 12479 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12480 if (appId < 0) { 12481 return; 12482 } 12483 12484 final KeyStore keyStore = KeyStore.getInstance(); 12485 if (keyStore != null) { 12486 if (userId == UserHandle.USER_ALL) { 12487 for (final int individual : sUserManager.getUserIds()) { 12488 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12489 } 12490 } else { 12491 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12492 } 12493 } else { 12494 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12495 } 12496 } 12497 12498 @Override 12499 public void deleteApplicationCacheFiles(final String packageName, 12500 final IPackageDataObserver observer) { 12501 mContext.enforceCallingOrSelfPermission( 12502 android.Manifest.permission.DELETE_CACHE_FILES, null); 12503 // Queue up an async operation since the package deletion may take a little while. 12504 final int userId = UserHandle.getCallingUserId(); 12505 mHandler.post(new Runnable() { 12506 public void run() { 12507 mHandler.removeCallbacks(this); 12508 final boolean succeded; 12509 synchronized (mInstallLock) { 12510 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12511 } 12512 clearExternalStorageDataSync(packageName, userId, false); 12513 if (observer != null) { 12514 try { 12515 observer.onRemoveCompleted(packageName, succeded); 12516 } catch (RemoteException e) { 12517 Log.i(TAG, "Observer no longer exists."); 12518 } 12519 } //end if observer 12520 } //end run 12521 }); 12522 } 12523 12524 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12525 if (packageName == null) { 12526 Slog.w(TAG, "Attempt to delete null packageName."); 12527 return false; 12528 } 12529 PackageParser.Package p; 12530 synchronized (mPackages) { 12531 p = mPackages.get(packageName); 12532 } 12533 if (p == null) { 12534 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12535 return false; 12536 } 12537 final ApplicationInfo applicationInfo = p.applicationInfo; 12538 if (applicationInfo == null) { 12539 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12540 return false; 12541 } 12542 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12543 if (retCode < 0) { 12544 Slog.w(TAG, "Couldn't remove cache files for package: " 12545 + packageName + " u" + userId); 12546 return false; 12547 } 12548 return true; 12549 } 12550 12551 @Override 12552 public void getPackageSizeInfo(final String packageName, int userHandle, 12553 final IPackageStatsObserver observer) { 12554 mContext.enforceCallingOrSelfPermission( 12555 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12556 if (packageName == null) { 12557 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12558 } 12559 12560 PackageStats stats = new PackageStats(packageName, userHandle); 12561 12562 /* 12563 * Queue up an async operation since the package measurement may take a 12564 * little while. 12565 */ 12566 Message msg = mHandler.obtainMessage(INIT_COPY); 12567 msg.obj = new MeasureParams(stats, observer); 12568 mHandler.sendMessage(msg); 12569 } 12570 12571 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12572 PackageStats pStats) { 12573 if (packageName == null) { 12574 Slog.w(TAG, "Attempt to get size of null packageName."); 12575 return false; 12576 } 12577 PackageParser.Package p; 12578 boolean dataOnly = false; 12579 String libDirRoot = null; 12580 String asecPath = null; 12581 PackageSetting ps = null; 12582 synchronized (mPackages) { 12583 p = mPackages.get(packageName); 12584 ps = mSettings.mPackages.get(packageName); 12585 if(p == null) { 12586 dataOnly = true; 12587 if((ps == null) || (ps.pkg == null)) { 12588 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12589 return false; 12590 } 12591 p = ps.pkg; 12592 } 12593 if (ps != null) { 12594 libDirRoot = ps.legacyNativeLibraryPathString; 12595 } 12596 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12597 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12598 if (secureContainerId != null) { 12599 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12600 } 12601 } 12602 } 12603 String publicSrcDir = null; 12604 if(!dataOnly) { 12605 final ApplicationInfo applicationInfo = p.applicationInfo; 12606 if (applicationInfo == null) { 12607 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12608 return false; 12609 } 12610 if (p.isForwardLocked()) { 12611 publicSrcDir = applicationInfo.getBaseResourcePath(); 12612 } 12613 } 12614 // TODO: extend to measure size of split APKs 12615 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12616 // not just the first level. 12617 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12618 // just the primary. 12619 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12620 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12621 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12622 if (res < 0) { 12623 return false; 12624 } 12625 12626 // Fix-up for forward-locked applications in ASEC containers. 12627 if (!isExternal(p)) { 12628 pStats.codeSize += pStats.externalCodeSize; 12629 pStats.externalCodeSize = 0L; 12630 } 12631 12632 return true; 12633 } 12634 12635 12636 @Override 12637 public void addPackageToPreferred(String packageName) { 12638 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12639 } 12640 12641 @Override 12642 public void removePackageFromPreferred(String packageName) { 12643 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12644 } 12645 12646 @Override 12647 public List<PackageInfo> getPreferredPackages(int flags) { 12648 return new ArrayList<PackageInfo>(); 12649 } 12650 12651 private int getUidTargetSdkVersionLockedLPr(int uid) { 12652 Object obj = mSettings.getUserIdLPr(uid); 12653 if (obj instanceof SharedUserSetting) { 12654 final SharedUserSetting sus = (SharedUserSetting) obj; 12655 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12656 final Iterator<PackageSetting> it = sus.packages.iterator(); 12657 while (it.hasNext()) { 12658 final PackageSetting ps = it.next(); 12659 if (ps.pkg != null) { 12660 int v = ps.pkg.applicationInfo.targetSdkVersion; 12661 if (v < vers) vers = v; 12662 } 12663 } 12664 return vers; 12665 } else if (obj instanceof PackageSetting) { 12666 final PackageSetting ps = (PackageSetting) obj; 12667 if (ps.pkg != null) { 12668 return ps.pkg.applicationInfo.targetSdkVersion; 12669 } 12670 } 12671 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12672 } 12673 12674 @Override 12675 public void addPreferredActivity(IntentFilter filter, int match, 12676 ComponentName[] set, ComponentName activity, int userId) { 12677 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12678 "Adding preferred"); 12679 } 12680 12681 private void addPreferredActivityInternal(IntentFilter filter, int match, 12682 ComponentName[] set, ComponentName activity, boolean always, int userId, 12683 String opname) { 12684 // writer 12685 int callingUid = Binder.getCallingUid(); 12686 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12687 if (filter.countActions() == 0) { 12688 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12689 return; 12690 } 12691 synchronized (mPackages) { 12692 if (mContext.checkCallingOrSelfPermission( 12693 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12694 != PackageManager.PERMISSION_GRANTED) { 12695 if (getUidTargetSdkVersionLockedLPr(callingUid) 12696 < Build.VERSION_CODES.FROYO) { 12697 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12698 + callingUid); 12699 return; 12700 } 12701 mContext.enforceCallingOrSelfPermission( 12702 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12703 } 12704 12705 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12706 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12707 + userId + ":"); 12708 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12709 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12710 scheduleWritePackageRestrictionsLocked(userId); 12711 } 12712 } 12713 12714 @Override 12715 public void replacePreferredActivity(IntentFilter filter, int match, 12716 ComponentName[] set, ComponentName activity, int userId) { 12717 if (filter.countActions() != 1) { 12718 throw new IllegalArgumentException( 12719 "replacePreferredActivity expects filter to have only 1 action."); 12720 } 12721 if (filter.countDataAuthorities() != 0 12722 || filter.countDataPaths() != 0 12723 || filter.countDataSchemes() > 1 12724 || filter.countDataTypes() != 0) { 12725 throw new IllegalArgumentException( 12726 "replacePreferredActivity expects filter to have no data authorities, " + 12727 "paths, or types; and at most one scheme."); 12728 } 12729 12730 final int callingUid = Binder.getCallingUid(); 12731 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12732 synchronized (mPackages) { 12733 if (mContext.checkCallingOrSelfPermission( 12734 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12735 != PackageManager.PERMISSION_GRANTED) { 12736 if (getUidTargetSdkVersionLockedLPr(callingUid) 12737 < Build.VERSION_CODES.FROYO) { 12738 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12739 + Binder.getCallingUid()); 12740 return; 12741 } 12742 mContext.enforceCallingOrSelfPermission( 12743 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12744 } 12745 12746 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12747 if (pir != null) { 12748 // Get all of the existing entries that exactly match this filter. 12749 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12750 if (existing != null && existing.size() == 1) { 12751 PreferredActivity cur = existing.get(0); 12752 if (DEBUG_PREFERRED) { 12753 Slog.i(TAG, "Checking replace of preferred:"); 12754 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12755 if (!cur.mPref.mAlways) { 12756 Slog.i(TAG, " -- CUR; not mAlways!"); 12757 } else { 12758 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12759 Slog.i(TAG, " -- CUR: mSet=" 12760 + Arrays.toString(cur.mPref.mSetComponents)); 12761 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12762 Slog.i(TAG, " -- NEW: mMatch=" 12763 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12764 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12765 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12766 } 12767 } 12768 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12769 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12770 && cur.mPref.sameSet(set)) { 12771 // Setting the preferred activity to what it happens to be already 12772 if (DEBUG_PREFERRED) { 12773 Slog.i(TAG, "Replacing with same preferred activity " 12774 + cur.mPref.mShortComponent + " for user " 12775 + userId + ":"); 12776 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12777 } 12778 return; 12779 } 12780 } 12781 12782 if (existing != null) { 12783 if (DEBUG_PREFERRED) { 12784 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12785 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12786 } 12787 for (int i = 0; i < existing.size(); i++) { 12788 PreferredActivity pa = existing.get(i); 12789 if (DEBUG_PREFERRED) { 12790 Slog.i(TAG, "Removing existing preferred activity " 12791 + pa.mPref.mComponent + ":"); 12792 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12793 } 12794 pir.removeFilter(pa); 12795 } 12796 } 12797 } 12798 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12799 "Replacing preferred"); 12800 } 12801 } 12802 12803 @Override 12804 public void clearPackagePreferredActivities(String packageName) { 12805 final int uid = Binder.getCallingUid(); 12806 // writer 12807 synchronized (mPackages) { 12808 PackageParser.Package pkg = mPackages.get(packageName); 12809 if (pkg == null || pkg.applicationInfo.uid != uid) { 12810 if (mContext.checkCallingOrSelfPermission( 12811 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12812 != PackageManager.PERMISSION_GRANTED) { 12813 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12814 < Build.VERSION_CODES.FROYO) { 12815 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12816 + Binder.getCallingUid()); 12817 return; 12818 } 12819 mContext.enforceCallingOrSelfPermission( 12820 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12821 } 12822 } 12823 12824 int user = UserHandle.getCallingUserId(); 12825 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12826 scheduleWritePackageRestrictionsLocked(user); 12827 } 12828 } 12829 } 12830 12831 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12832 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12833 ArrayList<PreferredActivity> removed = null; 12834 boolean changed = false; 12835 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12836 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12837 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12838 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12839 continue; 12840 } 12841 Iterator<PreferredActivity> it = pir.filterIterator(); 12842 while (it.hasNext()) { 12843 PreferredActivity pa = it.next(); 12844 // Mark entry for removal only if it matches the package name 12845 // and the entry is of type "always". 12846 if (packageName == null || 12847 (pa.mPref.mComponent.getPackageName().equals(packageName) 12848 && pa.mPref.mAlways)) { 12849 if (removed == null) { 12850 removed = new ArrayList<PreferredActivity>(); 12851 } 12852 removed.add(pa); 12853 } 12854 } 12855 if (removed != null) { 12856 for (int j=0; j<removed.size(); j++) { 12857 PreferredActivity pa = removed.get(j); 12858 pir.removeFilter(pa); 12859 } 12860 changed = true; 12861 } 12862 } 12863 return changed; 12864 } 12865 12866 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12867 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12868 if (userId == UserHandle.USER_ALL) { 12869 if (mSettings.removeIntentFilterVerificationLPw(packageName, 12870 sUserManager.getUserIds())) { 12871 for (int oneUserId : sUserManager.getUserIds()) { 12872 scheduleWritePackageRestrictionsLocked(oneUserId); 12873 } 12874 } 12875 } else { 12876 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 12877 scheduleWritePackageRestrictionsLocked(userId); 12878 } 12879 } 12880 } 12881 12882 12883 void clearDefaultBrowserIfNeeded(String packageName) { 12884 for (int oneUserId : sUserManager.getUserIds()) { 12885 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 12886 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 12887 if (packageName.equals(defaultBrowserPackageName)) { 12888 setDefaultBrowserPackageName(null, oneUserId); 12889 } 12890 } 12891 } 12892 12893 @Override 12894 public void resetPreferredActivities(int userId) { 12895 /* TODO: Actually use userId. Why is it being passed in? */ 12896 mContext.enforceCallingOrSelfPermission( 12897 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12898 // writer 12899 synchronized (mPackages) { 12900 int user = UserHandle.getCallingUserId(); 12901 clearPackagePreferredActivitiesLPw(null, user); 12902 mSettings.readDefaultPreferredAppsLPw(this, user); 12903 scheduleWritePackageRestrictionsLocked(user); 12904 } 12905 } 12906 12907 @Override 12908 public int getPreferredActivities(List<IntentFilter> outFilters, 12909 List<ComponentName> outActivities, String packageName) { 12910 12911 int num = 0; 12912 final int userId = UserHandle.getCallingUserId(); 12913 // reader 12914 synchronized (mPackages) { 12915 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12916 if (pir != null) { 12917 final Iterator<PreferredActivity> it = pir.filterIterator(); 12918 while (it.hasNext()) { 12919 final PreferredActivity pa = it.next(); 12920 if (packageName == null 12921 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12922 && pa.mPref.mAlways)) { 12923 if (outFilters != null) { 12924 outFilters.add(new IntentFilter(pa)); 12925 } 12926 if (outActivities != null) { 12927 outActivities.add(pa.mPref.mComponent); 12928 } 12929 } 12930 } 12931 } 12932 } 12933 12934 return num; 12935 } 12936 12937 @Override 12938 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12939 int userId) { 12940 int callingUid = Binder.getCallingUid(); 12941 if (callingUid != Process.SYSTEM_UID) { 12942 throw new SecurityException( 12943 "addPersistentPreferredActivity can only be run by the system"); 12944 } 12945 if (filter.countActions() == 0) { 12946 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12947 return; 12948 } 12949 synchronized (mPackages) { 12950 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12951 " :"); 12952 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12953 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12954 new PersistentPreferredActivity(filter, activity)); 12955 scheduleWritePackageRestrictionsLocked(userId); 12956 } 12957 } 12958 12959 @Override 12960 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12961 int callingUid = Binder.getCallingUid(); 12962 if (callingUid != Process.SYSTEM_UID) { 12963 throw new SecurityException( 12964 "clearPackagePersistentPreferredActivities can only be run by the system"); 12965 } 12966 ArrayList<PersistentPreferredActivity> removed = null; 12967 boolean changed = false; 12968 synchronized (mPackages) { 12969 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12970 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12971 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12972 .valueAt(i); 12973 if (userId != thisUserId) { 12974 continue; 12975 } 12976 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12977 while (it.hasNext()) { 12978 PersistentPreferredActivity ppa = it.next(); 12979 // Mark entry for removal only if it matches the package name. 12980 if (ppa.mComponent.getPackageName().equals(packageName)) { 12981 if (removed == null) { 12982 removed = new ArrayList<PersistentPreferredActivity>(); 12983 } 12984 removed.add(ppa); 12985 } 12986 } 12987 if (removed != null) { 12988 for (int j=0; j<removed.size(); j++) { 12989 PersistentPreferredActivity ppa = removed.get(j); 12990 ppir.removeFilter(ppa); 12991 } 12992 changed = true; 12993 } 12994 } 12995 12996 if (changed) { 12997 scheduleWritePackageRestrictionsLocked(userId); 12998 } 12999 } 13000 } 13001 13002 /** 13003 * Non-Binder method, support for the backup/restore mechanism: write the 13004 * full set of preferred activities in its canonical XML format. Returns true 13005 * on success; false otherwise. 13006 */ 13007 @Override 13008 public byte[] getPreferredActivityBackup(int userId) { 13009 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13010 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13011 } 13012 13013 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13014 try { 13015 final XmlSerializer serializer = new FastXmlSerializer(); 13016 serializer.setOutput(dataStream, "utf-8"); 13017 serializer.startDocument(null, true); 13018 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13019 13020 synchronized (mPackages) { 13021 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13022 } 13023 13024 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13025 serializer.endDocument(); 13026 serializer.flush(); 13027 } catch (Exception e) { 13028 if (DEBUG_BACKUP) { 13029 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13030 } 13031 return null; 13032 } 13033 13034 return dataStream.toByteArray(); 13035 } 13036 13037 @Override 13038 public void restorePreferredActivities(byte[] backup, int userId) { 13039 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13040 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13041 } 13042 13043 try { 13044 final XmlPullParser parser = Xml.newPullParser(); 13045 parser.setInput(new ByteArrayInputStream(backup), null); 13046 13047 int type; 13048 while ((type = parser.next()) != XmlPullParser.START_TAG 13049 && type != XmlPullParser.END_DOCUMENT) { 13050 } 13051 if (type != XmlPullParser.START_TAG) { 13052 // oops didn't find a start tag?! 13053 if (DEBUG_BACKUP) { 13054 Slog.e(TAG, "Didn't find start tag during restore"); 13055 } 13056 return; 13057 } 13058 13059 // this is supposed to be TAG_PREFERRED_BACKUP 13060 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13061 if (DEBUG_BACKUP) { 13062 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13063 } 13064 return; 13065 } 13066 13067 // skip interfering stuff, then we're aligned with the backing implementation 13068 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13069 synchronized (mPackages) { 13070 mSettings.readPreferredActivitiesLPw(parser, userId); 13071 } 13072 } catch (Exception e) { 13073 if (DEBUG_BACKUP) { 13074 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13075 } 13076 } 13077 } 13078 13079 @Override 13080 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13081 int sourceUserId, int targetUserId, int flags) { 13082 mContext.enforceCallingOrSelfPermission( 13083 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13084 int callingUid = Binder.getCallingUid(); 13085 enforceOwnerRights(ownerPackage, callingUid); 13086 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13087 if (intentFilter.countActions() == 0) { 13088 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13089 return; 13090 } 13091 synchronized (mPackages) { 13092 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13093 ownerPackage, targetUserId, flags); 13094 CrossProfileIntentResolver resolver = 13095 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13096 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13097 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13098 if (existing != null) { 13099 int size = existing.size(); 13100 for (int i = 0; i < size; i++) { 13101 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13102 return; 13103 } 13104 } 13105 } 13106 resolver.addFilter(newFilter); 13107 scheduleWritePackageRestrictionsLocked(sourceUserId); 13108 } 13109 } 13110 13111 @Override 13112 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13113 mContext.enforceCallingOrSelfPermission( 13114 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13115 int callingUid = Binder.getCallingUid(); 13116 enforceOwnerRights(ownerPackage, callingUid); 13117 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13118 synchronized (mPackages) { 13119 CrossProfileIntentResolver resolver = 13120 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13121 ArraySet<CrossProfileIntentFilter> set = 13122 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13123 for (CrossProfileIntentFilter filter : set) { 13124 if (filter.getOwnerPackage().equals(ownerPackage)) { 13125 resolver.removeFilter(filter); 13126 } 13127 } 13128 scheduleWritePackageRestrictionsLocked(sourceUserId); 13129 } 13130 } 13131 13132 // Enforcing that callingUid is owning pkg on userId 13133 private void enforceOwnerRights(String pkg, int callingUid) { 13134 // The system owns everything. 13135 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13136 return; 13137 } 13138 int callingUserId = UserHandle.getUserId(callingUid); 13139 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13140 if (pi == null) { 13141 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13142 + callingUserId); 13143 } 13144 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13145 throw new SecurityException("Calling uid " + callingUid 13146 + " does not own package " + pkg); 13147 } 13148 } 13149 13150 @Override 13151 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13152 Intent intent = new Intent(Intent.ACTION_MAIN); 13153 intent.addCategory(Intent.CATEGORY_HOME); 13154 13155 final int callingUserId = UserHandle.getCallingUserId(); 13156 List<ResolveInfo> list = queryIntentActivities(intent, null, 13157 PackageManager.GET_META_DATA, callingUserId); 13158 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13159 true, false, false, callingUserId); 13160 13161 allHomeCandidates.clear(); 13162 if (list != null) { 13163 for (ResolveInfo ri : list) { 13164 allHomeCandidates.add(ri); 13165 } 13166 } 13167 return (preferred == null || preferred.activityInfo == null) 13168 ? null 13169 : new ComponentName(preferred.activityInfo.packageName, 13170 preferred.activityInfo.name); 13171 } 13172 13173 @Override 13174 public void setApplicationEnabledSetting(String appPackageName, 13175 int newState, int flags, int userId, String callingPackage) { 13176 if (!sUserManager.exists(userId)) return; 13177 if (callingPackage == null) { 13178 callingPackage = Integer.toString(Binder.getCallingUid()); 13179 } 13180 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13181 } 13182 13183 @Override 13184 public void setComponentEnabledSetting(ComponentName componentName, 13185 int newState, int flags, int userId) { 13186 if (!sUserManager.exists(userId)) return; 13187 setEnabledSetting(componentName.getPackageName(), 13188 componentName.getClassName(), newState, flags, userId, null); 13189 } 13190 13191 private void setEnabledSetting(final String packageName, String className, int newState, 13192 final int flags, int userId, String callingPackage) { 13193 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13194 || newState == COMPONENT_ENABLED_STATE_ENABLED 13195 || newState == COMPONENT_ENABLED_STATE_DISABLED 13196 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13197 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13198 throw new IllegalArgumentException("Invalid new component state: " 13199 + newState); 13200 } 13201 PackageSetting pkgSetting; 13202 final int uid = Binder.getCallingUid(); 13203 final int permission = mContext.checkCallingOrSelfPermission( 13204 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13205 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13206 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13207 boolean sendNow = false; 13208 boolean isApp = (className == null); 13209 String componentName = isApp ? packageName : className; 13210 int packageUid = -1; 13211 ArrayList<String> components; 13212 13213 // writer 13214 synchronized (mPackages) { 13215 pkgSetting = mSettings.mPackages.get(packageName); 13216 if (pkgSetting == null) { 13217 if (className == null) { 13218 throw new IllegalArgumentException( 13219 "Unknown package: " + packageName); 13220 } 13221 throw new IllegalArgumentException( 13222 "Unknown component: " + packageName 13223 + "/" + className); 13224 } 13225 // Allow root and verify that userId is not being specified by a different user 13226 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13227 throw new SecurityException( 13228 "Permission Denial: attempt to change component state from pid=" 13229 + Binder.getCallingPid() 13230 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13231 } 13232 if (className == null) { 13233 // We're dealing with an application/package level state change 13234 if (pkgSetting.getEnabled(userId) == newState) { 13235 // Nothing to do 13236 return; 13237 } 13238 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13239 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13240 // Don't care about who enables an app. 13241 callingPackage = null; 13242 } 13243 pkgSetting.setEnabled(newState, userId, callingPackage); 13244 // pkgSetting.pkg.mSetEnabled = newState; 13245 } else { 13246 // We're dealing with a component level state change 13247 // First, verify that this is a valid class name. 13248 PackageParser.Package pkg = pkgSetting.pkg; 13249 if (pkg == null || !pkg.hasComponentClassName(className)) { 13250 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13251 throw new IllegalArgumentException("Component class " + className 13252 + " does not exist in " + packageName); 13253 } else { 13254 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13255 + className + " does not exist in " + packageName); 13256 } 13257 } 13258 switch (newState) { 13259 case COMPONENT_ENABLED_STATE_ENABLED: 13260 if (!pkgSetting.enableComponentLPw(className, userId)) { 13261 return; 13262 } 13263 break; 13264 case COMPONENT_ENABLED_STATE_DISABLED: 13265 if (!pkgSetting.disableComponentLPw(className, userId)) { 13266 return; 13267 } 13268 break; 13269 case COMPONENT_ENABLED_STATE_DEFAULT: 13270 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13271 return; 13272 } 13273 break; 13274 default: 13275 Slog.e(TAG, "Invalid new component state: " + newState); 13276 return; 13277 } 13278 } 13279 scheduleWritePackageRestrictionsLocked(userId); 13280 components = mPendingBroadcasts.get(userId, packageName); 13281 final boolean newPackage = components == null; 13282 if (newPackage) { 13283 components = new ArrayList<String>(); 13284 } 13285 if (!components.contains(componentName)) { 13286 components.add(componentName); 13287 } 13288 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13289 sendNow = true; 13290 // Purge entry from pending broadcast list if another one exists already 13291 // since we are sending one right away. 13292 mPendingBroadcasts.remove(userId, packageName); 13293 } else { 13294 if (newPackage) { 13295 mPendingBroadcasts.put(userId, packageName, components); 13296 } 13297 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13298 // Schedule a message 13299 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13300 } 13301 } 13302 } 13303 13304 long callingId = Binder.clearCallingIdentity(); 13305 try { 13306 if (sendNow) { 13307 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13308 sendPackageChangedBroadcast(packageName, 13309 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13310 } 13311 } finally { 13312 Binder.restoreCallingIdentity(callingId); 13313 } 13314 } 13315 13316 private void sendPackageChangedBroadcast(String packageName, 13317 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13318 if (DEBUG_INSTALL) 13319 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13320 + componentNames); 13321 Bundle extras = new Bundle(4); 13322 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13323 String nameList[] = new String[componentNames.size()]; 13324 componentNames.toArray(nameList); 13325 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13326 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13327 extras.putInt(Intent.EXTRA_UID, packageUid); 13328 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13329 new int[] {UserHandle.getUserId(packageUid)}); 13330 } 13331 13332 @Override 13333 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13334 if (!sUserManager.exists(userId)) return; 13335 final int uid = Binder.getCallingUid(); 13336 final int permission = mContext.checkCallingOrSelfPermission( 13337 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13338 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13339 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13340 // writer 13341 synchronized (mPackages) { 13342 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13343 allowedByPermission, uid, userId)) { 13344 scheduleWritePackageRestrictionsLocked(userId); 13345 } 13346 } 13347 } 13348 13349 @Override 13350 public String getInstallerPackageName(String packageName) { 13351 // reader 13352 synchronized (mPackages) { 13353 return mSettings.getInstallerPackageNameLPr(packageName); 13354 } 13355 } 13356 13357 @Override 13358 public int getApplicationEnabledSetting(String packageName, int userId) { 13359 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13360 int uid = Binder.getCallingUid(); 13361 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13362 // reader 13363 synchronized (mPackages) { 13364 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13365 } 13366 } 13367 13368 @Override 13369 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13370 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13371 int uid = Binder.getCallingUid(); 13372 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13373 // reader 13374 synchronized (mPackages) { 13375 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13376 } 13377 } 13378 13379 @Override 13380 public void enterSafeMode() { 13381 enforceSystemOrRoot("Only the system can request entering safe mode"); 13382 13383 if (!mSystemReady) { 13384 mSafeMode = true; 13385 } 13386 } 13387 13388 @Override 13389 public void systemReady() { 13390 mSystemReady = true; 13391 13392 // Read the compatibilty setting when the system is ready. 13393 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13394 mContext.getContentResolver(), 13395 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13396 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13397 if (DEBUG_SETTINGS) { 13398 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13399 } 13400 13401 synchronized (mPackages) { 13402 // Verify that all of the preferred activity components actually 13403 // exist. It is possible for applications to be updated and at 13404 // that point remove a previously declared activity component that 13405 // had been set as a preferred activity. We try to clean this up 13406 // the next time we encounter that preferred activity, but it is 13407 // possible for the user flow to never be able to return to that 13408 // situation so here we do a sanity check to make sure we haven't 13409 // left any junk around. 13410 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13411 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13412 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13413 removed.clear(); 13414 for (PreferredActivity pa : pir.filterSet()) { 13415 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13416 removed.add(pa); 13417 } 13418 } 13419 if (removed.size() > 0) { 13420 for (int r=0; r<removed.size(); r++) { 13421 PreferredActivity pa = removed.get(r); 13422 Slog.w(TAG, "Removing dangling preferred activity: " 13423 + pa.mPref.mComponent); 13424 pir.removeFilter(pa); 13425 } 13426 mSettings.writePackageRestrictionsLPr( 13427 mSettings.mPreferredActivities.keyAt(i)); 13428 } 13429 } 13430 } 13431 sUserManager.systemReady(); 13432 13433 // Kick off any messages waiting for system ready 13434 if (mPostSystemReadyMessages != null) { 13435 for (Message msg : mPostSystemReadyMessages) { 13436 msg.sendToTarget(); 13437 } 13438 mPostSystemReadyMessages = null; 13439 } 13440 13441 // Watch for external volumes that come and go over time 13442 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13443 storage.registerListener(mStorageListener); 13444 13445 mInstallerService.systemReady(); 13446 } 13447 13448 @Override 13449 public boolean isSafeMode() { 13450 return mSafeMode; 13451 } 13452 13453 @Override 13454 public boolean hasSystemUidErrors() { 13455 return mHasSystemUidErrors; 13456 } 13457 13458 static String arrayToString(int[] array) { 13459 StringBuffer buf = new StringBuffer(128); 13460 buf.append('['); 13461 if (array != null) { 13462 for (int i=0; i<array.length; i++) { 13463 if (i > 0) buf.append(", "); 13464 buf.append(array[i]); 13465 } 13466 } 13467 buf.append(']'); 13468 return buf.toString(); 13469 } 13470 13471 static class DumpState { 13472 public static final int DUMP_LIBS = 1 << 0; 13473 public static final int DUMP_FEATURES = 1 << 1; 13474 public static final int DUMP_RESOLVERS = 1 << 2; 13475 public static final int DUMP_PERMISSIONS = 1 << 3; 13476 public static final int DUMP_PACKAGES = 1 << 4; 13477 public static final int DUMP_SHARED_USERS = 1 << 5; 13478 public static final int DUMP_MESSAGES = 1 << 6; 13479 public static final int DUMP_PROVIDERS = 1 << 7; 13480 public static final int DUMP_VERIFIERS = 1 << 8; 13481 public static final int DUMP_PREFERRED = 1 << 9; 13482 public static final int DUMP_PREFERRED_XML = 1 << 10; 13483 public static final int DUMP_KEYSETS = 1 << 11; 13484 public static final int DUMP_VERSION = 1 << 12; 13485 public static final int DUMP_INSTALLS = 1 << 13; 13486 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13487 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13488 13489 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13490 13491 private int mTypes; 13492 13493 private int mOptions; 13494 13495 private boolean mTitlePrinted; 13496 13497 private SharedUserSetting mSharedUser; 13498 13499 public boolean isDumping(int type) { 13500 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13501 return true; 13502 } 13503 13504 return (mTypes & type) != 0; 13505 } 13506 13507 public void setDump(int type) { 13508 mTypes |= type; 13509 } 13510 13511 public boolean isOptionEnabled(int option) { 13512 return (mOptions & option) != 0; 13513 } 13514 13515 public void setOptionEnabled(int option) { 13516 mOptions |= option; 13517 } 13518 13519 public boolean onTitlePrinted() { 13520 final boolean printed = mTitlePrinted; 13521 mTitlePrinted = true; 13522 return printed; 13523 } 13524 13525 public boolean getTitlePrinted() { 13526 return mTitlePrinted; 13527 } 13528 13529 public void setTitlePrinted(boolean enabled) { 13530 mTitlePrinted = enabled; 13531 } 13532 13533 public SharedUserSetting getSharedUser() { 13534 return mSharedUser; 13535 } 13536 13537 public void setSharedUser(SharedUserSetting user) { 13538 mSharedUser = user; 13539 } 13540 } 13541 13542 @Override 13543 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13544 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13545 != PackageManager.PERMISSION_GRANTED) { 13546 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13547 + Binder.getCallingPid() 13548 + ", uid=" + Binder.getCallingUid() 13549 + " without permission " 13550 + android.Manifest.permission.DUMP); 13551 return; 13552 } 13553 13554 DumpState dumpState = new DumpState(); 13555 boolean fullPreferred = false; 13556 boolean checkin = false; 13557 13558 String packageName = null; 13559 13560 int opti = 0; 13561 while (opti < args.length) { 13562 String opt = args[opti]; 13563 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13564 break; 13565 } 13566 opti++; 13567 13568 if ("-a".equals(opt)) { 13569 // Right now we only know how to print all. 13570 } else if ("-h".equals(opt)) { 13571 pw.println("Package manager dump options:"); 13572 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13573 pw.println(" --checkin: dump for a checkin"); 13574 pw.println(" -f: print details of intent filters"); 13575 pw.println(" -h: print this help"); 13576 pw.println(" cmd may be one of:"); 13577 pw.println(" l[ibraries]: list known shared libraries"); 13578 pw.println(" f[ibraries]: list device features"); 13579 pw.println(" k[eysets]: print known keysets"); 13580 pw.println(" r[esolvers]: dump intent resolvers"); 13581 pw.println(" perm[issions]: dump permissions"); 13582 pw.println(" pref[erred]: print preferred package settings"); 13583 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13584 pw.println(" prov[iders]: dump content providers"); 13585 pw.println(" p[ackages]: dump installed packages"); 13586 pw.println(" s[hared-users]: dump shared user IDs"); 13587 pw.println(" m[essages]: print collected runtime messages"); 13588 pw.println(" v[erifiers]: print package verifier info"); 13589 pw.println(" version: print database version info"); 13590 pw.println(" write: write current settings now"); 13591 pw.println(" <package.name>: info about given package"); 13592 pw.println(" installs: details about install sessions"); 13593 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13594 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13595 return; 13596 } else if ("--checkin".equals(opt)) { 13597 checkin = true; 13598 } else if ("-f".equals(opt)) { 13599 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13600 } else { 13601 pw.println("Unknown argument: " + opt + "; use -h for help"); 13602 } 13603 } 13604 13605 // Is the caller requesting to dump a particular piece of data? 13606 if (opti < args.length) { 13607 String cmd = args[opti]; 13608 opti++; 13609 // Is this a package name? 13610 if ("android".equals(cmd) || cmd.contains(".")) { 13611 packageName = cmd; 13612 // When dumping a single package, we always dump all of its 13613 // filter information since the amount of data will be reasonable. 13614 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13615 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13616 dumpState.setDump(DumpState.DUMP_LIBS); 13617 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13618 dumpState.setDump(DumpState.DUMP_FEATURES); 13619 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13620 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13621 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13622 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13623 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13624 dumpState.setDump(DumpState.DUMP_PREFERRED); 13625 } else if ("preferred-xml".equals(cmd)) { 13626 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13627 if (opti < args.length && "--full".equals(args[opti])) { 13628 fullPreferred = true; 13629 opti++; 13630 } 13631 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13632 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13633 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13634 dumpState.setDump(DumpState.DUMP_PACKAGES); 13635 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13636 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13637 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13638 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13639 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13640 dumpState.setDump(DumpState.DUMP_MESSAGES); 13641 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13642 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13643 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13644 || "intent-filter-verifiers".equals(cmd)) { 13645 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13646 } else if ("version".equals(cmd)) { 13647 dumpState.setDump(DumpState.DUMP_VERSION); 13648 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13649 dumpState.setDump(DumpState.DUMP_KEYSETS); 13650 } else if ("installs".equals(cmd)) { 13651 dumpState.setDump(DumpState.DUMP_INSTALLS); 13652 } else if ("write".equals(cmd)) { 13653 synchronized (mPackages) { 13654 mSettings.writeLPr(); 13655 pw.println("Settings written."); 13656 return; 13657 } 13658 } 13659 } 13660 13661 if (checkin) { 13662 pw.println("vers,1"); 13663 } 13664 13665 // reader 13666 synchronized (mPackages) { 13667 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13668 if (!checkin) { 13669 if (dumpState.onTitlePrinted()) 13670 pw.println(); 13671 pw.println("Database versions:"); 13672 pw.print(" SDK Version:"); 13673 pw.print(" internal="); 13674 pw.print(mSettings.mInternalSdkPlatform); 13675 pw.print(" external="); 13676 pw.println(mSettings.mExternalSdkPlatform); 13677 pw.print(" DB Version:"); 13678 pw.print(" internal="); 13679 pw.print(mSettings.mInternalDatabaseVersion); 13680 pw.print(" external="); 13681 pw.println(mSettings.mExternalDatabaseVersion); 13682 } 13683 } 13684 13685 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13686 if (!checkin) { 13687 if (dumpState.onTitlePrinted()) 13688 pw.println(); 13689 pw.println("Verifiers:"); 13690 pw.print(" Required: "); 13691 pw.print(mRequiredVerifierPackage); 13692 pw.print(" (uid="); 13693 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13694 pw.println(")"); 13695 } else if (mRequiredVerifierPackage != null) { 13696 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13697 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13698 } 13699 } 13700 13701 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13702 packageName == null) { 13703 if (mIntentFilterVerifierComponent != null) { 13704 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13705 if (!checkin) { 13706 if (dumpState.onTitlePrinted()) 13707 pw.println(); 13708 pw.println("Intent Filter Verifier:"); 13709 pw.print(" Using: "); 13710 pw.print(verifierPackageName); 13711 pw.print(" (uid="); 13712 pw.print(getPackageUid(verifierPackageName, 0)); 13713 pw.println(")"); 13714 } else if (verifierPackageName != null) { 13715 pw.print("ifv,"); pw.print(verifierPackageName); 13716 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13717 } 13718 } else { 13719 pw.println(); 13720 pw.println("No Intent Filter Verifier available!"); 13721 } 13722 } 13723 13724 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13725 boolean printedHeader = false; 13726 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13727 while (it.hasNext()) { 13728 String name = it.next(); 13729 SharedLibraryEntry ent = mSharedLibraries.get(name); 13730 if (!checkin) { 13731 if (!printedHeader) { 13732 if (dumpState.onTitlePrinted()) 13733 pw.println(); 13734 pw.println("Libraries:"); 13735 printedHeader = true; 13736 } 13737 pw.print(" "); 13738 } else { 13739 pw.print("lib,"); 13740 } 13741 pw.print(name); 13742 if (!checkin) { 13743 pw.print(" -> "); 13744 } 13745 if (ent.path != null) { 13746 if (!checkin) { 13747 pw.print("(jar) "); 13748 pw.print(ent.path); 13749 } else { 13750 pw.print(",jar,"); 13751 pw.print(ent.path); 13752 } 13753 } else { 13754 if (!checkin) { 13755 pw.print("(apk) "); 13756 pw.print(ent.apk); 13757 } else { 13758 pw.print(",apk,"); 13759 pw.print(ent.apk); 13760 } 13761 } 13762 pw.println(); 13763 } 13764 } 13765 13766 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13767 if (dumpState.onTitlePrinted()) 13768 pw.println(); 13769 if (!checkin) { 13770 pw.println("Features:"); 13771 } 13772 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13773 while (it.hasNext()) { 13774 String name = it.next(); 13775 if (!checkin) { 13776 pw.print(" "); 13777 } else { 13778 pw.print("feat,"); 13779 } 13780 pw.println(name); 13781 } 13782 } 13783 13784 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13785 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13786 : "Activity Resolver Table:", " ", packageName, 13787 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13788 dumpState.setTitlePrinted(true); 13789 } 13790 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13791 : "Receiver Resolver Table:", " ", packageName, 13792 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13793 dumpState.setTitlePrinted(true); 13794 } 13795 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13796 : "Service Resolver Table:", " ", packageName, 13797 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13798 dumpState.setTitlePrinted(true); 13799 } 13800 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13801 : "Provider Resolver Table:", " ", packageName, 13802 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13803 dumpState.setTitlePrinted(true); 13804 } 13805 } 13806 13807 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13808 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13809 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13810 int user = mSettings.mPreferredActivities.keyAt(i); 13811 if (pir.dump(pw, 13812 dumpState.getTitlePrinted() 13813 ? "\nPreferred Activities User " + user + ":" 13814 : "Preferred Activities User " + user + ":", " ", 13815 packageName, true, false)) { 13816 dumpState.setTitlePrinted(true); 13817 } 13818 } 13819 } 13820 13821 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13822 pw.flush(); 13823 FileOutputStream fout = new FileOutputStream(fd); 13824 BufferedOutputStream str = new BufferedOutputStream(fout); 13825 XmlSerializer serializer = new FastXmlSerializer(); 13826 try { 13827 serializer.setOutput(str, "utf-8"); 13828 serializer.startDocument(null, true); 13829 serializer.setFeature( 13830 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13831 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13832 serializer.endDocument(); 13833 serializer.flush(); 13834 } catch (IllegalArgumentException e) { 13835 pw.println("Failed writing: " + e); 13836 } catch (IllegalStateException e) { 13837 pw.println("Failed writing: " + e); 13838 } catch (IOException e) { 13839 pw.println("Failed writing: " + e); 13840 } 13841 } 13842 13843 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13844 pw.println(); 13845 int count = mSettings.mPackages.size(); 13846 if (count == 0) { 13847 pw.println("No domain preferred apps!"); 13848 pw.println(); 13849 } else { 13850 final String prefix = " "; 13851 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13852 if (allPackageSettings.size() == 0) { 13853 pw.println("No domain preferred apps!"); 13854 pw.println(); 13855 } else { 13856 pw.println("Domain preferred apps status:"); 13857 pw.println(); 13858 count = 0; 13859 for (PackageSetting ps : allPackageSettings) { 13860 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13861 if (ivi == null || ivi.getPackageName() == null) continue; 13862 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13863 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13864 pw.println(prefix + "Status: " + ivi.getStatusString()); 13865 pw.println(); 13866 count++; 13867 } 13868 if (count == 0) { 13869 pw.println(prefix + "No domain preferred app status!"); 13870 pw.println(); 13871 } 13872 for (int userId : sUserManager.getUserIds()) { 13873 pw.println("Domain preferred apps for User " + userId + ":"); 13874 pw.println(); 13875 count = 0; 13876 for (PackageSetting ps : allPackageSettings) { 13877 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13878 if (ivi == null || ivi.getPackageName() == null) { 13879 continue; 13880 } 13881 final int status = ps.getDomainVerificationStatusForUser(userId); 13882 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13883 continue; 13884 } 13885 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13886 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13887 String statusStr = IntentFilterVerificationInfo. 13888 getStatusStringFromValue(status); 13889 pw.println(prefix + "Status: " + statusStr); 13890 pw.println(); 13891 count++; 13892 } 13893 if (count == 0) { 13894 pw.println(prefix + "No domain preferred apps!"); 13895 pw.println(); 13896 } 13897 } 13898 } 13899 } 13900 } 13901 13902 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13903 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13904 if (packageName == null) { 13905 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13906 if (iperm == 0) { 13907 if (dumpState.onTitlePrinted()) 13908 pw.println(); 13909 pw.println("AppOp Permissions:"); 13910 } 13911 pw.print(" AppOp Permission "); 13912 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13913 pw.println(":"); 13914 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13915 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13916 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13917 } 13918 } 13919 } 13920 } 13921 13922 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13923 boolean printedSomething = false; 13924 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13925 if (packageName != null && !packageName.equals(p.info.packageName)) { 13926 continue; 13927 } 13928 if (!printedSomething) { 13929 if (dumpState.onTitlePrinted()) 13930 pw.println(); 13931 pw.println("Registered ContentProviders:"); 13932 printedSomething = true; 13933 } 13934 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13935 pw.print(" "); pw.println(p.toString()); 13936 } 13937 printedSomething = false; 13938 for (Map.Entry<String, PackageParser.Provider> entry : 13939 mProvidersByAuthority.entrySet()) { 13940 PackageParser.Provider p = entry.getValue(); 13941 if (packageName != null && !packageName.equals(p.info.packageName)) { 13942 continue; 13943 } 13944 if (!printedSomething) { 13945 if (dumpState.onTitlePrinted()) 13946 pw.println(); 13947 pw.println("ContentProvider Authorities:"); 13948 printedSomething = true; 13949 } 13950 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13951 pw.print(" "); pw.println(p.toString()); 13952 if (p.info != null && p.info.applicationInfo != null) { 13953 final String appInfo = p.info.applicationInfo.toString(); 13954 pw.print(" applicationInfo="); pw.println(appInfo); 13955 } 13956 } 13957 } 13958 13959 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13960 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13961 } 13962 13963 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13964 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13965 } 13966 13967 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13968 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13969 } 13970 13971 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13972 // XXX should handle packageName != null by dumping only install data that 13973 // the given package is involved with. 13974 if (dumpState.onTitlePrinted()) pw.println(); 13975 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13976 } 13977 13978 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13979 if (dumpState.onTitlePrinted()) pw.println(); 13980 mSettings.dumpReadMessagesLPr(pw, dumpState); 13981 13982 pw.println(); 13983 pw.println("Package warning messages:"); 13984 BufferedReader in = null; 13985 String line = null; 13986 try { 13987 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13988 while ((line = in.readLine()) != null) { 13989 if (line.contains("ignored: updated version")) continue; 13990 pw.println(line); 13991 } 13992 } catch (IOException ignored) { 13993 } finally { 13994 IoUtils.closeQuietly(in); 13995 } 13996 } 13997 13998 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13999 BufferedReader in = null; 14000 String line = null; 14001 try { 14002 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14003 while ((line = in.readLine()) != null) { 14004 if (line.contains("ignored: updated version")) continue; 14005 pw.print("msg,"); 14006 pw.println(line); 14007 } 14008 } catch (IOException ignored) { 14009 } finally { 14010 IoUtils.closeQuietly(in); 14011 } 14012 } 14013 } 14014 } 14015 14016 // ------- apps on sdcard specific code ------- 14017 static final boolean DEBUG_SD_INSTALL = false; 14018 14019 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14020 14021 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14022 14023 private boolean mMediaMounted = false; 14024 14025 static String getEncryptKey() { 14026 try { 14027 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14028 SD_ENCRYPTION_KEYSTORE_NAME); 14029 if (sdEncKey == null) { 14030 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14031 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14032 if (sdEncKey == null) { 14033 Slog.e(TAG, "Failed to create encryption keys"); 14034 return null; 14035 } 14036 } 14037 return sdEncKey; 14038 } catch (NoSuchAlgorithmException nsae) { 14039 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14040 return null; 14041 } catch (IOException ioe) { 14042 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14043 return null; 14044 } 14045 } 14046 14047 /* 14048 * Update media status on PackageManager. 14049 */ 14050 @Override 14051 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14052 int callingUid = Binder.getCallingUid(); 14053 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14054 throw new SecurityException("Media status can only be updated by the system"); 14055 } 14056 // reader; this apparently protects mMediaMounted, but should probably 14057 // be a different lock in that case. 14058 synchronized (mPackages) { 14059 Log.i(TAG, "Updating external media status from " 14060 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14061 + (mediaStatus ? "mounted" : "unmounted")); 14062 if (DEBUG_SD_INSTALL) 14063 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14064 + ", mMediaMounted=" + mMediaMounted); 14065 if (mediaStatus == mMediaMounted) { 14066 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14067 : 0, -1); 14068 mHandler.sendMessage(msg); 14069 return; 14070 } 14071 mMediaMounted = mediaStatus; 14072 } 14073 // Queue up an async operation since the package installation may take a 14074 // little while. 14075 mHandler.post(new Runnable() { 14076 public void run() { 14077 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14078 } 14079 }); 14080 } 14081 14082 /** 14083 * Called by MountService when the initial ASECs to scan are available. 14084 * Should block until all the ASEC containers are finished being scanned. 14085 */ 14086 public void scanAvailableAsecs() { 14087 updateExternalMediaStatusInner(true, false, false); 14088 if (mShouldRestoreconData) { 14089 SELinuxMMAC.setRestoreconDone(); 14090 mShouldRestoreconData = false; 14091 } 14092 } 14093 14094 /* 14095 * Collect information of applications on external media, map them against 14096 * existing containers and update information based on current mount status. 14097 * Please note that we always have to report status if reportStatus has been 14098 * set to true especially when unloading packages. 14099 */ 14100 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14101 boolean externalStorage) { 14102 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14103 int[] uidArr = EmptyArray.INT; 14104 14105 final String[] list = PackageHelper.getSecureContainerList(); 14106 if (ArrayUtils.isEmpty(list)) { 14107 Log.i(TAG, "No secure containers found"); 14108 } else { 14109 // Process list of secure containers and categorize them 14110 // as active or stale based on their package internal state. 14111 14112 // reader 14113 synchronized (mPackages) { 14114 for (String cid : list) { 14115 // Leave stages untouched for now; installer service owns them 14116 if (PackageInstallerService.isStageName(cid)) continue; 14117 14118 if (DEBUG_SD_INSTALL) 14119 Log.i(TAG, "Processing container " + cid); 14120 String pkgName = getAsecPackageName(cid); 14121 if (pkgName == null) { 14122 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14123 continue; 14124 } 14125 if (DEBUG_SD_INSTALL) 14126 Log.i(TAG, "Looking for pkg : " + pkgName); 14127 14128 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14129 if (ps == null) { 14130 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14131 continue; 14132 } 14133 14134 /* 14135 * Skip packages that are not external if we're unmounting 14136 * external storage. 14137 */ 14138 if (externalStorage && !isMounted && !isExternal(ps)) { 14139 continue; 14140 } 14141 14142 final AsecInstallArgs args = new AsecInstallArgs(cid, 14143 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14144 // The package status is changed only if the code path 14145 // matches between settings and the container id. 14146 if (ps.codePathString != null 14147 && ps.codePathString.startsWith(args.getCodePath())) { 14148 if (DEBUG_SD_INSTALL) { 14149 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14150 + " at code path: " + ps.codePathString); 14151 } 14152 14153 // We do have a valid package installed on sdcard 14154 processCids.put(args, ps.codePathString); 14155 final int uid = ps.appId; 14156 if (uid != -1) { 14157 uidArr = ArrayUtils.appendInt(uidArr, uid); 14158 } 14159 } else { 14160 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14161 + ps.codePathString); 14162 } 14163 } 14164 } 14165 14166 Arrays.sort(uidArr); 14167 } 14168 14169 // Process packages with valid entries. 14170 if (isMounted) { 14171 if (DEBUG_SD_INSTALL) 14172 Log.i(TAG, "Loading packages"); 14173 loadMediaPackages(processCids, uidArr); 14174 startCleaningPackages(); 14175 mInstallerService.onSecureContainersAvailable(); 14176 } else { 14177 if (DEBUG_SD_INSTALL) 14178 Log.i(TAG, "Unloading packages"); 14179 unloadMediaPackages(processCids, uidArr, reportStatus); 14180 } 14181 } 14182 14183 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14184 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14185 final int size = infos.size(); 14186 final String[] packageNames = new String[size]; 14187 final int[] packageUids = new int[size]; 14188 for (int i = 0; i < size; i++) { 14189 final ApplicationInfo info = infos.get(i); 14190 packageNames[i] = info.packageName; 14191 packageUids[i] = info.uid; 14192 } 14193 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14194 finishedReceiver); 14195 } 14196 14197 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14198 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14199 sendResourcesChangedBroadcast(mediaStatus, replacing, 14200 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14201 } 14202 14203 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14204 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14205 int size = pkgList.length; 14206 if (size > 0) { 14207 // Send broadcasts here 14208 Bundle extras = new Bundle(); 14209 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14210 if (uidArr != null) { 14211 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14212 } 14213 if (replacing) { 14214 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14215 } 14216 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14217 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14218 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14219 } 14220 } 14221 14222 /* 14223 * Look at potentially valid container ids from processCids If package 14224 * information doesn't match the one on record or package scanning fails, 14225 * the cid is added to list of removeCids. We currently don't delete stale 14226 * containers. 14227 */ 14228 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14229 ArrayList<String> pkgList = new ArrayList<String>(); 14230 Set<AsecInstallArgs> keys = processCids.keySet(); 14231 14232 for (AsecInstallArgs args : keys) { 14233 String codePath = processCids.get(args); 14234 if (DEBUG_SD_INSTALL) 14235 Log.i(TAG, "Loading container : " + args.cid); 14236 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14237 try { 14238 // Make sure there are no container errors first. 14239 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14240 Slog.e(TAG, "Failed to mount cid : " + args.cid 14241 + " when installing from sdcard"); 14242 continue; 14243 } 14244 // Check code path here. 14245 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14246 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14247 + " does not match one in settings " + codePath); 14248 continue; 14249 } 14250 // Parse package 14251 int parseFlags = mDefParseFlags; 14252 if (args.isExternalAsec()) { 14253 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14254 } 14255 if (args.isFwdLocked()) { 14256 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14257 } 14258 14259 synchronized (mInstallLock) { 14260 PackageParser.Package pkg = null; 14261 try { 14262 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14263 } catch (PackageManagerException e) { 14264 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14265 } 14266 // Scan the package 14267 if (pkg != null) { 14268 /* 14269 * TODO why is the lock being held? doPostInstall is 14270 * called in other places without the lock. This needs 14271 * to be straightened out. 14272 */ 14273 // writer 14274 synchronized (mPackages) { 14275 retCode = PackageManager.INSTALL_SUCCEEDED; 14276 pkgList.add(pkg.packageName); 14277 // Post process args 14278 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14279 pkg.applicationInfo.uid); 14280 } 14281 } else { 14282 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14283 } 14284 } 14285 14286 } finally { 14287 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14288 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14289 } 14290 } 14291 } 14292 // writer 14293 synchronized (mPackages) { 14294 // If the platform SDK has changed since the last time we booted, 14295 // we need to re-grant app permission to catch any new ones that 14296 // appear. This is really a hack, and means that apps can in some 14297 // cases get permissions that the user didn't initially explicitly 14298 // allow... it would be nice to have some better way to handle 14299 // this situation. 14300 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14301 if (regrantPermissions) 14302 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14303 + mSdkVersion + "; regranting permissions for external storage"); 14304 mSettings.mExternalSdkPlatform = mSdkVersion; 14305 14306 // Make sure group IDs have been assigned, and any permission 14307 // changes in other apps are accounted for 14308 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14309 | (regrantPermissions 14310 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14311 : 0)); 14312 14313 mSettings.updateExternalDatabaseVersion(); 14314 14315 // can downgrade to reader 14316 // Persist settings 14317 mSettings.writeLPr(); 14318 } 14319 // Send a broadcast to let everyone know we are done processing 14320 if (pkgList.size() > 0) { 14321 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14322 } 14323 } 14324 14325 /* 14326 * Utility method to unload a list of specified containers 14327 */ 14328 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14329 // Just unmount all valid containers. 14330 for (AsecInstallArgs arg : cidArgs) { 14331 synchronized (mInstallLock) { 14332 arg.doPostDeleteLI(false); 14333 } 14334 } 14335 } 14336 14337 /* 14338 * Unload packages mounted on external media. This involves deleting package 14339 * data from internal structures, sending broadcasts about diabled packages, 14340 * gc'ing to free up references, unmounting all secure containers 14341 * corresponding to packages on external media, and posting a 14342 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14343 * that we always have to post this message if status has been requested no 14344 * matter what. 14345 */ 14346 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14347 final boolean reportStatus) { 14348 if (DEBUG_SD_INSTALL) 14349 Log.i(TAG, "unloading media packages"); 14350 ArrayList<String> pkgList = new ArrayList<String>(); 14351 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14352 final Set<AsecInstallArgs> keys = processCids.keySet(); 14353 for (AsecInstallArgs args : keys) { 14354 String pkgName = args.getPackageName(); 14355 if (DEBUG_SD_INSTALL) 14356 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14357 // Delete package internally 14358 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14359 synchronized (mInstallLock) { 14360 boolean res = deletePackageLI(pkgName, null, false, null, null, 14361 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14362 if (res) { 14363 pkgList.add(pkgName); 14364 } else { 14365 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14366 failedList.add(args); 14367 } 14368 } 14369 } 14370 14371 // reader 14372 synchronized (mPackages) { 14373 // We didn't update the settings after removing each package; 14374 // write them now for all packages. 14375 mSettings.writeLPr(); 14376 } 14377 14378 // We have to absolutely send UPDATED_MEDIA_STATUS only 14379 // after confirming that all the receivers processed the ordered 14380 // broadcast when packages get disabled, force a gc to clean things up. 14381 // and unload all the containers. 14382 if (pkgList.size() > 0) { 14383 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14384 new IIntentReceiver.Stub() { 14385 public void performReceive(Intent intent, int resultCode, String data, 14386 Bundle extras, boolean ordered, boolean sticky, 14387 int sendingUser) throws RemoteException { 14388 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14389 reportStatus ? 1 : 0, 1, keys); 14390 mHandler.sendMessage(msg); 14391 } 14392 }); 14393 } else { 14394 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14395 keys); 14396 mHandler.sendMessage(msg); 14397 } 14398 } 14399 14400 private void loadPrivatePackages(VolumeInfo vol) { 14401 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14402 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14403 synchronized (mInstallLock) { 14404 synchronized (mPackages) { 14405 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14406 for (PackageSetting ps : packages) { 14407 final PackageParser.Package pkg; 14408 try { 14409 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14410 loaded.add(pkg.applicationInfo); 14411 } catch (PackageManagerException e) { 14412 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14413 } 14414 } 14415 14416 // TODO: regrant any permissions that changed based since original install 14417 14418 mSettings.writeLPr(); 14419 } 14420 } 14421 14422 Slog.d(TAG, "Loaded packages " + loaded); 14423 sendResourcesChangedBroadcast(true, false, loaded, null); 14424 } 14425 14426 private void unloadPrivatePackages(VolumeInfo vol) { 14427 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14428 synchronized (mInstallLock) { 14429 synchronized (mPackages) { 14430 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14431 for (PackageSetting ps : packages) { 14432 if (ps.pkg == null) continue; 14433 14434 final ApplicationInfo info = ps.pkg.applicationInfo; 14435 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14436 if (deletePackageLI(ps.name, null, false, null, null, 14437 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14438 unloaded.add(info); 14439 } else { 14440 Slog.w(TAG, "Failed to unload " + ps.codePath); 14441 } 14442 } 14443 14444 mSettings.writeLPr(); 14445 } 14446 } 14447 14448 Slog.d(TAG, "Unloaded packages " + unloaded); 14449 sendResourcesChangedBroadcast(false, false, unloaded, null); 14450 } 14451 14452 private void unfreezePackage(String packageName) { 14453 synchronized (mPackages) { 14454 final PackageSetting ps = mSettings.mPackages.get(packageName); 14455 if (ps != null) { 14456 ps.frozen = false; 14457 } 14458 } 14459 } 14460 14461 @Override 14462 public int movePackage(final String packageName, final String volumeUuid) { 14463 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14464 14465 final int moveId = mNextMoveId.getAndIncrement(); 14466 try { 14467 movePackageInternal(packageName, volumeUuid, moveId); 14468 } catch (PackageManagerException e) { 14469 Slog.d(TAG, "Failed to move " + packageName, e); 14470 mMoveCallbacks.notifyStatusChanged(moveId, 14471 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14472 } 14473 return moveId; 14474 } 14475 14476 private void movePackageInternal(final String packageName, final String volumeUuid, 14477 final int moveId) throws PackageManagerException { 14478 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14479 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14480 final PackageManager pm = mContext.getPackageManager(); 14481 14482 final boolean currentAsec; 14483 final String currentVolumeUuid; 14484 final File codeFile; 14485 final String installerPackageName; 14486 final String packageAbiOverride; 14487 final int appId; 14488 final String seinfo; 14489 final String label; 14490 14491 // reader 14492 synchronized (mPackages) { 14493 final PackageParser.Package pkg = mPackages.get(packageName); 14494 final PackageSetting ps = mSettings.mPackages.get(packageName); 14495 if (pkg == null || ps == null) { 14496 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14497 } 14498 14499 if (pkg.applicationInfo.isSystemApp()) { 14500 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14501 "Cannot move system application"); 14502 } 14503 14504 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14505 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14506 "Package already moved to " + volumeUuid); 14507 } 14508 14509 final File probe = new File(pkg.codePath); 14510 final File probeOat = new File(probe, "oat"); 14511 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14512 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14513 "Move only supported for modern cluster style installs"); 14514 } 14515 14516 if (ps.frozen) { 14517 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14518 "Failed to move already frozen package"); 14519 } 14520 ps.frozen = true; 14521 14522 currentAsec = pkg.applicationInfo.isForwardLocked() 14523 || pkg.applicationInfo.isExternalAsec(); 14524 currentVolumeUuid = ps.volumeUuid; 14525 codeFile = new File(pkg.codePath); 14526 installerPackageName = ps.installerPackageName; 14527 packageAbiOverride = ps.cpuAbiOverrideString; 14528 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14529 seinfo = pkg.applicationInfo.seinfo; 14530 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14531 } 14532 14533 // Now that we're guarded by frozen state, kill app during move 14534 killApplication(packageName, appId, "move pkg"); 14535 14536 final Bundle extras = new Bundle(); 14537 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14538 extras.putString(Intent.EXTRA_TITLE, label); 14539 mMoveCallbacks.notifyCreated(moveId, extras); 14540 14541 int installFlags; 14542 final boolean moveCompleteApp; 14543 final File measurePath; 14544 14545 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14546 installFlags = INSTALL_INTERNAL; 14547 moveCompleteApp = !currentAsec; 14548 measurePath = Environment.getDataAppDirectory(volumeUuid); 14549 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14550 installFlags = INSTALL_EXTERNAL; 14551 moveCompleteApp = false; 14552 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14553 } else { 14554 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14555 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14556 || !volume.isMountedWritable()) { 14557 unfreezePackage(packageName); 14558 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14559 "Move location not mounted private volume"); 14560 } 14561 14562 Preconditions.checkState(!currentAsec); 14563 14564 installFlags = INSTALL_INTERNAL; 14565 moveCompleteApp = true; 14566 measurePath = Environment.getDataAppDirectory(volumeUuid); 14567 } 14568 14569 final PackageStats stats = new PackageStats(null, -1); 14570 synchronized (mInstaller) { 14571 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14572 unfreezePackage(packageName); 14573 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14574 "Failed to measure package size"); 14575 } 14576 } 14577 14578 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14579 14580 final long startFreeBytes = measurePath.getFreeSpace(); 14581 final long sizeBytes; 14582 if (moveCompleteApp) { 14583 sizeBytes = stats.codeSize + stats.dataSize; 14584 } else { 14585 sizeBytes = stats.codeSize; 14586 } 14587 14588 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14589 unfreezePackage(packageName); 14590 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14591 "Not enough free space to move"); 14592 } 14593 14594 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14595 14596 final CountDownLatch installedLatch = new CountDownLatch(1); 14597 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14598 @Override 14599 public void onUserActionRequired(Intent intent) throws RemoteException { 14600 throw new IllegalStateException(); 14601 } 14602 14603 @Override 14604 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14605 Bundle extras) throws RemoteException { 14606 Slog.d(TAG, "Install result for move: " 14607 + PackageManager.installStatusToString(returnCode, msg)); 14608 14609 installedLatch.countDown(); 14610 14611 // Regardless of success or failure of the move operation, 14612 // always unfreeze the package 14613 unfreezePackage(packageName); 14614 14615 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14616 switch (status) { 14617 case PackageInstaller.STATUS_SUCCESS: 14618 mMoveCallbacks.notifyStatusChanged(moveId, 14619 PackageManager.MOVE_SUCCEEDED); 14620 break; 14621 case PackageInstaller.STATUS_FAILURE_STORAGE: 14622 mMoveCallbacks.notifyStatusChanged(moveId, 14623 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14624 break; 14625 default: 14626 mMoveCallbacks.notifyStatusChanged(moveId, 14627 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14628 break; 14629 } 14630 } 14631 }; 14632 14633 final MoveInfo move; 14634 if (moveCompleteApp) { 14635 // Kick off a thread to report progress estimates 14636 new Thread() { 14637 @Override 14638 public void run() { 14639 while (true) { 14640 try { 14641 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14642 break; 14643 } 14644 } catch (InterruptedException ignored) { 14645 } 14646 14647 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14648 final int progress = 10 + (int) MathUtils.constrain( 14649 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14650 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14651 } 14652 } 14653 }.start(); 14654 14655 final String dataAppName = codeFile.getName(); 14656 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14657 dataAppName, appId, seinfo); 14658 } else { 14659 move = null; 14660 } 14661 14662 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14663 14664 final Message msg = mHandler.obtainMessage(INIT_COPY); 14665 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14666 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14667 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14668 mHandler.sendMessage(msg); 14669 } 14670 14671 @Override 14672 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14673 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14674 14675 final int realMoveId = mNextMoveId.getAndIncrement(); 14676 final Bundle extras = new Bundle(); 14677 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14678 mMoveCallbacks.notifyCreated(realMoveId, extras); 14679 14680 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14681 @Override 14682 public void onCreated(int moveId, Bundle extras) { 14683 // Ignored 14684 } 14685 14686 @Override 14687 public void onStatusChanged(int moveId, int status, long estMillis) { 14688 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14689 } 14690 }; 14691 14692 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14693 storage.setPrimaryStorageUuid(volumeUuid, callback); 14694 return realMoveId; 14695 } 14696 14697 @Override 14698 public int getMoveStatus(int moveId) { 14699 mContext.enforceCallingOrSelfPermission( 14700 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14701 return mMoveCallbacks.mLastStatus.get(moveId); 14702 } 14703 14704 @Override 14705 public void registerMoveCallback(IPackageMoveObserver callback) { 14706 mContext.enforceCallingOrSelfPermission( 14707 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14708 mMoveCallbacks.register(callback); 14709 } 14710 14711 @Override 14712 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14713 mContext.enforceCallingOrSelfPermission( 14714 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14715 mMoveCallbacks.unregister(callback); 14716 } 14717 14718 @Override 14719 public boolean setInstallLocation(int loc) { 14720 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14721 null); 14722 if (getInstallLocation() == loc) { 14723 return true; 14724 } 14725 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14726 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14727 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14728 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14729 return true; 14730 } 14731 return false; 14732 } 14733 14734 @Override 14735 public int getInstallLocation() { 14736 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14737 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14738 PackageHelper.APP_INSTALL_AUTO); 14739 } 14740 14741 /** Called by UserManagerService */ 14742 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14743 mDirtyUsers.remove(userHandle); 14744 mSettings.removeUserLPw(userHandle); 14745 mPendingBroadcasts.remove(userHandle); 14746 if (mInstaller != null) { 14747 // Technically, we shouldn't be doing this with the package lock 14748 // held. However, this is very rare, and there is already so much 14749 // other disk I/O going on, that we'll let it slide for now. 14750 final StorageManager storage = StorageManager.from(mContext); 14751 final List<VolumeInfo> vols = storage.getVolumes(); 14752 for (VolumeInfo vol : vols) { 14753 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14754 final String volumeUuid = vol.getFsUuid(); 14755 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14756 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14757 } 14758 } 14759 } 14760 mUserNeedsBadging.delete(userHandle); 14761 removeUnusedPackagesLILPw(userManager, userHandle); 14762 } 14763 14764 /** 14765 * We're removing userHandle and would like to remove any downloaded packages 14766 * that are no longer in use by any other user. 14767 * @param userHandle the user being removed 14768 */ 14769 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14770 final boolean DEBUG_CLEAN_APKS = false; 14771 int [] users = userManager.getUserIdsLPr(); 14772 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14773 while (psit.hasNext()) { 14774 PackageSetting ps = psit.next(); 14775 if (ps.pkg == null) { 14776 continue; 14777 } 14778 final String packageName = ps.pkg.packageName; 14779 // Skip over if system app 14780 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14781 continue; 14782 } 14783 if (DEBUG_CLEAN_APKS) { 14784 Slog.i(TAG, "Checking package " + packageName); 14785 } 14786 boolean keep = false; 14787 for (int i = 0; i < users.length; i++) { 14788 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14789 keep = true; 14790 if (DEBUG_CLEAN_APKS) { 14791 Slog.i(TAG, " Keeping package " + packageName + " for user " 14792 + users[i]); 14793 } 14794 break; 14795 } 14796 } 14797 if (!keep) { 14798 if (DEBUG_CLEAN_APKS) { 14799 Slog.i(TAG, " Removing package " + packageName); 14800 } 14801 mHandler.post(new Runnable() { 14802 public void run() { 14803 deletePackageX(packageName, userHandle, 0); 14804 } //end run 14805 }); 14806 } 14807 } 14808 } 14809 14810 /** Called by UserManagerService */ 14811 void createNewUserLILPw(int userHandle, File path) { 14812 if (mInstaller != null) { 14813 mInstaller.createUserConfig(userHandle); 14814 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14815 } 14816 } 14817 14818 void newUserCreatedLILPw(int userHandle) { 14819 // Adding a user requires updating runtime permissions for system apps. 14820 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14821 } 14822 14823 @Override 14824 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14825 mContext.enforceCallingOrSelfPermission( 14826 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14827 "Only package verification agents can read the verifier device identity"); 14828 14829 synchronized (mPackages) { 14830 return mSettings.getVerifierDeviceIdentityLPw(); 14831 } 14832 } 14833 14834 @Override 14835 public void setPermissionEnforced(String permission, boolean enforced) { 14836 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14837 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14838 synchronized (mPackages) { 14839 if (mSettings.mReadExternalStorageEnforced == null 14840 || mSettings.mReadExternalStorageEnforced != enforced) { 14841 mSettings.mReadExternalStorageEnforced = enforced; 14842 mSettings.writeLPr(); 14843 } 14844 } 14845 // kill any non-foreground processes so we restart them and 14846 // grant/revoke the GID. 14847 final IActivityManager am = ActivityManagerNative.getDefault(); 14848 if (am != null) { 14849 final long token = Binder.clearCallingIdentity(); 14850 try { 14851 am.killProcessesBelowForeground("setPermissionEnforcement"); 14852 } catch (RemoteException e) { 14853 } finally { 14854 Binder.restoreCallingIdentity(token); 14855 } 14856 } 14857 } else { 14858 throw new IllegalArgumentException("No selective enforcement for " + permission); 14859 } 14860 } 14861 14862 @Override 14863 @Deprecated 14864 public boolean isPermissionEnforced(String permission) { 14865 return true; 14866 } 14867 14868 @Override 14869 public boolean isStorageLow() { 14870 final long token = Binder.clearCallingIdentity(); 14871 try { 14872 final DeviceStorageMonitorInternal 14873 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14874 if (dsm != null) { 14875 return dsm.isMemoryLow(); 14876 } else { 14877 return false; 14878 } 14879 } finally { 14880 Binder.restoreCallingIdentity(token); 14881 } 14882 } 14883 14884 @Override 14885 public IPackageInstaller getPackageInstaller() { 14886 return mInstallerService; 14887 } 14888 14889 private boolean userNeedsBadging(int userId) { 14890 int index = mUserNeedsBadging.indexOfKey(userId); 14891 if (index < 0) { 14892 final UserInfo userInfo; 14893 final long token = Binder.clearCallingIdentity(); 14894 try { 14895 userInfo = sUserManager.getUserInfo(userId); 14896 } finally { 14897 Binder.restoreCallingIdentity(token); 14898 } 14899 final boolean b; 14900 if (userInfo != null && userInfo.isManagedProfile()) { 14901 b = true; 14902 } else { 14903 b = false; 14904 } 14905 mUserNeedsBadging.put(userId, b); 14906 return b; 14907 } 14908 return mUserNeedsBadging.valueAt(index); 14909 } 14910 14911 @Override 14912 public KeySet getKeySetByAlias(String packageName, String alias) { 14913 if (packageName == null || alias == null) { 14914 return null; 14915 } 14916 synchronized(mPackages) { 14917 final PackageParser.Package pkg = mPackages.get(packageName); 14918 if (pkg == null) { 14919 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14920 throw new IllegalArgumentException("Unknown package: " + packageName); 14921 } 14922 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14923 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14924 } 14925 } 14926 14927 @Override 14928 public KeySet getSigningKeySet(String packageName) { 14929 if (packageName == null) { 14930 return null; 14931 } 14932 synchronized(mPackages) { 14933 final PackageParser.Package pkg = mPackages.get(packageName); 14934 if (pkg == null) { 14935 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14936 throw new IllegalArgumentException("Unknown package: " + packageName); 14937 } 14938 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14939 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14940 throw new SecurityException("May not access signing KeySet of other apps."); 14941 } 14942 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14943 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14944 } 14945 } 14946 14947 @Override 14948 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14949 if (packageName == null || ks == null) { 14950 return false; 14951 } 14952 synchronized(mPackages) { 14953 final PackageParser.Package pkg = mPackages.get(packageName); 14954 if (pkg == null) { 14955 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14956 throw new IllegalArgumentException("Unknown package: " + packageName); 14957 } 14958 IBinder ksh = ks.getToken(); 14959 if (ksh instanceof KeySetHandle) { 14960 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14961 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14962 } 14963 return false; 14964 } 14965 } 14966 14967 @Override 14968 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14969 if (packageName == null || ks == null) { 14970 return false; 14971 } 14972 synchronized(mPackages) { 14973 final PackageParser.Package pkg = mPackages.get(packageName); 14974 if (pkg == null) { 14975 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14976 throw new IllegalArgumentException("Unknown package: " + packageName); 14977 } 14978 IBinder ksh = ks.getToken(); 14979 if (ksh instanceof KeySetHandle) { 14980 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14981 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14982 } 14983 return false; 14984 } 14985 } 14986 14987 public void getUsageStatsIfNoPackageUsageInfo() { 14988 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14989 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14990 if (usm == null) { 14991 throw new IllegalStateException("UsageStatsManager must be initialized"); 14992 } 14993 long now = System.currentTimeMillis(); 14994 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14995 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14996 String packageName = entry.getKey(); 14997 PackageParser.Package pkg = mPackages.get(packageName); 14998 if (pkg == null) { 14999 continue; 15000 } 15001 UsageStats usage = entry.getValue(); 15002 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15003 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15004 } 15005 } 15006 } 15007 15008 /** 15009 * Check and throw if the given before/after packages would be considered a 15010 * downgrade. 15011 */ 15012 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15013 throws PackageManagerException { 15014 if (after.versionCode < before.mVersionCode) { 15015 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15016 "Update version code " + after.versionCode + " is older than current " 15017 + before.mVersionCode); 15018 } else if (after.versionCode == before.mVersionCode) { 15019 if (after.baseRevisionCode < before.baseRevisionCode) { 15020 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15021 "Update base revision code " + after.baseRevisionCode 15022 + " is older than current " + before.baseRevisionCode); 15023 } 15024 15025 if (!ArrayUtils.isEmpty(after.splitNames)) { 15026 for (int i = 0; i < after.splitNames.length; i++) { 15027 final String splitName = after.splitNames[i]; 15028 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15029 if (j != -1) { 15030 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15031 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15032 "Update split " + splitName + " revision code " 15033 + after.splitRevisionCodes[i] + " is older than current " 15034 + before.splitRevisionCodes[j]); 15035 } 15036 } 15037 } 15038 } 15039 } 15040 } 15041 15042 private static class MoveCallbacks extends Handler { 15043 private static final int MSG_CREATED = 1; 15044 private static final int MSG_STATUS_CHANGED = 2; 15045 15046 private final RemoteCallbackList<IPackageMoveObserver> 15047 mCallbacks = new RemoteCallbackList<>(); 15048 15049 private final SparseIntArray mLastStatus = new SparseIntArray(); 15050 15051 public MoveCallbacks(Looper looper) { 15052 super(looper); 15053 } 15054 15055 public void register(IPackageMoveObserver callback) { 15056 mCallbacks.register(callback); 15057 } 15058 15059 public void unregister(IPackageMoveObserver callback) { 15060 mCallbacks.unregister(callback); 15061 } 15062 15063 @Override 15064 public void handleMessage(Message msg) { 15065 final SomeArgs args = (SomeArgs) msg.obj; 15066 final int n = mCallbacks.beginBroadcast(); 15067 for (int i = 0; i < n; i++) { 15068 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15069 try { 15070 invokeCallback(callback, msg.what, args); 15071 } catch (RemoteException ignored) { 15072 } 15073 } 15074 mCallbacks.finishBroadcast(); 15075 args.recycle(); 15076 } 15077 15078 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15079 throws RemoteException { 15080 switch (what) { 15081 case MSG_CREATED: { 15082 callback.onCreated(args.argi1, (Bundle) args.arg2); 15083 break; 15084 } 15085 case MSG_STATUS_CHANGED: { 15086 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15087 break; 15088 } 15089 } 15090 } 15091 15092 private void notifyCreated(int moveId, Bundle extras) { 15093 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15094 15095 final SomeArgs args = SomeArgs.obtain(); 15096 args.argi1 = moveId; 15097 args.arg2 = extras; 15098 obtainMessage(MSG_CREATED, args).sendToTarget(); 15099 } 15100 15101 private void notifyStatusChanged(int moveId, int status) { 15102 notifyStatusChanged(moveId, status, -1); 15103 } 15104 15105 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15106 Slog.v(TAG, "Move " + moveId + " status " + status); 15107 15108 final SomeArgs args = SomeArgs.obtain(); 15109 args.argi1 = moveId; 15110 args.argi2 = status; 15111 args.arg3 = estMillis; 15112 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15113 15114 synchronized (mLastStatus) { 15115 mLastStatus.put(moveId, status); 15116 } 15117 } 15118 } 15119} 15120