PackageManagerService.java revision 8c7f700a59ad26e75c9791335d78f14322cad49a
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.PACKAGE_INFO_GID; 59import static android.os.Process.SYSTEM_UID; 60import static android.system.OsConstants.O_CREAT; 61import static android.system.OsConstants.O_RDWR; 62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 66import static com.android.internal.util.ArrayUtils.appendInt; 67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 72 73import android.Manifest; 74import android.app.ActivityManager; 75import android.app.ActivityManagerNative; 76import android.app.AppGlobals; 77import android.app.IActivityManager; 78import android.app.admin.IDevicePolicyManager; 79import android.app.backup.IBackupManager; 80import android.app.usage.UsageStats; 81import android.app.usage.UsageStatsManager; 82import android.content.BroadcastReceiver; 83import android.content.ComponentName; 84import android.content.Context; 85import android.content.IIntentReceiver; 86import android.content.Intent; 87import android.content.IntentFilter; 88import android.content.IntentSender; 89import android.content.IntentSender.SendIntentException; 90import android.content.ServiceConnection; 91import android.content.pm.ActivityInfo; 92import android.content.pm.ApplicationInfo; 93import android.content.pm.FeatureInfo; 94import android.content.pm.IPackageDataObserver; 95import android.content.pm.IPackageDeleteObserver; 96import android.content.pm.IPackageDeleteObserver2; 97import android.content.pm.IPackageInstallObserver2; 98import android.content.pm.IPackageInstaller; 99import android.content.pm.IPackageManager; 100import android.content.pm.IPackageMoveObserver; 101import android.content.pm.IPackageStatsObserver; 102import android.content.pm.InstrumentationInfo; 103import android.content.pm.IntentFilterVerificationInfo; 104import android.content.pm.KeySet; 105import android.content.pm.ManifestDigest; 106import android.content.pm.PackageCleanItem; 107import android.content.pm.PackageInfo; 108import android.content.pm.PackageInfoLite; 109import android.content.pm.PackageInstaller; 110import android.content.pm.PackageManager; 111import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 112import android.content.pm.PackageParser; 113import android.content.pm.PackageParser.ActivityIntentInfo; 114import android.content.pm.PackageParser.PackageLite; 115import android.content.pm.PackageParser.PackageParserException; 116import android.content.pm.PackageStats; 117import android.content.pm.PackageUserState; 118import android.content.pm.ParceledListSlice; 119import android.content.pm.PermissionGroupInfo; 120import android.content.pm.PermissionInfo; 121import android.content.pm.ProviderInfo; 122import android.content.pm.ResolveInfo; 123import android.content.pm.ServiceInfo; 124import android.content.pm.Signature; 125import android.content.pm.UserInfo; 126import android.content.pm.VerificationParams; 127import android.content.pm.VerifierDeviceIdentity; 128import android.content.pm.VerifierInfo; 129import android.content.res.Resources; 130import android.hardware.display.DisplayManager; 131import android.net.Uri; 132import android.os.Binder; 133import android.os.Build; 134import android.os.Bundle; 135import android.os.Debug; 136import android.os.Environment; 137import android.os.Environment.UserEnvironment; 138import android.os.FileUtils; 139import android.os.Handler; 140import android.os.IBinder; 141import android.os.Looper; 142import android.os.Message; 143import android.os.Parcel; 144import android.os.ParcelFileDescriptor; 145import android.os.Process; 146import android.os.RemoteCallbackList; 147import android.os.RemoteException; 148import android.os.SELinux; 149import android.os.ServiceManager; 150import android.os.SystemClock; 151import android.os.SystemProperties; 152import android.os.UserHandle; 153import android.os.UserManager; 154import android.os.storage.IMountService; 155import android.os.storage.StorageEventListener; 156import android.os.storage.StorageManager; 157import android.os.storage.VolumeInfo; 158import android.os.storage.VolumeRecord; 159import android.security.KeyStore; 160import android.security.SystemKeyStore; 161import android.system.ErrnoException; 162import android.system.Os; 163import android.system.StructStat; 164import android.text.TextUtils; 165import android.text.format.DateUtils; 166import android.util.ArrayMap; 167import android.util.ArraySet; 168import android.util.AtomicFile; 169import android.util.DisplayMetrics; 170import android.util.EventLog; 171import android.util.ExceptionUtils; 172import android.util.Log; 173import android.util.LogPrinter; 174import android.util.MathUtils; 175import android.util.PrintStreamPrinter; 176import android.util.Slog; 177import android.util.SparseArray; 178import android.util.SparseBooleanArray; 179import android.util.SparseIntArray; 180import android.util.Xml; 181import android.view.Display; 182 183import dalvik.system.DexFile; 184import dalvik.system.VMRuntime; 185 186import libcore.io.IoUtils; 187import libcore.util.EmptyArray; 188 189import com.android.internal.R; 190import com.android.internal.app.IMediaContainerService; 191import com.android.internal.app.ResolverActivity; 192import com.android.internal.content.NativeLibraryHelper; 193import com.android.internal.content.PackageHelper; 194import com.android.internal.os.IParcelFileDescriptorFactory; 195import com.android.internal.os.SomeArgs; 196import com.android.internal.util.ArrayUtils; 197import com.android.internal.util.FastPrintWriter; 198import com.android.internal.util.FastXmlSerializer; 199import com.android.internal.util.IndentingPrintWriter; 200import com.android.internal.util.Preconditions; 201import com.android.server.EventLogTags; 202import com.android.server.FgThread; 203import com.android.server.IntentResolver; 204import com.android.server.LocalServices; 205import com.android.server.ServiceThread; 206import com.android.server.SystemConfig; 207import com.android.server.Watchdog; 208import com.android.server.pm.Settings.DatabaseVersion; 209import com.android.server.pm.PermissionsState.PermissionState; 210import com.android.server.storage.DeviceStorageMonitorInternal; 211 212import org.xmlpull.v1.XmlPullParser; 213import org.xmlpull.v1.XmlSerializer; 214 215import java.io.BufferedInputStream; 216import java.io.BufferedOutputStream; 217import java.io.BufferedReader; 218import java.io.ByteArrayInputStream; 219import java.io.ByteArrayOutputStream; 220import java.io.File; 221import java.io.FileDescriptor; 222import java.io.FileNotFoundException; 223import java.io.FileOutputStream; 224import java.io.FileReader; 225import java.io.FilenameFilter; 226import java.io.IOException; 227import java.io.InputStream; 228import java.io.PrintWriter; 229import java.nio.charset.StandardCharsets; 230import java.security.NoSuchAlgorithmException; 231import java.security.PublicKey; 232import java.security.cert.CertificateEncodingException; 233import java.security.cert.CertificateException; 234import java.text.SimpleDateFormat; 235import java.util.ArrayList; 236import java.util.Arrays; 237import java.util.Collection; 238import java.util.Collections; 239import java.util.Comparator; 240import java.util.Date; 241import java.util.Iterator; 242import java.util.List; 243import java.util.Map; 244import java.util.Objects; 245import java.util.Set; 246import java.util.concurrent.CountDownLatch; 247import java.util.concurrent.TimeUnit; 248import java.util.concurrent.atomic.AtomicBoolean; 249import java.util.concurrent.atomic.AtomicInteger; 250import java.util.concurrent.atomic.AtomicLong; 251 252/** 253 * Keep track of all those .apks everywhere. 254 * 255 * This is very central to the platform's security; please run the unit 256 * tests whenever making modifications here: 257 * 258mmm frameworks/base/tests/AndroidTests 259adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 260adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 261 * 262 * {@hide} 263 */ 264public class PackageManagerService extends IPackageManager.Stub { 265 static final String TAG = "PackageManager"; 266 static final boolean DEBUG_SETTINGS = false; 267 static final boolean DEBUG_PREFERRED = false; 268 static final boolean DEBUG_UPGRADE = false; 269 private static final boolean DEBUG_BACKUP = true; 270 private static final boolean DEBUG_INSTALL = false; 271 private static final boolean DEBUG_REMOVE = false; 272 private static final boolean DEBUG_BROADCASTS = false; 273 private static final boolean DEBUG_SHOW_INFO = false; 274 private static final boolean DEBUG_PACKAGE_INFO = false; 275 private static final boolean DEBUG_INTENT_MATCHING = false; 276 private static final boolean DEBUG_PACKAGE_SCANNING = false; 277 private static final boolean DEBUG_VERIFY = false; 278 private static final boolean DEBUG_DEXOPT = false; 279 private static final boolean DEBUG_ABI_SELECTION = false; 280 281 private static final int RADIO_UID = Process.PHONE_UID; 282 private static final int LOG_UID = Process.LOG_UID; 283 private static final int NFC_UID = Process.NFC_UID; 284 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 285 private static final int SHELL_UID = Process.SHELL_UID; 286 287 // Cap the size of permission trees that 3rd party apps can define 288 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 289 290 // Suffix used during package installation when copying/moving 291 // package apks to install directory. 292 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 293 294 static final int SCAN_NO_DEX = 1<<1; 295 static final int SCAN_FORCE_DEX = 1<<2; 296 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 297 static final int SCAN_NEW_INSTALL = 1<<4; 298 static final int SCAN_NO_PATHS = 1<<5; 299 static final int SCAN_UPDATE_TIME = 1<<6; 300 static final int SCAN_DEFER_DEX = 1<<7; 301 static final int SCAN_BOOTING = 1<<8; 302 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 303 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 304 static final int SCAN_REQUIRE_KNOWN = 1<<12; 305 306 static final int REMOVE_CHATTY = 1<<16; 307 308 private static final int[] EMPTY_INT_ARRAY = new int[0]; 309 310 /** 311 * Timeout (in milliseconds) after which the watchdog should declare that 312 * our handler thread is wedged. The usual default for such things is one 313 * minute but we sometimes do very lengthy I/O operations on this thread, 314 * such as installing multi-gigabyte applications, so ours needs to be longer. 315 */ 316 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 317 318 /** 319 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 320 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 321 * settings entry if available, otherwise we use the hardcoded default. If it's been 322 * more than this long since the last fstrim, we force one during the boot sequence. 323 * 324 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 325 * one gets run at the next available charging+idle time. This final mandatory 326 * no-fstrim check kicks in only of the other scheduling criteria is never met. 327 */ 328 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 329 330 /** 331 * Whether verification is enabled by default. 332 */ 333 private static final boolean DEFAULT_VERIFY_ENABLE = true; 334 335 /** 336 * The default maximum time to wait for the verification agent to return in 337 * milliseconds. 338 */ 339 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 340 341 /** 342 * The default response for package verification timeout. 343 * 344 * This can be either PackageManager.VERIFICATION_ALLOW or 345 * PackageManager.VERIFICATION_REJECT. 346 */ 347 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 348 349 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 350 351 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 352 DEFAULT_CONTAINER_PACKAGE, 353 "com.android.defcontainer.DefaultContainerService"); 354 355 private static final String KILL_APP_REASON_GIDS_CHANGED = 356 "permission grant or revoke changed gids"; 357 358 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 359 "permissions revoked"; 360 361 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 362 363 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 364 365 /** Permission grant: not grant the permission. */ 366 private static final int GRANT_DENIED = 1; 367 368 /** Permission grant: grant the permission as an install permission. */ 369 private static final int GRANT_INSTALL = 2; 370 371 /** Permission grant: grant the permission as a runtime one. */ 372 private static final int GRANT_RUNTIME = 3; 373 374 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 375 private static final int GRANT_UPGRADE = 4; 376 377 final ServiceThread mHandlerThread; 378 379 final PackageHandler mHandler; 380 381 /** 382 * Messages for {@link #mHandler} that need to wait for system ready before 383 * being dispatched. 384 */ 385 private ArrayList<Message> mPostSystemReadyMessages; 386 387 final int mSdkVersion = Build.VERSION.SDK_INT; 388 389 final Context mContext; 390 final boolean mFactoryTest; 391 final boolean mOnlyCore; 392 final boolean mLazyDexOpt; 393 final long mDexOptLRUThresholdInMills; 394 final DisplayMetrics mMetrics; 395 final int mDefParseFlags; 396 final String[] mSeparateProcesses; 397 final boolean mIsUpgrade; 398 399 // This is where all application persistent data goes. 400 final File mAppDataDir; 401 402 // This is where all application persistent data goes for secondary users. 403 final File mUserAppDataDir; 404 405 /** The location for ASEC container files on internal storage. */ 406 final String mAsecInternalPath; 407 408 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 409 // LOCK HELD. Can be called with mInstallLock held. 410 final Installer mInstaller; 411 412 /** Directory where installed third-party apps stored */ 413 final File mAppInstallDir; 414 415 /** 416 * Directory to which applications installed internally have their 417 * 32 bit native libraries copied. 418 */ 419 private File mAppLib32InstallDir; 420 421 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 422 // apps. 423 final File mDrmAppPrivateInstallDir; 424 425 // ---------------------------------------------------------------- 426 427 // Lock for state used when installing and doing other long running 428 // operations. Methods that must be called with this lock held have 429 // the suffix "LI". 430 final Object mInstallLock = new Object(); 431 432 // ---------------------------------------------------------------- 433 434 // Keys are String (package name), values are Package. This also serves 435 // as the lock for the global state. Methods that must be called with 436 // this lock held have the prefix "LP". 437 final ArrayMap<String, PackageParser.Package> mPackages = 438 new ArrayMap<String, PackageParser.Package>(); 439 440 // Tracks available target package names -> overlay package paths. 441 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 442 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 443 444 final Settings mSettings; 445 boolean mRestoredSettings; 446 447 // System configuration read by SystemConfig. 448 final int[] mGlobalGids; 449 final SparseArray<ArraySet<String>> mSystemPermissions; 450 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 451 452 // If mac_permissions.xml was found for seinfo labeling. 453 boolean mFoundPolicyFile; 454 455 // If a recursive restorecon of /data/data/<pkg> is needed. 456 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 457 458 public static final class SharedLibraryEntry { 459 public final String path; 460 public final String apk; 461 462 SharedLibraryEntry(String _path, String _apk) { 463 path = _path; 464 apk = _apk; 465 } 466 } 467 468 // Currently known shared libraries. 469 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 470 new ArrayMap<String, SharedLibraryEntry>(); 471 472 // All available activities, for your resolving pleasure. 473 final ActivityIntentResolver mActivities = 474 new ActivityIntentResolver(); 475 476 // All available receivers, for your resolving pleasure. 477 final ActivityIntentResolver mReceivers = 478 new ActivityIntentResolver(); 479 480 // All available services, for your resolving pleasure. 481 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 482 483 // All available providers, for your resolving pleasure. 484 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 485 486 // Mapping from provider base names (first directory in content URI codePath) 487 // to the provider information. 488 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 489 new ArrayMap<String, PackageParser.Provider>(); 490 491 // Mapping from instrumentation class names to info about them. 492 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 493 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 494 495 // Mapping from permission names to info about them. 496 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 497 new ArrayMap<String, PackageParser.PermissionGroup>(); 498 499 // Packages whose data we have transfered into another package, thus 500 // should no longer exist. 501 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 502 503 // Broadcast actions that are only available to the system. 504 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 505 506 /** List of packages waiting for verification. */ 507 final SparseArray<PackageVerificationState> mPendingVerification 508 = new SparseArray<PackageVerificationState>(); 509 510 /** Set of packages associated with each app op permission. */ 511 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 512 513 final PackageInstallerService mInstallerService; 514 515 private final PackageDexOptimizer mPackageDexOptimizer; 516 517 private AtomicInteger mNextMoveId = new AtomicInteger(); 518 private final MoveCallbacks mMoveCallbacks; 519 520 // Cache of users who need badging. 521 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 522 523 /** Token for keys in mPendingVerification. */ 524 private int mPendingVerificationToken = 0; 525 526 volatile boolean mSystemReady; 527 volatile boolean mSafeMode; 528 volatile boolean mHasSystemUidErrors; 529 530 ApplicationInfo mAndroidApplication; 531 final ActivityInfo mResolveActivity = new ActivityInfo(); 532 final ResolveInfo mResolveInfo = new ResolveInfo(); 533 ComponentName mResolveComponentName; 534 PackageParser.Package mPlatformPackage; 535 ComponentName mCustomResolverComponentName; 536 537 boolean mResolverReplaced = false; 538 539 private final ComponentName mIntentFilterVerifierComponent; 540 private int mIntentFilterVerificationToken = 0; 541 542 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 543 = new SparseArray<IntentFilterVerificationState>(); 544 545 private interface IntentFilterVerifier<T extends IntentFilter> { 546 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 547 T filter, String packageName); 548 void startVerifications(int userId); 549 void receiveVerificationResponse(int verificationId); 550 } 551 552 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 553 private Context mContext; 554 private ComponentName mIntentFilterVerifierComponent; 555 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 556 557 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 558 mContext = context; 559 mIntentFilterVerifierComponent = verifierComponent; 560 } 561 562 private String getDefaultScheme() { 563 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 564 return IntentFilter.SCHEME_HTTP; 565 } 566 567 @Override 568 public void startVerifications(int userId) { 569 // Launch verifications requests 570 int count = mCurrentIntentFilterVerifications.size(); 571 for (int n=0; n<count; n++) { 572 int verificationId = mCurrentIntentFilterVerifications.get(n); 573 final IntentFilterVerificationState ivs = 574 mIntentFilterVerificationStates.get(verificationId); 575 576 String packageName = ivs.getPackageName(); 577 578 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 579 final int filterCount = filters.size(); 580 ArraySet<String> domainsSet = new ArraySet<>(); 581 for (int m=0; m<filterCount; m++) { 582 PackageParser.ActivityIntentInfo filter = filters.get(m); 583 domainsSet.addAll(filter.getHostsList()); 584 } 585 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 586 synchronized (mPackages) { 587 if (mSettings.createIntentFilterVerificationIfNeededLPw( 588 packageName, domainsList) != null) { 589 scheduleWriteSettingsLocked(); 590 } 591 } 592 sendVerificationRequest(userId, verificationId, ivs); 593 } 594 mCurrentIntentFilterVerifications.clear(); 595 } 596 597 private void sendVerificationRequest(int userId, int verificationId, 598 IntentFilterVerificationState ivs) { 599 600 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 601 verificationIntent.putExtra( 602 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 603 verificationId); 604 verificationIntent.putExtra( 605 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 606 getDefaultScheme()); 607 verificationIntent.putExtra( 608 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 609 ivs.getHostsString()); 610 verificationIntent.putExtra( 611 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 612 ivs.getPackageName()); 613 verificationIntent.setComponent(mIntentFilterVerifierComponent); 614 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 615 616 UserHandle user = new UserHandle(userId); 617 mContext.sendBroadcastAsUser(verificationIntent, user); 618 Slog.d(TAG, "Sending IntenFilter verification broadcast"); 619 } 620 621 public void receiveVerificationResponse(int verificationId) { 622 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 623 624 final boolean verified = ivs.isVerified(); 625 626 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 627 final int count = filters.size(); 628 for (int n=0; n<count; n++) { 629 PackageParser.ActivityIntentInfo filter = filters.get(n); 630 filter.setVerified(verified); 631 632 Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:" 633 + verified + " and hosts:" + ivs.getHostsString()); 634 } 635 636 mIntentFilterVerificationStates.remove(verificationId); 637 638 final String packageName = ivs.getPackageName(); 639 IntentFilterVerificationInfo ivi = null; 640 641 synchronized (mPackages) { 642 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 643 } 644 if (ivi == null) { 645 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 646 + verificationId + " packageName:" + packageName); 647 return; 648 } 649 Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:" 650 + verificationId); 651 652 synchronized (mPackages) { 653 if (verified) { 654 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 655 } else { 656 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 657 } 658 scheduleWriteSettingsLocked(); 659 660 final int userId = ivs.getUserId(); 661 if (userId != UserHandle.USER_ALL) { 662 final int userStatus = 663 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 664 665 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 666 boolean needUpdate = false; 667 668 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 669 // already been set by the User thru the Disambiguation dialog 670 switch (userStatus) { 671 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 672 if (verified) { 673 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 674 } else { 675 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 676 } 677 needUpdate = true; 678 break; 679 680 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 681 if (verified) { 682 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 683 needUpdate = true; 684 } 685 break; 686 687 default: 688 // Nothing to do 689 } 690 691 if (needUpdate) { 692 mSettings.updateIntentFilterVerificationStatusLPw( 693 packageName, updatedStatus, userId); 694 scheduleWritePackageRestrictionsLocked(userId); 695 } 696 } 697 } 698 } 699 700 @Override 701 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 702 ActivityIntentInfo filter, String packageName) { 703 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 704 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 705 Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme"); 706 return false; 707 } 708 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 709 if (ivs == null) { 710 ivs = createDomainVerificationState(verifierId, userId, verificationId, 711 packageName); 712 } 713 if (!hasValidDomains(filter)) { 714 return false; 715 } 716 ivs.addFilter(filter); 717 return true; 718 } 719 720 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 721 int userId, int verificationId, String packageName) { 722 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 723 verifierId, userId, packageName); 724 ivs.setPendingState(); 725 synchronized (mPackages) { 726 mIntentFilterVerificationStates.append(verificationId, ivs); 727 mCurrentIntentFilterVerifications.add(verificationId); 728 } 729 return ivs; 730 } 731 } 732 733 private static boolean hasValidDomains(ActivityIntentInfo filter) { 734 return hasValidDomains(filter, true); 735 } 736 737 private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) { 738 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 739 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 740 if (!hasHTTPorHTTPS) { 741 if (logging) { 742 Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme"); 743 } 744 return false; 745 } 746 return true; 747 } 748 749 private IntentFilterVerifier mIntentFilterVerifier; 750 751 // Set of pending broadcasts for aggregating enable/disable of components. 752 static class PendingPackageBroadcasts { 753 // for each user id, a map of <package name -> components within that package> 754 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 755 756 public PendingPackageBroadcasts() { 757 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 758 } 759 760 public ArrayList<String> get(int userId, String packageName) { 761 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 762 return packages.get(packageName); 763 } 764 765 public void put(int userId, String packageName, ArrayList<String> components) { 766 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 767 packages.put(packageName, components); 768 } 769 770 public void remove(int userId, String packageName) { 771 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 772 if (packages != null) { 773 packages.remove(packageName); 774 } 775 } 776 777 public void remove(int userId) { 778 mUidMap.remove(userId); 779 } 780 781 public int userIdCount() { 782 return mUidMap.size(); 783 } 784 785 public int userIdAt(int n) { 786 return mUidMap.keyAt(n); 787 } 788 789 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 790 return mUidMap.get(userId); 791 } 792 793 public int size() { 794 // total number of pending broadcast entries across all userIds 795 int num = 0; 796 for (int i = 0; i< mUidMap.size(); i++) { 797 num += mUidMap.valueAt(i).size(); 798 } 799 return num; 800 } 801 802 public void clear() { 803 mUidMap.clear(); 804 } 805 806 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 807 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 808 if (map == null) { 809 map = new ArrayMap<String, ArrayList<String>>(); 810 mUidMap.put(userId, map); 811 } 812 return map; 813 } 814 } 815 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 816 817 // Service Connection to remote media container service to copy 818 // package uri's from external media onto secure containers 819 // or internal storage. 820 private IMediaContainerService mContainerService = null; 821 822 static final int SEND_PENDING_BROADCAST = 1; 823 static final int MCS_BOUND = 3; 824 static final int END_COPY = 4; 825 static final int INIT_COPY = 5; 826 static final int MCS_UNBIND = 6; 827 static final int START_CLEANING_PACKAGE = 7; 828 static final int FIND_INSTALL_LOC = 8; 829 static final int POST_INSTALL = 9; 830 static final int MCS_RECONNECT = 10; 831 static final int MCS_GIVE_UP = 11; 832 static final int UPDATED_MEDIA_STATUS = 12; 833 static final int WRITE_SETTINGS = 13; 834 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 835 static final int PACKAGE_VERIFIED = 15; 836 static final int CHECK_PENDING_VERIFICATION = 16; 837 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 838 static final int INTENT_FILTER_VERIFIED = 18; 839 840 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 841 842 // Delay time in millisecs 843 static final int BROADCAST_DELAY = 10 * 1000; 844 845 static UserManagerService sUserManager; 846 847 // Stores a list of users whose package restrictions file needs to be updated 848 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 849 850 final private DefaultContainerConnection mDefContainerConn = 851 new DefaultContainerConnection(); 852 class DefaultContainerConnection implements ServiceConnection { 853 public void onServiceConnected(ComponentName name, IBinder service) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 855 IMediaContainerService imcs = 856 IMediaContainerService.Stub.asInterface(service); 857 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 858 } 859 860 public void onServiceDisconnected(ComponentName name) { 861 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 862 } 863 }; 864 865 // Recordkeeping of restore-after-install operations that are currently in flight 866 // between the Package Manager and the Backup Manager 867 class PostInstallData { 868 public InstallArgs args; 869 public PackageInstalledInfo res; 870 871 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 872 args = _a; 873 res = _r; 874 } 875 }; 876 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 877 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 878 879 // backup/restore of preferred activity state 880 private static final String TAG_PREFERRED_BACKUP = "pa"; 881 882 private final String mRequiredVerifierPackage; 883 884 private final PackageUsage mPackageUsage = new PackageUsage(); 885 886 private class PackageUsage { 887 private static final int WRITE_INTERVAL 888 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 889 890 private final Object mFileLock = new Object(); 891 private final AtomicLong mLastWritten = new AtomicLong(0); 892 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 893 894 private boolean mIsHistoricalPackageUsageAvailable = true; 895 896 boolean isHistoricalPackageUsageAvailable() { 897 return mIsHistoricalPackageUsageAvailable; 898 } 899 900 void write(boolean force) { 901 if (force) { 902 writeInternal(); 903 return; 904 } 905 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 906 && !DEBUG_DEXOPT) { 907 return; 908 } 909 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 910 new Thread("PackageUsage_DiskWriter") { 911 @Override 912 public void run() { 913 try { 914 writeInternal(); 915 } finally { 916 mBackgroundWriteRunning.set(false); 917 } 918 } 919 }.start(); 920 } 921 } 922 923 private void writeInternal() { 924 synchronized (mPackages) { 925 synchronized (mFileLock) { 926 AtomicFile file = getFile(); 927 FileOutputStream f = null; 928 try { 929 f = file.startWrite(); 930 BufferedOutputStream out = new BufferedOutputStream(f); 931 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 932 StringBuilder sb = new StringBuilder(); 933 for (PackageParser.Package pkg : mPackages.values()) { 934 if (pkg.mLastPackageUsageTimeInMills == 0) { 935 continue; 936 } 937 sb.setLength(0); 938 sb.append(pkg.packageName); 939 sb.append(' '); 940 sb.append((long)pkg.mLastPackageUsageTimeInMills); 941 sb.append('\n'); 942 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 943 } 944 out.flush(); 945 file.finishWrite(f); 946 } catch (IOException e) { 947 if (f != null) { 948 file.failWrite(f); 949 } 950 Log.e(TAG, "Failed to write package usage times", e); 951 } 952 } 953 } 954 mLastWritten.set(SystemClock.elapsedRealtime()); 955 } 956 957 void readLP() { 958 synchronized (mFileLock) { 959 AtomicFile file = getFile(); 960 BufferedInputStream in = null; 961 try { 962 in = new BufferedInputStream(file.openRead()); 963 StringBuffer sb = new StringBuffer(); 964 while (true) { 965 String packageName = readToken(in, sb, ' '); 966 if (packageName == null) { 967 break; 968 } 969 String timeInMillisString = readToken(in, sb, '\n'); 970 if (timeInMillisString == null) { 971 throw new IOException("Failed to find last usage time for package " 972 + packageName); 973 } 974 PackageParser.Package pkg = mPackages.get(packageName); 975 if (pkg == null) { 976 continue; 977 } 978 long timeInMillis; 979 try { 980 timeInMillis = Long.parseLong(timeInMillisString.toString()); 981 } catch (NumberFormatException e) { 982 throw new IOException("Failed to parse " + timeInMillisString 983 + " as a long.", e); 984 } 985 pkg.mLastPackageUsageTimeInMills = timeInMillis; 986 } 987 } catch (FileNotFoundException expected) { 988 mIsHistoricalPackageUsageAvailable = false; 989 } catch (IOException e) { 990 Log.w(TAG, "Failed to read package usage times", e); 991 } finally { 992 IoUtils.closeQuietly(in); 993 } 994 } 995 mLastWritten.set(SystemClock.elapsedRealtime()); 996 } 997 998 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 999 throws IOException { 1000 sb.setLength(0); 1001 while (true) { 1002 int ch = in.read(); 1003 if (ch == -1) { 1004 if (sb.length() == 0) { 1005 return null; 1006 } 1007 throw new IOException("Unexpected EOF"); 1008 } 1009 if (ch == endOfToken) { 1010 return sb.toString(); 1011 } 1012 sb.append((char)ch); 1013 } 1014 } 1015 1016 private AtomicFile getFile() { 1017 File dataDir = Environment.getDataDirectory(); 1018 File systemDir = new File(dataDir, "system"); 1019 File fname = new File(systemDir, "package-usage.list"); 1020 return new AtomicFile(fname); 1021 } 1022 } 1023 1024 class PackageHandler extends Handler { 1025 private boolean mBound = false; 1026 final ArrayList<HandlerParams> mPendingInstalls = 1027 new ArrayList<HandlerParams>(); 1028 1029 private boolean connectToService() { 1030 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1031 " DefaultContainerService"); 1032 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1033 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1034 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1035 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1036 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1037 mBound = true; 1038 return true; 1039 } 1040 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1041 return false; 1042 } 1043 1044 private void disconnectService() { 1045 mContainerService = null; 1046 mBound = false; 1047 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1048 mContext.unbindService(mDefContainerConn); 1049 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1050 } 1051 1052 PackageHandler(Looper looper) { 1053 super(looper); 1054 } 1055 1056 public void handleMessage(Message msg) { 1057 try { 1058 doHandleMessage(msg); 1059 } finally { 1060 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1061 } 1062 } 1063 1064 void doHandleMessage(Message msg) { 1065 switch (msg.what) { 1066 case INIT_COPY: { 1067 HandlerParams params = (HandlerParams) msg.obj; 1068 int idx = mPendingInstalls.size(); 1069 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1070 // If a bind was already initiated we dont really 1071 // need to do anything. The pending install 1072 // will be processed later on. 1073 if (!mBound) { 1074 // If this is the only one pending we might 1075 // have to bind to the service again. 1076 if (!connectToService()) { 1077 Slog.e(TAG, "Failed to bind to media container service"); 1078 params.serviceError(); 1079 return; 1080 } else { 1081 // Once we bind to the service, the first 1082 // pending request will be processed. 1083 mPendingInstalls.add(idx, params); 1084 } 1085 } else { 1086 mPendingInstalls.add(idx, params); 1087 // Already bound to the service. Just make 1088 // sure we trigger off processing the first request. 1089 if (idx == 0) { 1090 mHandler.sendEmptyMessage(MCS_BOUND); 1091 } 1092 } 1093 break; 1094 } 1095 case MCS_BOUND: { 1096 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1097 if (msg.obj != null) { 1098 mContainerService = (IMediaContainerService) msg.obj; 1099 } 1100 if (mContainerService == null) { 1101 // Something seriously wrong. Bail out 1102 Slog.e(TAG, "Cannot bind to media container service"); 1103 for (HandlerParams params : mPendingInstalls) { 1104 // Indicate service bind error 1105 params.serviceError(); 1106 } 1107 mPendingInstalls.clear(); 1108 } else if (mPendingInstalls.size() > 0) { 1109 HandlerParams params = mPendingInstalls.get(0); 1110 if (params != null) { 1111 if (params.startCopy()) { 1112 // We are done... look for more work or to 1113 // go idle. 1114 if (DEBUG_SD_INSTALL) Log.i(TAG, 1115 "Checking for more work or unbind..."); 1116 // Delete pending install 1117 if (mPendingInstalls.size() > 0) { 1118 mPendingInstalls.remove(0); 1119 } 1120 if (mPendingInstalls.size() == 0) { 1121 if (mBound) { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, 1123 "Posting delayed MCS_UNBIND"); 1124 removeMessages(MCS_UNBIND); 1125 Message ubmsg = obtainMessage(MCS_UNBIND); 1126 // Unbind after a little delay, to avoid 1127 // continual thrashing. 1128 sendMessageDelayed(ubmsg, 10000); 1129 } 1130 } else { 1131 // There are more pending requests in queue. 1132 // Just post MCS_BOUND message to trigger processing 1133 // of next pending install. 1134 if (DEBUG_SD_INSTALL) Log.i(TAG, 1135 "Posting MCS_BOUND for next work"); 1136 mHandler.sendEmptyMessage(MCS_BOUND); 1137 } 1138 } 1139 } 1140 } else { 1141 // Should never happen ideally. 1142 Slog.w(TAG, "Empty queue"); 1143 } 1144 break; 1145 } 1146 case MCS_RECONNECT: { 1147 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1148 if (mPendingInstalls.size() > 0) { 1149 if (mBound) { 1150 disconnectService(); 1151 } 1152 if (!connectToService()) { 1153 Slog.e(TAG, "Failed to bind to media container service"); 1154 for (HandlerParams params : mPendingInstalls) { 1155 // Indicate service bind error 1156 params.serviceError(); 1157 } 1158 mPendingInstalls.clear(); 1159 } 1160 } 1161 break; 1162 } 1163 case MCS_UNBIND: { 1164 // If there is no actual work left, then time to unbind. 1165 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1166 1167 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1168 if (mBound) { 1169 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1170 1171 disconnectService(); 1172 } 1173 } else if (mPendingInstalls.size() > 0) { 1174 // There are more pending requests in queue. 1175 // Just post MCS_BOUND message to trigger processing 1176 // of next pending install. 1177 mHandler.sendEmptyMessage(MCS_BOUND); 1178 } 1179 1180 break; 1181 } 1182 case MCS_GIVE_UP: { 1183 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1184 mPendingInstalls.remove(0); 1185 break; 1186 } 1187 case SEND_PENDING_BROADCAST: { 1188 String packages[]; 1189 ArrayList<String> components[]; 1190 int size = 0; 1191 int uids[]; 1192 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1193 synchronized (mPackages) { 1194 if (mPendingBroadcasts == null) { 1195 return; 1196 } 1197 size = mPendingBroadcasts.size(); 1198 if (size <= 0) { 1199 // Nothing to be done. Just return 1200 return; 1201 } 1202 packages = new String[size]; 1203 components = new ArrayList[size]; 1204 uids = new int[size]; 1205 int i = 0; // filling out the above arrays 1206 1207 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1208 int packageUserId = mPendingBroadcasts.userIdAt(n); 1209 Iterator<Map.Entry<String, ArrayList<String>>> it 1210 = mPendingBroadcasts.packagesForUserId(packageUserId) 1211 .entrySet().iterator(); 1212 while (it.hasNext() && i < size) { 1213 Map.Entry<String, ArrayList<String>> ent = it.next(); 1214 packages[i] = ent.getKey(); 1215 components[i] = ent.getValue(); 1216 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1217 uids[i] = (ps != null) 1218 ? UserHandle.getUid(packageUserId, ps.appId) 1219 : -1; 1220 i++; 1221 } 1222 } 1223 size = i; 1224 mPendingBroadcasts.clear(); 1225 } 1226 // Send broadcasts 1227 for (int i = 0; i < size; i++) { 1228 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1229 } 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1231 break; 1232 } 1233 case START_CLEANING_PACKAGE: { 1234 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1235 final String packageName = (String)msg.obj; 1236 final int userId = msg.arg1; 1237 final boolean andCode = msg.arg2 != 0; 1238 synchronized (mPackages) { 1239 if (userId == UserHandle.USER_ALL) { 1240 int[] users = sUserManager.getUserIds(); 1241 for (int user : users) { 1242 mSettings.addPackageToCleanLPw( 1243 new PackageCleanItem(user, packageName, andCode)); 1244 } 1245 } else { 1246 mSettings.addPackageToCleanLPw( 1247 new PackageCleanItem(userId, packageName, andCode)); 1248 } 1249 } 1250 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1251 startCleaningPackages(); 1252 } break; 1253 case POST_INSTALL: { 1254 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1255 PostInstallData data = mRunningInstalls.get(msg.arg1); 1256 mRunningInstalls.delete(msg.arg1); 1257 boolean deleteOld = false; 1258 1259 if (data != null) { 1260 InstallArgs args = data.args; 1261 PackageInstalledInfo res = data.res; 1262 1263 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1264 res.removedInfo.sendBroadcast(false, true, false); 1265 Bundle extras = new Bundle(1); 1266 extras.putInt(Intent.EXTRA_UID, res.uid); 1267 1268 // Now that we successfully installed the package, grant runtime 1269 // permissions if requested before broadcasting the install. 1270 if ((args.installFlags 1271 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1272 grantRequestedRuntimePermissions(res.pkg, 1273 args.user.getIdentifier()); 1274 } 1275 1276 // Determine the set of users who are adding this 1277 // package for the first time vs. those who are seeing 1278 // an update. 1279 int[] firstUsers; 1280 int[] updateUsers = new int[0]; 1281 if (res.origUsers == null || res.origUsers.length == 0) { 1282 firstUsers = res.newUsers; 1283 } else { 1284 firstUsers = new int[0]; 1285 for (int i=0; i<res.newUsers.length; i++) { 1286 int user = res.newUsers[i]; 1287 boolean isNew = true; 1288 for (int j=0; j<res.origUsers.length; j++) { 1289 if (res.origUsers[j] == user) { 1290 isNew = false; 1291 break; 1292 } 1293 } 1294 if (isNew) { 1295 int[] newFirst = new int[firstUsers.length+1]; 1296 System.arraycopy(firstUsers, 0, newFirst, 0, 1297 firstUsers.length); 1298 newFirst[firstUsers.length] = user; 1299 firstUsers = newFirst; 1300 } else { 1301 int[] newUpdate = new int[updateUsers.length+1]; 1302 System.arraycopy(updateUsers, 0, newUpdate, 0, 1303 updateUsers.length); 1304 newUpdate[updateUsers.length] = user; 1305 updateUsers = newUpdate; 1306 } 1307 } 1308 } 1309 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1310 res.pkg.applicationInfo.packageName, 1311 extras, null, null, firstUsers); 1312 final boolean update = res.removedInfo.removedPackage != null; 1313 if (update) { 1314 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1315 } 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, updateUsers); 1319 if (update) { 1320 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1321 res.pkg.applicationInfo.packageName, 1322 extras, null, null, updateUsers); 1323 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1324 null, null, 1325 res.pkg.applicationInfo.packageName, null, updateUsers); 1326 1327 // treat asec-hosted packages like removable media on upgrade 1328 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1329 if (DEBUG_INSTALL) { 1330 Slog.i(TAG, "upgrading pkg " + res.pkg 1331 + " is ASEC-hosted -> AVAILABLE"); 1332 } 1333 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1334 ArrayList<String> pkgList = new ArrayList<String>(1); 1335 pkgList.add(res.pkg.applicationInfo.packageName); 1336 sendResourcesChangedBroadcast(true, true, 1337 pkgList,uidArray, null); 1338 } 1339 } 1340 if (res.removedInfo.args != null) { 1341 // Remove the replaced package's older resources safely now 1342 deleteOld = true; 1343 } 1344 1345 // Log current value of "unknown sources" setting 1346 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1347 getUnknownSourcesSettings()); 1348 } 1349 // Force a gc to clear up things 1350 Runtime.getRuntime().gc(); 1351 // We delete after a gc for applications on sdcard. 1352 if (deleteOld) { 1353 synchronized (mInstallLock) { 1354 res.removedInfo.args.doPostDeleteLI(true); 1355 } 1356 } 1357 if (args.observer != null) { 1358 try { 1359 Bundle extras = extrasForInstallResult(res); 1360 args.observer.onPackageInstalled(res.name, res.returnCode, 1361 res.returnMsg, extras); 1362 } catch (RemoteException e) { 1363 Slog.i(TAG, "Observer no longer exists."); 1364 } 1365 } 1366 } else { 1367 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1368 } 1369 } break; 1370 case UPDATED_MEDIA_STATUS: { 1371 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1372 boolean reportStatus = msg.arg1 == 1; 1373 boolean doGc = msg.arg2 == 1; 1374 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1375 if (doGc) { 1376 // Force a gc to clear up stale containers. 1377 Runtime.getRuntime().gc(); 1378 } 1379 if (msg.obj != null) { 1380 @SuppressWarnings("unchecked") 1381 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1383 // Unload containers 1384 unloadAllContainers(args); 1385 } 1386 if (reportStatus) { 1387 try { 1388 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1389 PackageHelper.getMountService().finishMediaUpdate(); 1390 } catch (RemoteException e) { 1391 Log.e(TAG, "MountService not running?"); 1392 } 1393 } 1394 } break; 1395 case WRITE_SETTINGS: { 1396 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1397 synchronized (mPackages) { 1398 removeMessages(WRITE_SETTINGS); 1399 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1400 mSettings.writeLPr(); 1401 mDirtyUsers.clear(); 1402 } 1403 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1404 } break; 1405 case WRITE_PACKAGE_RESTRICTIONS: { 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1407 synchronized (mPackages) { 1408 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1409 for (int userId : mDirtyUsers) { 1410 mSettings.writePackageRestrictionsLPr(userId); 1411 } 1412 mDirtyUsers.clear(); 1413 } 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1415 } break; 1416 case CHECK_PENDING_VERIFICATION: { 1417 final int verificationId = msg.arg1; 1418 final PackageVerificationState state = mPendingVerification.get(verificationId); 1419 1420 if ((state != null) && !state.timeoutExtended()) { 1421 final InstallArgs args = state.getInstallArgs(); 1422 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1423 1424 Slog.i(TAG, "Verification timed out for " + originUri); 1425 mPendingVerification.remove(verificationId); 1426 1427 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1428 1429 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1430 Slog.i(TAG, "Continuing with installation of " + originUri); 1431 state.setVerifierResponse(Binder.getCallingUid(), 1432 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1433 broadcastPackageVerified(verificationId, originUri, 1434 PackageManager.VERIFICATION_ALLOW, 1435 state.getInstallArgs().getUser()); 1436 try { 1437 ret = args.copyApk(mContainerService, true); 1438 } catch (RemoteException e) { 1439 Slog.e(TAG, "Could not contact the ContainerService"); 1440 } 1441 } else { 1442 broadcastPackageVerified(verificationId, originUri, 1443 PackageManager.VERIFICATION_REJECT, 1444 state.getInstallArgs().getUser()); 1445 } 1446 1447 processPendingInstall(args, ret); 1448 mHandler.sendEmptyMessage(MCS_UNBIND); 1449 } 1450 break; 1451 } 1452 case PACKAGE_VERIFIED: { 1453 final int verificationId = msg.arg1; 1454 1455 final PackageVerificationState state = mPendingVerification.get(verificationId); 1456 if (state == null) { 1457 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1458 break; 1459 } 1460 1461 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1462 1463 state.setVerifierResponse(response.callerUid, response.code); 1464 1465 if (state.isVerificationComplete()) { 1466 mPendingVerification.remove(verificationId); 1467 1468 final InstallArgs args = state.getInstallArgs(); 1469 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1470 1471 int ret; 1472 if (state.isInstallAllowed()) { 1473 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1474 broadcastPackageVerified(verificationId, originUri, 1475 response.code, state.getInstallArgs().getUser()); 1476 try { 1477 ret = args.copyApk(mContainerService, true); 1478 } catch (RemoteException e) { 1479 Slog.e(TAG, "Could not contact the ContainerService"); 1480 } 1481 } else { 1482 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1483 } 1484 1485 processPendingInstall(args, ret); 1486 1487 mHandler.sendEmptyMessage(MCS_UNBIND); 1488 } 1489 1490 break; 1491 } 1492 case START_INTENT_FILTER_VERIFICATIONS: { 1493 int userId = msg.arg1; 1494 int verifierUid = msg.arg2; 1495 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1496 1497 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1498 break; 1499 } 1500 case INTENT_FILTER_VERIFIED: { 1501 final int verificationId = msg.arg1; 1502 1503 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1504 verificationId); 1505 if (state == null) { 1506 Slog.w(TAG, "Invalid IntentFilter verification token " 1507 + verificationId + " received"); 1508 break; 1509 } 1510 1511 final int userId = state.getUserId(); 1512 1513 Slog.d(TAG, "Processing IntentFilter verification with token:" 1514 + verificationId + " and userId:" + userId); 1515 1516 final IntentFilterVerificationResponse response = 1517 (IntentFilterVerificationResponse) msg.obj; 1518 1519 state.setVerifierResponse(response.callerUid, response.code); 1520 1521 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1522 + " and userId:" + userId 1523 + " is settings verifier response with response code:" 1524 + response.code); 1525 1526 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1527 Slog.d(TAG, "Domains failing verification: " 1528 + response.getFailedDomainsString()); 1529 } 1530 1531 if (state.isVerificationComplete()) { 1532 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1533 } else { 1534 Slog.d(TAG, "IntentFilter verification with token:" + verificationId 1535 + " was not said to be complete"); 1536 } 1537 1538 break; 1539 } 1540 } 1541 } 1542 } 1543 1544 private StorageEventListener mStorageListener = new StorageEventListener() { 1545 @Override 1546 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1547 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1548 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1549 // TODO: ensure that private directories exist for all active users 1550 // TODO: remove user data whose serial number doesn't match 1551 loadPrivatePackages(vol); 1552 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1553 unloadPrivatePackages(vol); 1554 } 1555 } 1556 1557 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1558 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1559 updateExternalMediaStatus(true, false); 1560 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1561 updateExternalMediaStatus(false, false); 1562 } 1563 } 1564 } 1565 1566 @Override 1567 public void onVolumeForgotten(String fsUuid) { 1568 // TODO: remove all packages hosted on this uuid 1569 } 1570 }; 1571 1572 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1573 if (userId >= UserHandle.USER_OWNER) { 1574 grantRequestedRuntimePermissionsForUser(pkg, userId); 1575 } else if (userId == UserHandle.USER_ALL) { 1576 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1577 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1578 } 1579 } 1580 } 1581 1582 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1583 SettingBase sb = (SettingBase) pkg.mExtras; 1584 if (sb == null) { 1585 return; 1586 } 1587 1588 PermissionsState permissionsState = sb.getPermissionsState(); 1589 1590 for (String permission : pkg.requestedPermissions) { 1591 BasePermission bp = mSettings.mPermissions.get(permission); 1592 if (bp != null && bp.isRuntime()) { 1593 permissionsState.grantRuntimePermission(bp, userId); 1594 } 1595 } 1596 } 1597 1598 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1599 Bundle extras = null; 1600 switch (res.returnCode) { 1601 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1602 extras = new Bundle(); 1603 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1604 res.origPermission); 1605 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1606 res.origPackage); 1607 break; 1608 } 1609 case PackageManager.INSTALL_SUCCEEDED: { 1610 extras = new Bundle(); 1611 extras.putBoolean(Intent.EXTRA_REPLACING, 1612 res.removedInfo != null && res.removedInfo.removedPackage != null); 1613 break; 1614 } 1615 } 1616 return extras; 1617 } 1618 1619 void scheduleWriteSettingsLocked() { 1620 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1621 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1622 } 1623 } 1624 1625 void scheduleWritePackageRestrictionsLocked(int userId) { 1626 if (!sUserManager.exists(userId)) return; 1627 mDirtyUsers.add(userId); 1628 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1629 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1630 } 1631 } 1632 1633 public static PackageManagerService main(Context context, Installer installer, 1634 boolean factoryTest, boolean onlyCore) { 1635 PackageManagerService m = new PackageManagerService(context, installer, 1636 factoryTest, onlyCore); 1637 ServiceManager.addService("package", m); 1638 return m; 1639 } 1640 1641 static String[] splitString(String str, char sep) { 1642 int count = 1; 1643 int i = 0; 1644 while ((i=str.indexOf(sep, i)) >= 0) { 1645 count++; 1646 i++; 1647 } 1648 1649 String[] res = new String[count]; 1650 i=0; 1651 count = 0; 1652 int lastI=0; 1653 while ((i=str.indexOf(sep, i)) >= 0) { 1654 res[count] = str.substring(lastI, i); 1655 count++; 1656 i++; 1657 lastI = i; 1658 } 1659 res[count] = str.substring(lastI, str.length()); 1660 return res; 1661 } 1662 1663 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1664 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1665 Context.DISPLAY_SERVICE); 1666 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1667 } 1668 1669 public PackageManagerService(Context context, Installer installer, 1670 boolean factoryTest, boolean onlyCore) { 1671 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1672 SystemClock.uptimeMillis()); 1673 1674 if (mSdkVersion <= 0) { 1675 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1676 } 1677 1678 mContext = context; 1679 mFactoryTest = factoryTest; 1680 mOnlyCore = onlyCore; 1681 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1682 mMetrics = new DisplayMetrics(); 1683 mSettings = new Settings(mPackages); 1684 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1685 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1686 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1687 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1688 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1689 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1690 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1691 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1692 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1693 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1694 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1695 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1696 1697 // TODO: add a property to control this? 1698 long dexOptLRUThresholdInMinutes; 1699 if (mLazyDexOpt) { 1700 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1701 } else { 1702 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1703 } 1704 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1705 1706 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1707 if (separateProcesses != null && separateProcesses.length() > 0) { 1708 if ("*".equals(separateProcesses)) { 1709 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1710 mSeparateProcesses = null; 1711 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1712 } else { 1713 mDefParseFlags = 0; 1714 mSeparateProcesses = separateProcesses.split(","); 1715 Slog.w(TAG, "Running with debug.separate_processes: " 1716 + separateProcesses); 1717 } 1718 } else { 1719 mDefParseFlags = 0; 1720 mSeparateProcesses = null; 1721 } 1722 1723 mInstaller = installer; 1724 mPackageDexOptimizer = new PackageDexOptimizer(this); 1725 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1726 1727 getDefaultDisplayMetrics(context, mMetrics); 1728 1729 SystemConfig systemConfig = SystemConfig.getInstance(); 1730 mGlobalGids = systemConfig.getGlobalGids(); 1731 mSystemPermissions = systemConfig.getSystemPermissions(); 1732 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1733 1734 synchronized (mInstallLock) { 1735 // writer 1736 synchronized (mPackages) { 1737 mHandlerThread = new ServiceThread(TAG, 1738 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1739 mHandlerThread.start(); 1740 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1741 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1742 1743 File dataDir = Environment.getDataDirectory(); 1744 mAppDataDir = new File(dataDir, "data"); 1745 mAppInstallDir = new File(dataDir, "app"); 1746 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1747 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1748 mUserAppDataDir = new File(dataDir, "user"); 1749 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1750 1751 sUserManager = new UserManagerService(context, this, 1752 mInstallLock, mPackages); 1753 1754 // Propagate permission configuration in to package manager. 1755 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1756 = systemConfig.getPermissions(); 1757 for (int i=0; i<permConfig.size(); i++) { 1758 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1759 BasePermission bp = mSettings.mPermissions.get(perm.name); 1760 if (bp == null) { 1761 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1762 mSettings.mPermissions.put(perm.name, bp); 1763 } 1764 if (perm.gids != null) { 1765 bp.setGids(perm.gids, perm.perUser); 1766 } 1767 } 1768 1769 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1770 for (int i=0; i<libConfig.size(); i++) { 1771 mSharedLibraries.put(libConfig.keyAt(i), 1772 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1773 } 1774 1775 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1776 1777 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1778 mSdkVersion, mOnlyCore); 1779 1780 String customResolverActivity = Resources.getSystem().getString( 1781 R.string.config_customResolverActivity); 1782 if (TextUtils.isEmpty(customResolverActivity)) { 1783 customResolverActivity = null; 1784 } else { 1785 mCustomResolverComponentName = ComponentName.unflattenFromString( 1786 customResolverActivity); 1787 } 1788 1789 long startTime = SystemClock.uptimeMillis(); 1790 1791 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1792 startTime); 1793 1794 // Set flag to monitor and not change apk file paths when 1795 // scanning install directories. 1796 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1797 1798 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1799 1800 /** 1801 * Add everything in the in the boot class path to the 1802 * list of process files because dexopt will have been run 1803 * if necessary during zygote startup. 1804 */ 1805 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1806 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1807 1808 if (bootClassPath != null) { 1809 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1810 for (String element : bootClassPathElements) { 1811 alreadyDexOpted.add(element); 1812 } 1813 } else { 1814 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1815 } 1816 1817 if (systemServerClassPath != null) { 1818 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1819 for (String element : systemServerClassPathElements) { 1820 alreadyDexOpted.add(element); 1821 } 1822 } else { 1823 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1824 } 1825 1826 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1827 final String[] dexCodeInstructionSets = 1828 getDexCodeInstructionSets( 1829 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1830 1831 /** 1832 * Ensure all external libraries have had dexopt run on them. 1833 */ 1834 if (mSharedLibraries.size() > 0) { 1835 // NOTE: For now, we're compiling these system "shared libraries" 1836 // (and framework jars) into all available architectures. It's possible 1837 // to compile them only when we come across an app that uses them (there's 1838 // already logic for that in scanPackageLI) but that adds some complexity. 1839 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1840 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1841 final String lib = libEntry.path; 1842 if (lib == null) { 1843 continue; 1844 } 1845 1846 try { 1847 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1848 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1849 alreadyDexOpted.add(lib); 1850 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1851 } 1852 } catch (FileNotFoundException e) { 1853 Slog.w(TAG, "Library not found: " + lib); 1854 } catch (IOException e) { 1855 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1856 + e.getMessage()); 1857 } 1858 } 1859 } 1860 } 1861 1862 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1863 1864 // Gross hack for now: we know this file doesn't contain any 1865 // code, so don't dexopt it to avoid the resulting log spew. 1866 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1867 1868 // Gross hack for now: we know this file is only part of 1869 // the boot class path for art, so don't dexopt it to 1870 // avoid the resulting log spew. 1871 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1872 1873 /** 1874 * And there are a number of commands implemented in Java, which 1875 * we currently need to do the dexopt on so that they can be 1876 * run from a non-root shell. 1877 */ 1878 String[] frameworkFiles = frameworkDir.list(); 1879 if (frameworkFiles != null) { 1880 // TODO: We could compile these only for the most preferred ABI. We should 1881 // first double check that the dex files for these commands are not referenced 1882 // by other system apps. 1883 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1884 for (int i=0; i<frameworkFiles.length; i++) { 1885 File libPath = new File(frameworkDir, frameworkFiles[i]); 1886 String path = libPath.getPath(); 1887 // Skip the file if we already did it. 1888 if (alreadyDexOpted.contains(path)) { 1889 continue; 1890 } 1891 // Skip the file if it is not a type we want to dexopt. 1892 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1893 continue; 1894 } 1895 try { 1896 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1897 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1898 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1899 } 1900 } catch (FileNotFoundException e) { 1901 Slog.w(TAG, "Jar not found: " + path); 1902 } catch (IOException e) { 1903 Slog.w(TAG, "Exception reading jar: " + path, e); 1904 } 1905 } 1906 } 1907 } 1908 1909 // Collect vendor overlay packages. 1910 // (Do this before scanning any apps.) 1911 // For security and version matching reason, only consider 1912 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1913 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1914 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1915 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1916 1917 // Find base frameworks (resource packages without code). 1918 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1919 | PackageParser.PARSE_IS_SYSTEM_DIR 1920 | PackageParser.PARSE_IS_PRIVILEGED, 1921 scanFlags | SCAN_NO_DEX, 0); 1922 1923 // Collected privileged system packages. 1924 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1925 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1926 | PackageParser.PARSE_IS_SYSTEM_DIR 1927 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1928 1929 // Collect ordinary system packages. 1930 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1931 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1933 1934 // Collect all vendor packages. 1935 File vendorAppDir = new File("/vendor/app"); 1936 try { 1937 vendorAppDir = vendorAppDir.getCanonicalFile(); 1938 } catch (IOException e) { 1939 // failed to look up canonical path, continue with original one 1940 } 1941 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1942 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1943 1944 // Collect all OEM packages. 1945 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1946 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1947 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1948 1949 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1950 mInstaller.moveFiles(); 1951 1952 // Prune any system packages that no longer exist. 1953 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1954 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1955 if (!mOnlyCore) { 1956 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1957 while (psit.hasNext()) { 1958 PackageSetting ps = psit.next(); 1959 1960 /* 1961 * If this is not a system app, it can't be a 1962 * disable system app. 1963 */ 1964 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1965 continue; 1966 } 1967 1968 /* 1969 * If the package is scanned, it's not erased. 1970 */ 1971 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1972 if (scannedPkg != null) { 1973 /* 1974 * If the system app is both scanned and in the 1975 * disabled packages list, then it must have been 1976 * added via OTA. Remove it from the currently 1977 * scanned package so the previously user-installed 1978 * application can be scanned. 1979 */ 1980 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1981 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1982 + ps.name + "; removing system app. Last known codePath=" 1983 + ps.codePathString + ", installStatus=" + ps.installStatus 1984 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1985 + scannedPkg.mVersionCode); 1986 removePackageLI(ps, true); 1987 expectingBetter.put(ps.name, ps.codePath); 1988 } 1989 1990 continue; 1991 } 1992 1993 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1994 psit.remove(); 1995 logCriticalInfo(Log.WARN, "System package " + ps.name 1996 + " no longer exists; wiping its data"); 1997 removeDataDirsLI(null, ps.name); 1998 } else { 1999 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2000 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2001 possiblyDeletedUpdatedSystemApps.add(ps.name); 2002 } 2003 } 2004 } 2005 } 2006 2007 //look for any incomplete package installations 2008 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2009 //clean up list 2010 for(int i = 0; i < deletePkgsList.size(); i++) { 2011 //clean up here 2012 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2013 } 2014 //delete tmp files 2015 deleteTempPackageFiles(); 2016 2017 // Remove any shared userIDs that have no associated packages 2018 mSettings.pruneSharedUsersLPw(); 2019 2020 if (!mOnlyCore) { 2021 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2022 SystemClock.uptimeMillis()); 2023 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2024 2025 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2026 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2027 2028 /** 2029 * Remove disable package settings for any updated system 2030 * apps that were removed via an OTA. If they're not a 2031 * previously-updated app, remove them completely. 2032 * Otherwise, just revoke their system-level permissions. 2033 */ 2034 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2035 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2036 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2037 2038 String msg; 2039 if (deletedPkg == null) { 2040 msg = "Updated system package " + deletedAppName 2041 + " no longer exists; wiping its data"; 2042 removeDataDirsLI(null, deletedAppName); 2043 } else { 2044 msg = "Updated system app + " + deletedAppName 2045 + " no longer present; removing system privileges for " 2046 + deletedAppName; 2047 2048 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2049 2050 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2051 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2052 } 2053 logCriticalInfo(Log.WARN, msg); 2054 } 2055 2056 /** 2057 * Make sure all system apps that we expected to appear on 2058 * the userdata partition actually showed up. If they never 2059 * appeared, crawl back and revive the system version. 2060 */ 2061 for (int i = 0; i < expectingBetter.size(); i++) { 2062 final String packageName = expectingBetter.keyAt(i); 2063 if (!mPackages.containsKey(packageName)) { 2064 final File scanFile = expectingBetter.valueAt(i); 2065 2066 logCriticalInfo(Log.WARN, "Expected better " + packageName 2067 + " but never showed up; reverting to system"); 2068 2069 final int reparseFlags; 2070 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2071 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2072 | PackageParser.PARSE_IS_SYSTEM_DIR 2073 | PackageParser.PARSE_IS_PRIVILEGED; 2074 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2075 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2076 | PackageParser.PARSE_IS_SYSTEM_DIR; 2077 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2078 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2079 | PackageParser.PARSE_IS_SYSTEM_DIR; 2080 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2081 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR; 2083 } else { 2084 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2085 continue; 2086 } 2087 2088 mSettings.enableSystemPackageLPw(packageName); 2089 2090 try { 2091 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2092 } catch (PackageManagerException e) { 2093 Slog.e(TAG, "Failed to parse original system package: " 2094 + e.getMessage()); 2095 } 2096 } 2097 } 2098 } 2099 2100 // Now that we know all of the shared libraries, update all clients to have 2101 // the correct library paths. 2102 updateAllSharedLibrariesLPw(); 2103 2104 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2105 // NOTE: We ignore potential failures here during a system scan (like 2106 // the rest of the commands above) because there's precious little we 2107 // can do about it. A settings error is reported, though. 2108 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2109 false /* force dexopt */, false /* defer dexopt */); 2110 } 2111 2112 // Now that we know all the packages we are keeping, 2113 // read and update their last usage times. 2114 mPackageUsage.readLP(); 2115 2116 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2117 SystemClock.uptimeMillis()); 2118 Slog.i(TAG, "Time to scan packages: " 2119 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2120 + " seconds"); 2121 2122 // If the platform SDK has changed since the last time we booted, 2123 // we need to re-grant app permission to catch any new ones that 2124 // appear. This is really a hack, and means that apps can in some 2125 // cases get permissions that the user didn't initially explicitly 2126 // allow... it would be nice to have some better way to handle 2127 // this situation. 2128 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2129 != mSdkVersion; 2130 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2131 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2132 + "; regranting permissions for internal storage"); 2133 mSettings.mInternalSdkPlatform = mSdkVersion; 2134 2135 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2136 | (regrantPermissions 2137 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2138 : 0)); 2139 2140 // If this is the first boot, and it is a normal boot, then 2141 // we need to initialize the default preferred apps. 2142 if (!mRestoredSettings && !onlyCore) { 2143 mSettings.readDefaultPreferredAppsLPw(this, 0); 2144 } 2145 2146 // If this is first boot after an OTA, and a normal boot, then 2147 // we need to clear code cache directories. 2148 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2149 if (mIsUpgrade && !onlyCore) { 2150 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2151 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2152 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2153 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2154 } 2155 mSettings.mFingerprint = Build.FINGERPRINT; 2156 } 2157 2158 primeDomainVerificationsLPw(false); 2159 checkDefaultBrowser(); 2160 2161 // All the changes are done during package scanning. 2162 mSettings.updateInternalDatabaseVersion(); 2163 2164 // can downgrade to reader 2165 mSettings.writeLPr(); 2166 2167 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2168 SystemClock.uptimeMillis()); 2169 2170 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2171 2172 mInstallerService = new PackageInstallerService(context, this); 2173 2174 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2175 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2176 mIntentFilterVerifierComponent); 2177 2178 } // synchronized (mPackages) 2179 } // synchronized (mInstallLock) 2180 2181 // Now after opening every single application zip, make sure they 2182 // are all flushed. Not really needed, but keeps things nice and 2183 // tidy. 2184 Runtime.getRuntime().gc(); 2185 } 2186 2187 @Override 2188 public boolean isFirstBoot() { 2189 return !mRestoredSettings; 2190 } 2191 2192 @Override 2193 public boolean isOnlyCoreApps() { 2194 return mOnlyCore; 2195 } 2196 2197 @Override 2198 public boolean isUpgrade() { 2199 return mIsUpgrade; 2200 } 2201 2202 private String getRequiredVerifierLPr() { 2203 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2204 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2205 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2206 2207 String requiredVerifier = null; 2208 2209 final int N = receivers.size(); 2210 for (int i = 0; i < N; i++) { 2211 final ResolveInfo info = receivers.get(i); 2212 2213 if (info.activityInfo == null) { 2214 continue; 2215 } 2216 2217 final String packageName = info.activityInfo.packageName; 2218 2219 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2220 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2221 continue; 2222 } 2223 2224 if (requiredVerifier != null) { 2225 throw new RuntimeException("There can be only one required verifier"); 2226 } 2227 2228 requiredVerifier = packageName; 2229 } 2230 2231 return requiredVerifier; 2232 } 2233 2234 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2235 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2236 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2237 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2238 2239 ComponentName verifierComponentName = null; 2240 2241 int priority = -1000; 2242 final int N = receivers.size(); 2243 for (int i = 0; i < N; i++) { 2244 final ResolveInfo info = receivers.get(i); 2245 2246 if (info.activityInfo == null) { 2247 continue; 2248 } 2249 2250 final String packageName = info.activityInfo.packageName; 2251 2252 final PackageSetting ps = mSettings.mPackages.get(packageName); 2253 if (ps == null) { 2254 continue; 2255 } 2256 2257 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2258 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2259 continue; 2260 } 2261 2262 // Select the IntentFilterVerifier with the highest priority 2263 if (priority < info.priority) { 2264 priority = info.priority; 2265 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2266 Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName + 2267 " with priority: " + info.priority); 2268 } 2269 } 2270 2271 return verifierComponentName; 2272 } 2273 2274 private void primeDomainVerificationsLPw(boolean logging) { 2275 Slog.d(TAG, "Start priming domain verifications"); 2276 boolean updated = false; 2277 ArraySet<String> allHostsSet = new ArraySet<>(); 2278 for (PackageParser.Package pkg : mPackages.values()) { 2279 final String packageName = pkg.packageName; 2280 if (!hasDomainURLs(pkg)) { 2281 if (logging) { 2282 Slog.d(TAG, "No priming domain verifications for " + 2283 "package with no domain URLs: " + packageName); 2284 } 2285 continue; 2286 } 2287 if (!pkg.isSystemApp()) { 2288 if (logging) { 2289 Slog.d(TAG, "No priming domain verifications for a non system package : " + 2290 packageName); 2291 } 2292 continue; 2293 } 2294 for (PackageParser.Activity a : pkg.activities) { 2295 for (ActivityIntentInfo filter : a.intents) { 2296 if (hasValidDomains(filter, false)) { 2297 allHostsSet.addAll(filter.getHostsList()); 2298 } 2299 } 2300 } 2301 if (allHostsSet.size() == 0) { 2302 allHostsSet.add("*"); 2303 } 2304 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2305 IntentFilterVerificationInfo ivi = 2306 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2307 if (ivi != null) { 2308 // We will always log this 2309 Slog.d(TAG, "Priming domain verifications for package: " + packageName + 2310 " with hosts:" + ivi.getDomainsString()); 2311 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2312 updated = true; 2313 } 2314 else { 2315 if (logging) { 2316 Slog.d(TAG, "No priming domain verifications for package: " + packageName); 2317 } 2318 } 2319 allHostsSet.clear(); 2320 } 2321 if (updated) { 2322 if (logging) { 2323 Slog.d(TAG, "Will need to write primed domain verifications"); 2324 } 2325 } 2326 Slog.d(TAG, "End priming domain verifications"); 2327 } 2328 2329 private void checkDefaultBrowser() { 2330 final int myUserId = UserHandle.myUserId(); 2331 final String packageName = getDefaultBrowserPackageName(myUserId); 2332 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2333 if (info == null) { 2334 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2335 packageName); 2336 setDefaultBrowserPackageName(null, myUserId); 2337 } 2338 } 2339 2340 @Override 2341 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2342 throws RemoteException { 2343 try { 2344 return super.onTransact(code, data, reply, flags); 2345 } catch (RuntimeException e) { 2346 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2347 Slog.wtf(TAG, "Package Manager Crash", e); 2348 } 2349 throw e; 2350 } 2351 } 2352 2353 void cleanupInstallFailedPackage(PackageSetting ps) { 2354 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2355 2356 removeDataDirsLI(ps.volumeUuid, ps.name); 2357 if (ps.codePath != null) { 2358 if (ps.codePath.isDirectory()) { 2359 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2360 } else { 2361 ps.codePath.delete(); 2362 } 2363 } 2364 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2365 if (ps.resourcePath.isDirectory()) { 2366 FileUtils.deleteContents(ps.resourcePath); 2367 } 2368 ps.resourcePath.delete(); 2369 } 2370 mSettings.removePackageLPw(ps.name); 2371 } 2372 2373 static int[] appendInts(int[] cur, int[] add) { 2374 if (add == null) return cur; 2375 if (cur == null) return add; 2376 final int N = add.length; 2377 for (int i=0; i<N; i++) { 2378 cur = appendInt(cur, add[i]); 2379 } 2380 return cur; 2381 } 2382 2383 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2384 if (!sUserManager.exists(userId)) return null; 2385 final PackageSetting ps = (PackageSetting) p.mExtras; 2386 if (ps == null) { 2387 return null; 2388 } 2389 2390 final PermissionsState permissionsState = ps.getPermissionsState(); 2391 2392 final int[] gids = permissionsState.computeGids(userId); 2393 final Set<String> permissions = permissionsState.getPermissions(userId); 2394 final PackageUserState state = ps.readUserState(userId); 2395 2396 return PackageParser.generatePackageInfo(p, gids, flags, 2397 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2398 } 2399 2400 @Override 2401 public boolean isPackageFrozen(String packageName) { 2402 synchronized (mPackages) { 2403 final PackageSetting ps = mSettings.mPackages.get(packageName); 2404 if (ps != null) { 2405 return ps.frozen; 2406 } 2407 } 2408 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2409 return true; 2410 } 2411 2412 @Override 2413 public boolean isPackageAvailable(String packageName, int userId) { 2414 if (!sUserManager.exists(userId)) return false; 2415 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2416 synchronized (mPackages) { 2417 PackageParser.Package p = mPackages.get(packageName); 2418 if (p != null) { 2419 final PackageSetting ps = (PackageSetting) p.mExtras; 2420 if (ps != null) { 2421 final PackageUserState state = ps.readUserState(userId); 2422 if (state != null) { 2423 return PackageParser.isAvailable(state); 2424 } 2425 } 2426 } 2427 } 2428 return false; 2429 } 2430 2431 @Override 2432 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2433 if (!sUserManager.exists(userId)) return null; 2434 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2435 // reader 2436 synchronized (mPackages) { 2437 PackageParser.Package p = mPackages.get(packageName); 2438 if (DEBUG_PACKAGE_INFO) 2439 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2440 if (p != null) { 2441 return generatePackageInfo(p, flags, userId); 2442 } 2443 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2444 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2445 } 2446 } 2447 return null; 2448 } 2449 2450 @Override 2451 public String[] currentToCanonicalPackageNames(String[] names) { 2452 String[] out = new String[names.length]; 2453 // reader 2454 synchronized (mPackages) { 2455 for (int i=names.length-1; i>=0; i--) { 2456 PackageSetting ps = mSettings.mPackages.get(names[i]); 2457 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2458 } 2459 } 2460 return out; 2461 } 2462 2463 @Override 2464 public String[] canonicalToCurrentPackageNames(String[] names) { 2465 String[] out = new String[names.length]; 2466 // reader 2467 synchronized (mPackages) { 2468 for (int i=names.length-1; i>=0; i--) { 2469 String cur = mSettings.mRenamedPackages.get(names[i]); 2470 out[i] = cur != null ? cur : names[i]; 2471 } 2472 } 2473 return out; 2474 } 2475 2476 @Override 2477 public int getPackageUid(String packageName, int userId) { 2478 if (!sUserManager.exists(userId)) return -1; 2479 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2480 2481 // reader 2482 synchronized (mPackages) { 2483 PackageParser.Package p = mPackages.get(packageName); 2484 if(p != null) { 2485 return UserHandle.getUid(userId, p.applicationInfo.uid); 2486 } 2487 PackageSetting ps = mSettings.mPackages.get(packageName); 2488 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2489 return -1; 2490 } 2491 p = ps.pkg; 2492 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2493 } 2494 } 2495 2496 @Override 2497 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2498 if (!sUserManager.exists(userId)) { 2499 return null; 2500 } 2501 2502 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2503 "getPackageGids"); 2504 2505 // reader 2506 synchronized (mPackages) { 2507 PackageParser.Package p = mPackages.get(packageName); 2508 if (DEBUG_PACKAGE_INFO) { 2509 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2510 } 2511 if (p != null) { 2512 PackageSetting ps = (PackageSetting) p.mExtras; 2513 return ps.getPermissionsState().computeGids(userId); 2514 } 2515 } 2516 2517 return null; 2518 } 2519 2520 static PermissionInfo generatePermissionInfo( 2521 BasePermission bp, int flags) { 2522 if (bp.perm != null) { 2523 return PackageParser.generatePermissionInfo(bp.perm, flags); 2524 } 2525 PermissionInfo pi = new PermissionInfo(); 2526 pi.name = bp.name; 2527 pi.packageName = bp.sourcePackage; 2528 pi.nonLocalizedLabel = bp.name; 2529 pi.protectionLevel = bp.protectionLevel; 2530 return pi; 2531 } 2532 2533 @Override 2534 public PermissionInfo getPermissionInfo(String name, int flags) { 2535 // reader 2536 synchronized (mPackages) { 2537 final BasePermission p = mSettings.mPermissions.get(name); 2538 if (p != null) { 2539 return generatePermissionInfo(p, flags); 2540 } 2541 return null; 2542 } 2543 } 2544 2545 @Override 2546 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2547 // reader 2548 synchronized (mPackages) { 2549 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2550 for (BasePermission p : mSettings.mPermissions.values()) { 2551 if (group == null) { 2552 if (p.perm == null || p.perm.info.group == null) { 2553 out.add(generatePermissionInfo(p, flags)); 2554 } 2555 } else { 2556 if (p.perm != null && group.equals(p.perm.info.group)) { 2557 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2558 } 2559 } 2560 } 2561 2562 if (out.size() > 0) { 2563 return out; 2564 } 2565 return mPermissionGroups.containsKey(group) ? out : null; 2566 } 2567 } 2568 2569 @Override 2570 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2571 // reader 2572 synchronized (mPackages) { 2573 return PackageParser.generatePermissionGroupInfo( 2574 mPermissionGroups.get(name), flags); 2575 } 2576 } 2577 2578 @Override 2579 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2580 // reader 2581 synchronized (mPackages) { 2582 final int N = mPermissionGroups.size(); 2583 ArrayList<PermissionGroupInfo> out 2584 = new ArrayList<PermissionGroupInfo>(N); 2585 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2586 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2587 } 2588 return out; 2589 } 2590 } 2591 2592 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2593 int userId) { 2594 if (!sUserManager.exists(userId)) return null; 2595 PackageSetting ps = mSettings.mPackages.get(packageName); 2596 if (ps != null) { 2597 if (ps.pkg == null) { 2598 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2599 flags, userId); 2600 if (pInfo != null) { 2601 return pInfo.applicationInfo; 2602 } 2603 return null; 2604 } 2605 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2606 ps.readUserState(userId), userId); 2607 } 2608 return null; 2609 } 2610 2611 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2612 int userId) { 2613 if (!sUserManager.exists(userId)) return null; 2614 PackageSetting ps = mSettings.mPackages.get(packageName); 2615 if (ps != null) { 2616 PackageParser.Package pkg = ps.pkg; 2617 if (pkg == null) { 2618 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2619 return null; 2620 } 2621 // Only data remains, so we aren't worried about code paths 2622 pkg = new PackageParser.Package(packageName); 2623 pkg.applicationInfo.packageName = packageName; 2624 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2625 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2626 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2627 packageName, userId).getAbsolutePath(); 2628 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2629 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2630 } 2631 return generatePackageInfo(pkg, flags, userId); 2632 } 2633 return null; 2634 } 2635 2636 @Override 2637 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2638 if (!sUserManager.exists(userId)) return null; 2639 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2640 // writer 2641 synchronized (mPackages) { 2642 PackageParser.Package p = mPackages.get(packageName); 2643 if (DEBUG_PACKAGE_INFO) Log.v( 2644 TAG, "getApplicationInfo " + packageName 2645 + ": " + p); 2646 if (p != null) { 2647 PackageSetting ps = mSettings.mPackages.get(packageName); 2648 if (ps == null) return null; 2649 // Note: isEnabledLP() does not apply here - always return info 2650 return PackageParser.generateApplicationInfo( 2651 p, flags, ps.readUserState(userId), userId); 2652 } 2653 if ("android".equals(packageName)||"system".equals(packageName)) { 2654 return mAndroidApplication; 2655 } 2656 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2657 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2658 } 2659 } 2660 return null; 2661 } 2662 2663 @Override 2664 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2665 final IPackageDataObserver observer) { 2666 mContext.enforceCallingOrSelfPermission( 2667 android.Manifest.permission.CLEAR_APP_CACHE, null); 2668 // Queue up an async operation since clearing cache may take a little while. 2669 mHandler.post(new Runnable() { 2670 public void run() { 2671 mHandler.removeCallbacks(this); 2672 int retCode = -1; 2673 synchronized (mInstallLock) { 2674 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2675 if (retCode < 0) { 2676 Slog.w(TAG, "Couldn't clear application caches"); 2677 } 2678 } 2679 if (observer != null) { 2680 try { 2681 observer.onRemoveCompleted(null, (retCode >= 0)); 2682 } catch (RemoteException e) { 2683 Slog.w(TAG, "RemoveException when invoking call back"); 2684 } 2685 } 2686 } 2687 }); 2688 } 2689 2690 @Override 2691 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2692 final IntentSender pi) { 2693 mContext.enforceCallingOrSelfPermission( 2694 android.Manifest.permission.CLEAR_APP_CACHE, null); 2695 // Queue up an async operation since clearing cache may take a little while. 2696 mHandler.post(new Runnable() { 2697 public void run() { 2698 mHandler.removeCallbacks(this); 2699 int retCode = -1; 2700 synchronized (mInstallLock) { 2701 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2702 if (retCode < 0) { 2703 Slog.w(TAG, "Couldn't clear application caches"); 2704 } 2705 } 2706 if(pi != null) { 2707 try { 2708 // Callback via pending intent 2709 int code = (retCode >= 0) ? 1 : 0; 2710 pi.sendIntent(null, code, null, 2711 null, null); 2712 } catch (SendIntentException e1) { 2713 Slog.i(TAG, "Failed to send pending intent"); 2714 } 2715 } 2716 } 2717 }); 2718 } 2719 2720 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2721 synchronized (mInstallLock) { 2722 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2723 throw new IOException("Failed to free enough space"); 2724 } 2725 } 2726 } 2727 2728 @Override 2729 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2730 if (!sUserManager.exists(userId)) return null; 2731 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2732 synchronized (mPackages) { 2733 PackageParser.Activity a = mActivities.mActivities.get(component); 2734 2735 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2736 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2737 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2738 if (ps == null) return null; 2739 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2740 userId); 2741 } 2742 if (mResolveComponentName.equals(component)) { 2743 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2744 new PackageUserState(), userId); 2745 } 2746 } 2747 return null; 2748 } 2749 2750 @Override 2751 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2752 String resolvedType) { 2753 synchronized (mPackages) { 2754 PackageParser.Activity a = mActivities.mActivities.get(component); 2755 if (a == null) { 2756 return false; 2757 } 2758 for (int i=0; i<a.intents.size(); i++) { 2759 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2760 intent.getData(), intent.getCategories(), TAG) >= 0) { 2761 return true; 2762 } 2763 } 2764 return false; 2765 } 2766 } 2767 2768 @Override 2769 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2770 if (!sUserManager.exists(userId)) return null; 2771 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2772 synchronized (mPackages) { 2773 PackageParser.Activity a = mReceivers.mActivities.get(component); 2774 if (DEBUG_PACKAGE_INFO) Log.v( 2775 TAG, "getReceiverInfo " + component + ": " + a); 2776 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2777 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2778 if (ps == null) return null; 2779 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2780 userId); 2781 } 2782 } 2783 return null; 2784 } 2785 2786 @Override 2787 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2788 if (!sUserManager.exists(userId)) return null; 2789 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2790 synchronized (mPackages) { 2791 PackageParser.Service s = mServices.mServices.get(component); 2792 if (DEBUG_PACKAGE_INFO) Log.v( 2793 TAG, "getServiceInfo " + component + ": " + s); 2794 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2795 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2796 if (ps == null) return null; 2797 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2798 userId); 2799 } 2800 } 2801 return null; 2802 } 2803 2804 @Override 2805 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2806 if (!sUserManager.exists(userId)) return null; 2807 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2808 synchronized (mPackages) { 2809 PackageParser.Provider p = mProviders.mProviders.get(component); 2810 if (DEBUG_PACKAGE_INFO) Log.v( 2811 TAG, "getProviderInfo " + component + ": " + p); 2812 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2813 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2814 if (ps == null) return null; 2815 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2816 userId); 2817 } 2818 } 2819 return null; 2820 } 2821 2822 @Override 2823 public String[] getSystemSharedLibraryNames() { 2824 Set<String> libSet; 2825 synchronized (mPackages) { 2826 libSet = mSharedLibraries.keySet(); 2827 int size = libSet.size(); 2828 if (size > 0) { 2829 String[] libs = new String[size]; 2830 libSet.toArray(libs); 2831 return libs; 2832 } 2833 } 2834 return null; 2835 } 2836 2837 /** 2838 * @hide 2839 */ 2840 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2841 synchronized (mPackages) { 2842 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2843 if (lib != null && lib.apk != null) { 2844 return mPackages.get(lib.apk); 2845 } 2846 } 2847 return null; 2848 } 2849 2850 @Override 2851 public FeatureInfo[] getSystemAvailableFeatures() { 2852 Collection<FeatureInfo> featSet; 2853 synchronized (mPackages) { 2854 featSet = mAvailableFeatures.values(); 2855 int size = featSet.size(); 2856 if (size > 0) { 2857 FeatureInfo[] features = new FeatureInfo[size+1]; 2858 featSet.toArray(features); 2859 FeatureInfo fi = new FeatureInfo(); 2860 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2861 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2862 features[size] = fi; 2863 return features; 2864 } 2865 } 2866 return null; 2867 } 2868 2869 @Override 2870 public boolean hasSystemFeature(String name) { 2871 synchronized (mPackages) { 2872 return mAvailableFeatures.containsKey(name); 2873 } 2874 } 2875 2876 private void checkValidCaller(int uid, int userId) { 2877 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2878 return; 2879 2880 throw new SecurityException("Caller uid=" + uid 2881 + " is not privileged to communicate with user=" + userId); 2882 } 2883 2884 @Override 2885 public int checkPermission(String permName, String pkgName, int userId) { 2886 if (!sUserManager.exists(userId)) { 2887 return PackageManager.PERMISSION_DENIED; 2888 } 2889 2890 synchronized (mPackages) { 2891 final PackageParser.Package p = mPackages.get(pkgName); 2892 if (p != null && p.mExtras != null) { 2893 final PackageSetting ps = (PackageSetting) p.mExtras; 2894 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2895 return PackageManager.PERMISSION_GRANTED; 2896 } 2897 } 2898 } 2899 2900 return PackageManager.PERMISSION_DENIED; 2901 } 2902 2903 @Override 2904 public int checkUidPermission(String permName, int uid) { 2905 final int userId = UserHandle.getUserId(uid); 2906 2907 if (!sUserManager.exists(userId)) { 2908 return PackageManager.PERMISSION_DENIED; 2909 } 2910 2911 synchronized (mPackages) { 2912 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2913 if (obj != null) { 2914 final SettingBase ps = (SettingBase) obj; 2915 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2916 return PackageManager.PERMISSION_GRANTED; 2917 } 2918 } else { 2919 ArraySet<String> perms = mSystemPermissions.get(uid); 2920 if (perms != null && perms.contains(permName)) { 2921 return PackageManager.PERMISSION_GRANTED; 2922 } 2923 } 2924 } 2925 2926 return PackageManager.PERMISSION_DENIED; 2927 } 2928 2929 /** 2930 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2931 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2932 * @param checkShell TODO(yamasani): 2933 * @param message the message to log on security exception 2934 */ 2935 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2936 boolean checkShell, String message) { 2937 if (userId < 0) { 2938 throw new IllegalArgumentException("Invalid userId " + userId); 2939 } 2940 if (checkShell) { 2941 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2942 } 2943 if (userId == UserHandle.getUserId(callingUid)) return; 2944 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2945 if (requireFullPermission) { 2946 mContext.enforceCallingOrSelfPermission( 2947 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2948 } else { 2949 try { 2950 mContext.enforceCallingOrSelfPermission( 2951 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2952 } catch (SecurityException se) { 2953 mContext.enforceCallingOrSelfPermission( 2954 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2955 } 2956 } 2957 } 2958 } 2959 2960 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2961 if (callingUid == Process.SHELL_UID) { 2962 if (userHandle >= 0 2963 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2964 throw new SecurityException("Shell does not have permission to access user " 2965 + userHandle); 2966 } else if (userHandle < 0) { 2967 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2968 + Debug.getCallers(3)); 2969 } 2970 } 2971 } 2972 2973 private BasePermission findPermissionTreeLP(String permName) { 2974 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2975 if (permName.startsWith(bp.name) && 2976 permName.length() > bp.name.length() && 2977 permName.charAt(bp.name.length()) == '.') { 2978 return bp; 2979 } 2980 } 2981 return null; 2982 } 2983 2984 private BasePermission checkPermissionTreeLP(String permName) { 2985 if (permName != null) { 2986 BasePermission bp = findPermissionTreeLP(permName); 2987 if (bp != null) { 2988 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2989 return bp; 2990 } 2991 throw new SecurityException("Calling uid " 2992 + Binder.getCallingUid() 2993 + " is not allowed to add to permission tree " 2994 + bp.name + " owned by uid " + bp.uid); 2995 } 2996 } 2997 throw new SecurityException("No permission tree found for " + permName); 2998 } 2999 3000 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3001 if (s1 == null) { 3002 return s2 == null; 3003 } 3004 if (s2 == null) { 3005 return false; 3006 } 3007 if (s1.getClass() != s2.getClass()) { 3008 return false; 3009 } 3010 return s1.equals(s2); 3011 } 3012 3013 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3014 if (pi1.icon != pi2.icon) return false; 3015 if (pi1.logo != pi2.logo) return false; 3016 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3017 if (!compareStrings(pi1.name, pi2.name)) return false; 3018 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3019 // We'll take care of setting this one. 3020 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3021 // These are not currently stored in settings. 3022 //if (!compareStrings(pi1.group, pi2.group)) return false; 3023 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3024 //if (pi1.labelRes != pi2.labelRes) return false; 3025 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3026 return true; 3027 } 3028 3029 int permissionInfoFootprint(PermissionInfo info) { 3030 int size = info.name.length(); 3031 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3032 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3033 return size; 3034 } 3035 3036 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3037 int size = 0; 3038 for (BasePermission perm : mSettings.mPermissions.values()) { 3039 if (perm.uid == tree.uid) { 3040 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3041 } 3042 } 3043 return size; 3044 } 3045 3046 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3047 // We calculate the max size of permissions defined by this uid and throw 3048 // if that plus the size of 'info' would exceed our stated maximum. 3049 if (tree.uid != Process.SYSTEM_UID) { 3050 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3051 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3052 throw new SecurityException("Permission tree size cap exceeded"); 3053 } 3054 } 3055 } 3056 3057 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3058 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3059 throw new SecurityException("Label must be specified in permission"); 3060 } 3061 BasePermission tree = checkPermissionTreeLP(info.name); 3062 BasePermission bp = mSettings.mPermissions.get(info.name); 3063 boolean added = bp == null; 3064 boolean changed = true; 3065 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3066 if (added) { 3067 enforcePermissionCapLocked(info, tree); 3068 bp = new BasePermission(info.name, tree.sourcePackage, 3069 BasePermission.TYPE_DYNAMIC); 3070 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3071 throw new SecurityException( 3072 "Not allowed to modify non-dynamic permission " 3073 + info.name); 3074 } else { 3075 if (bp.protectionLevel == fixedLevel 3076 && bp.perm.owner.equals(tree.perm.owner) 3077 && bp.uid == tree.uid 3078 && comparePermissionInfos(bp.perm.info, info)) { 3079 changed = false; 3080 } 3081 } 3082 bp.protectionLevel = fixedLevel; 3083 info = new PermissionInfo(info); 3084 info.protectionLevel = fixedLevel; 3085 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3086 bp.perm.info.packageName = tree.perm.info.packageName; 3087 bp.uid = tree.uid; 3088 if (added) { 3089 mSettings.mPermissions.put(info.name, bp); 3090 } 3091 if (changed) { 3092 if (!async) { 3093 mSettings.writeLPr(); 3094 } else { 3095 scheduleWriteSettingsLocked(); 3096 } 3097 } 3098 return added; 3099 } 3100 3101 @Override 3102 public boolean addPermission(PermissionInfo info) { 3103 synchronized (mPackages) { 3104 return addPermissionLocked(info, false); 3105 } 3106 } 3107 3108 @Override 3109 public boolean addPermissionAsync(PermissionInfo info) { 3110 synchronized (mPackages) { 3111 return addPermissionLocked(info, true); 3112 } 3113 } 3114 3115 @Override 3116 public void removePermission(String name) { 3117 synchronized (mPackages) { 3118 checkPermissionTreeLP(name); 3119 BasePermission bp = mSettings.mPermissions.get(name); 3120 if (bp != null) { 3121 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3122 throw new SecurityException( 3123 "Not allowed to modify non-dynamic permission " 3124 + name); 3125 } 3126 mSettings.mPermissions.remove(name); 3127 mSettings.writeLPr(); 3128 } 3129 } 3130 } 3131 3132 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3133 BasePermission bp) { 3134 int index = pkg.requestedPermissions.indexOf(bp.name); 3135 if (index == -1) { 3136 throw new SecurityException("Package " + pkg.packageName 3137 + " has not requested permission " + bp.name); 3138 } 3139 if (!bp.isRuntime()) { 3140 throw new SecurityException("Permission " + bp.name 3141 + " is not a changeable permission type"); 3142 } 3143 } 3144 3145 private static void enforceOnlySystemUpdatesPermissionPolicyFlags(int flagMask, int flagValues) { 3146 if (((flagMask & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0 3147 || (flagValues & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) 3148 && getCallingUid() != Process.SYSTEM_UID) { 3149 throw new SecurityException("Only the system can modify policy flags"); 3150 } 3151 } 3152 3153 @Override 3154 public void grantRuntimePermission(String packageName, String name, int userId) { 3155 if (!sUserManager.exists(userId)) { 3156 return; 3157 } 3158 3159 mContext.enforceCallingOrSelfPermission( 3160 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3161 "grantRuntimePermission"); 3162 3163 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3164 "grantRuntimePermission"); 3165 3166 boolean gidsChanged = false; 3167 final SettingBase sb; 3168 3169 synchronized (mPackages) { 3170 final PackageParser.Package pkg = mPackages.get(packageName); 3171 if (pkg == null) { 3172 throw new IllegalArgumentException("Unknown package: " + packageName); 3173 } 3174 3175 final BasePermission bp = mSettings.mPermissions.get(name); 3176 if (bp == null) { 3177 throw new IllegalArgumentException("Unknown permission: " + name); 3178 } 3179 3180 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3181 3182 sb = (SettingBase) pkg.mExtras; 3183 if (sb == null) { 3184 throw new IllegalArgumentException("Unknown package: " + packageName); 3185 } 3186 3187 final PermissionsState permissionsState = sb.getPermissionsState(); 3188 3189 final int result = permissionsState.grantRuntimePermission(bp, userId); 3190 switch (result) { 3191 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3192 return; 3193 } 3194 3195 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3196 gidsChanged = true; 3197 } 3198 break; 3199 } 3200 3201 // Not critical if that is lost - app has to request again. 3202 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3203 } 3204 3205 if (gidsChanged) { 3206 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3207 } 3208 } 3209 3210 @Override 3211 public void revokeRuntimePermission(String packageName, String name, int userId) { 3212 if (!sUserManager.exists(userId)) { 3213 return; 3214 } 3215 3216 mContext.enforceCallingOrSelfPermission( 3217 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3218 "revokeRuntimePermission"); 3219 3220 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3221 "revokeRuntimePermission"); 3222 3223 final SettingBase sb; 3224 3225 synchronized (mPackages) { 3226 final PackageParser.Package pkg = mPackages.get(packageName); 3227 if (pkg == null) { 3228 throw new IllegalArgumentException("Unknown package: " + packageName); 3229 } 3230 3231 final BasePermission bp = mSettings.mPermissions.get(name); 3232 if (bp == null) { 3233 throw new IllegalArgumentException("Unknown permission: " + name); 3234 } 3235 3236 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3237 3238 sb = (SettingBase) pkg.mExtras; 3239 if (sb == null) { 3240 throw new IllegalArgumentException("Unknown package: " + packageName); 3241 } 3242 3243 final PermissionsState permissionsState = sb.getPermissionsState(); 3244 3245 if (permissionsState.revokeRuntimePermission(bp, userId) == 3246 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3247 return; 3248 } 3249 3250 // Critical, after this call app should never have the permission. 3251 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3252 } 3253 3254 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3255 } 3256 3257 @Override 3258 public int getPermissionFlags(String name, String packageName, int userId) { 3259 if (!sUserManager.exists(userId)) { 3260 return 0; 3261 } 3262 3263 mContext.enforceCallingOrSelfPermission( 3264 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3265 "getPermissionFlags"); 3266 3267 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3268 "getPermissionFlags"); 3269 3270 synchronized (mPackages) { 3271 final PackageParser.Package pkg = mPackages.get(packageName); 3272 if (pkg == null) { 3273 throw new IllegalArgumentException("Unknown package: " + packageName); 3274 } 3275 3276 final BasePermission bp = mSettings.mPermissions.get(name); 3277 if (bp == null) { 3278 throw new IllegalArgumentException("Unknown permission: " + name); 3279 } 3280 3281 SettingBase sb = (SettingBase) pkg.mExtras; 3282 if (sb == null) { 3283 throw new IllegalArgumentException("Unknown package: " + packageName); 3284 } 3285 3286 PermissionsState permissionsState = sb.getPermissionsState(); 3287 return permissionsState.getPermissionFlags(name, userId); 3288 } 3289 } 3290 3291 @Override 3292 public void updatePermissionFlags(String name, String packageName, int flagMask, 3293 int flagValues, int userId) { 3294 if (!sUserManager.exists(userId)) { 3295 return; 3296 } 3297 3298 mContext.enforceCallingOrSelfPermission( 3299 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3300 "updatePermissionFlags"); 3301 3302 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3303 "updatePermissionFlags"); 3304 3305 enforceOnlySystemUpdatesPermissionPolicyFlags(flagMask, flagValues); 3306 3307 synchronized (mPackages) { 3308 final PackageParser.Package pkg = mPackages.get(packageName); 3309 if (pkg == null) { 3310 throw new IllegalArgumentException("Unknown package: " + packageName); 3311 } 3312 3313 final BasePermission bp = mSettings.mPermissions.get(name); 3314 if (bp == null) { 3315 throw new IllegalArgumentException("Unknown permission: " + name); 3316 } 3317 3318 SettingBase sb = (SettingBase) pkg.mExtras; 3319 if (sb == null) { 3320 throw new IllegalArgumentException("Unknown package: " + packageName); 3321 } 3322 3323 PermissionsState permissionsState = sb.getPermissionsState(); 3324 3325 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3326 // Install and runtime permissions are stored in different places, 3327 // so figure out what permission changed and persist the change. 3328 if (permissionsState.getInstallPermissionState(name) != null) { 3329 scheduleWriteSettingsLocked(); 3330 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3331 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3332 } 3333 } 3334 } 3335 } 3336 3337 @Override 3338 public boolean isProtectedBroadcast(String actionName) { 3339 synchronized (mPackages) { 3340 return mProtectedBroadcasts.contains(actionName); 3341 } 3342 } 3343 3344 @Override 3345 public int checkSignatures(String pkg1, String pkg2) { 3346 synchronized (mPackages) { 3347 final PackageParser.Package p1 = mPackages.get(pkg1); 3348 final PackageParser.Package p2 = mPackages.get(pkg2); 3349 if (p1 == null || p1.mExtras == null 3350 || p2 == null || p2.mExtras == null) { 3351 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3352 } 3353 return compareSignatures(p1.mSignatures, p2.mSignatures); 3354 } 3355 } 3356 3357 @Override 3358 public int checkUidSignatures(int uid1, int uid2) { 3359 // Map to base uids. 3360 uid1 = UserHandle.getAppId(uid1); 3361 uid2 = UserHandle.getAppId(uid2); 3362 // reader 3363 synchronized (mPackages) { 3364 Signature[] s1; 3365 Signature[] s2; 3366 Object obj = mSettings.getUserIdLPr(uid1); 3367 if (obj != null) { 3368 if (obj instanceof SharedUserSetting) { 3369 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3370 } else if (obj instanceof PackageSetting) { 3371 s1 = ((PackageSetting)obj).signatures.mSignatures; 3372 } else { 3373 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3374 } 3375 } else { 3376 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3377 } 3378 obj = mSettings.getUserIdLPr(uid2); 3379 if (obj != null) { 3380 if (obj instanceof SharedUserSetting) { 3381 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3382 } else if (obj instanceof PackageSetting) { 3383 s2 = ((PackageSetting)obj).signatures.mSignatures; 3384 } else { 3385 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3386 } 3387 } else { 3388 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3389 } 3390 return compareSignatures(s1, s2); 3391 } 3392 } 3393 3394 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3395 final long identity = Binder.clearCallingIdentity(); 3396 try { 3397 if (sb instanceof SharedUserSetting) { 3398 SharedUserSetting sus = (SharedUserSetting) sb; 3399 final int packageCount = sus.packages.size(); 3400 for (int i = 0; i < packageCount; i++) { 3401 PackageSetting susPs = sus.packages.valueAt(i); 3402 if (userId == UserHandle.USER_ALL) { 3403 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3404 } else { 3405 final int uid = UserHandle.getUid(userId, susPs.appId); 3406 killUid(uid, reason); 3407 } 3408 } 3409 } else if (sb instanceof PackageSetting) { 3410 PackageSetting ps = (PackageSetting) sb; 3411 if (userId == UserHandle.USER_ALL) { 3412 killApplication(ps.pkg.packageName, ps.appId, reason); 3413 } else { 3414 final int uid = UserHandle.getUid(userId, ps.appId); 3415 killUid(uid, reason); 3416 } 3417 } 3418 } finally { 3419 Binder.restoreCallingIdentity(identity); 3420 } 3421 } 3422 3423 private static void killUid(int uid, String reason) { 3424 IActivityManager am = ActivityManagerNative.getDefault(); 3425 if (am != null) { 3426 try { 3427 am.killUid(uid, reason); 3428 } catch (RemoteException e) { 3429 /* ignore - same process */ 3430 } 3431 } 3432 } 3433 3434 /** 3435 * Compares two sets of signatures. Returns: 3436 * <br /> 3437 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3438 * <br /> 3439 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3440 * <br /> 3441 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3442 * <br /> 3443 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3444 * <br /> 3445 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3446 */ 3447 static int compareSignatures(Signature[] s1, Signature[] s2) { 3448 if (s1 == null) { 3449 return s2 == null 3450 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3451 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3452 } 3453 3454 if (s2 == null) { 3455 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3456 } 3457 3458 if (s1.length != s2.length) { 3459 return PackageManager.SIGNATURE_NO_MATCH; 3460 } 3461 3462 // Since both signature sets are of size 1, we can compare without HashSets. 3463 if (s1.length == 1) { 3464 return s1[0].equals(s2[0]) ? 3465 PackageManager.SIGNATURE_MATCH : 3466 PackageManager.SIGNATURE_NO_MATCH; 3467 } 3468 3469 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3470 for (Signature sig : s1) { 3471 set1.add(sig); 3472 } 3473 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3474 for (Signature sig : s2) { 3475 set2.add(sig); 3476 } 3477 // Make sure s2 contains all signatures in s1. 3478 if (set1.equals(set2)) { 3479 return PackageManager.SIGNATURE_MATCH; 3480 } 3481 return PackageManager.SIGNATURE_NO_MATCH; 3482 } 3483 3484 /** 3485 * If the database version for this type of package (internal storage or 3486 * external storage) is less than the version where package signatures 3487 * were updated, return true. 3488 */ 3489 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3490 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3491 DatabaseVersion.SIGNATURE_END_ENTITY)) 3492 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3493 DatabaseVersion.SIGNATURE_END_ENTITY)); 3494 } 3495 3496 /** 3497 * Used for backward compatibility to make sure any packages with 3498 * certificate chains get upgraded to the new style. {@code existingSigs} 3499 * will be in the old format (since they were stored on disk from before the 3500 * system upgrade) and {@code scannedSigs} will be in the newer format. 3501 */ 3502 private int compareSignaturesCompat(PackageSignatures existingSigs, 3503 PackageParser.Package scannedPkg) { 3504 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3505 return PackageManager.SIGNATURE_NO_MATCH; 3506 } 3507 3508 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3509 for (Signature sig : existingSigs.mSignatures) { 3510 existingSet.add(sig); 3511 } 3512 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3513 for (Signature sig : scannedPkg.mSignatures) { 3514 try { 3515 Signature[] chainSignatures = sig.getChainSignatures(); 3516 for (Signature chainSig : chainSignatures) { 3517 scannedCompatSet.add(chainSig); 3518 } 3519 } catch (CertificateEncodingException e) { 3520 scannedCompatSet.add(sig); 3521 } 3522 } 3523 /* 3524 * Make sure the expanded scanned set contains all signatures in the 3525 * existing one. 3526 */ 3527 if (scannedCompatSet.equals(existingSet)) { 3528 // Migrate the old signatures to the new scheme. 3529 existingSigs.assignSignatures(scannedPkg.mSignatures); 3530 // The new KeySets will be re-added later in the scanning process. 3531 synchronized (mPackages) { 3532 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3533 } 3534 return PackageManager.SIGNATURE_MATCH; 3535 } 3536 return PackageManager.SIGNATURE_NO_MATCH; 3537 } 3538 3539 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3540 if (isExternal(scannedPkg)) { 3541 return mSettings.isExternalDatabaseVersionOlderThan( 3542 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3543 } else { 3544 return mSettings.isInternalDatabaseVersionOlderThan( 3545 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3546 } 3547 } 3548 3549 private int compareSignaturesRecover(PackageSignatures existingSigs, 3550 PackageParser.Package scannedPkg) { 3551 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3552 return PackageManager.SIGNATURE_NO_MATCH; 3553 } 3554 3555 String msg = null; 3556 try { 3557 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3558 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3559 + scannedPkg.packageName); 3560 return PackageManager.SIGNATURE_MATCH; 3561 } 3562 } catch (CertificateException e) { 3563 msg = e.getMessage(); 3564 } 3565 3566 logCriticalInfo(Log.INFO, 3567 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3568 return PackageManager.SIGNATURE_NO_MATCH; 3569 } 3570 3571 @Override 3572 public String[] getPackagesForUid(int uid) { 3573 uid = UserHandle.getAppId(uid); 3574 // reader 3575 synchronized (mPackages) { 3576 Object obj = mSettings.getUserIdLPr(uid); 3577 if (obj instanceof SharedUserSetting) { 3578 final SharedUserSetting sus = (SharedUserSetting) obj; 3579 final int N = sus.packages.size(); 3580 final String[] res = new String[N]; 3581 final Iterator<PackageSetting> it = sus.packages.iterator(); 3582 int i = 0; 3583 while (it.hasNext()) { 3584 res[i++] = it.next().name; 3585 } 3586 return res; 3587 } else if (obj instanceof PackageSetting) { 3588 final PackageSetting ps = (PackageSetting) obj; 3589 return new String[] { ps.name }; 3590 } 3591 } 3592 return null; 3593 } 3594 3595 @Override 3596 public String getNameForUid(int uid) { 3597 // reader 3598 synchronized (mPackages) { 3599 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3600 if (obj instanceof SharedUserSetting) { 3601 final SharedUserSetting sus = (SharedUserSetting) obj; 3602 return sus.name + ":" + sus.userId; 3603 } else if (obj instanceof PackageSetting) { 3604 final PackageSetting ps = (PackageSetting) obj; 3605 return ps.name; 3606 } 3607 } 3608 return null; 3609 } 3610 3611 @Override 3612 public int getUidForSharedUser(String sharedUserName) { 3613 if(sharedUserName == null) { 3614 return -1; 3615 } 3616 // reader 3617 synchronized (mPackages) { 3618 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3619 if (suid == null) { 3620 return -1; 3621 } 3622 return suid.userId; 3623 } 3624 } 3625 3626 @Override 3627 public int getFlagsForUid(int uid) { 3628 synchronized (mPackages) { 3629 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3630 if (obj instanceof SharedUserSetting) { 3631 final SharedUserSetting sus = (SharedUserSetting) obj; 3632 return sus.pkgFlags; 3633 } else if (obj instanceof PackageSetting) { 3634 final PackageSetting ps = (PackageSetting) obj; 3635 return ps.pkgFlags; 3636 } 3637 } 3638 return 0; 3639 } 3640 3641 @Override 3642 public int getPrivateFlagsForUid(int uid) { 3643 synchronized (mPackages) { 3644 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3645 if (obj instanceof SharedUserSetting) { 3646 final SharedUserSetting sus = (SharedUserSetting) obj; 3647 return sus.pkgPrivateFlags; 3648 } else if (obj instanceof PackageSetting) { 3649 final PackageSetting ps = (PackageSetting) obj; 3650 return ps.pkgPrivateFlags; 3651 } 3652 } 3653 return 0; 3654 } 3655 3656 @Override 3657 public boolean isUidPrivileged(int uid) { 3658 uid = UserHandle.getAppId(uid); 3659 // reader 3660 synchronized (mPackages) { 3661 Object obj = mSettings.getUserIdLPr(uid); 3662 if (obj instanceof SharedUserSetting) { 3663 final SharedUserSetting sus = (SharedUserSetting) obj; 3664 final Iterator<PackageSetting> it = sus.packages.iterator(); 3665 while (it.hasNext()) { 3666 if (it.next().isPrivileged()) { 3667 return true; 3668 } 3669 } 3670 } else if (obj instanceof PackageSetting) { 3671 final PackageSetting ps = (PackageSetting) obj; 3672 return ps.isPrivileged(); 3673 } 3674 } 3675 return false; 3676 } 3677 3678 @Override 3679 public String[] getAppOpPermissionPackages(String permissionName) { 3680 synchronized (mPackages) { 3681 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3682 if (pkgs == null) { 3683 return null; 3684 } 3685 return pkgs.toArray(new String[pkgs.size()]); 3686 } 3687 } 3688 3689 @Override 3690 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3691 int flags, int userId) { 3692 if (!sUserManager.exists(userId)) return null; 3693 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3694 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3695 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3696 } 3697 3698 @Override 3699 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3700 IntentFilter filter, int match, ComponentName activity) { 3701 final int userId = UserHandle.getCallingUserId(); 3702 if (DEBUG_PREFERRED) { 3703 Log.v(TAG, "setLastChosenActivity intent=" + intent 3704 + " resolvedType=" + resolvedType 3705 + " flags=" + flags 3706 + " filter=" + filter 3707 + " match=" + match 3708 + " activity=" + activity); 3709 filter.dump(new PrintStreamPrinter(System.out), " "); 3710 } 3711 intent.setComponent(null); 3712 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3713 // Find any earlier preferred or last chosen entries and nuke them 3714 findPreferredActivity(intent, resolvedType, 3715 flags, query, 0, false, true, false, userId); 3716 // Add the new activity as the last chosen for this filter 3717 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3718 "Setting last chosen"); 3719 } 3720 3721 @Override 3722 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3723 final int userId = UserHandle.getCallingUserId(); 3724 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3725 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3726 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3727 false, false, false, userId); 3728 } 3729 3730 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3731 int flags, List<ResolveInfo> query, int userId) { 3732 if (query != null) { 3733 final int N = query.size(); 3734 if (N == 1) { 3735 return query.get(0); 3736 } else if (N > 1) { 3737 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3738 // If there is more than one activity with the same priority, 3739 // then let the user decide between them. 3740 ResolveInfo r0 = query.get(0); 3741 ResolveInfo r1 = query.get(1); 3742 if (DEBUG_INTENT_MATCHING || debug) { 3743 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3744 + r1.activityInfo.name + "=" + r1.priority); 3745 } 3746 // If the first activity has a higher priority, or a different 3747 // default, then it is always desireable to pick it. 3748 if (r0.priority != r1.priority 3749 || r0.preferredOrder != r1.preferredOrder 3750 || r0.isDefault != r1.isDefault) { 3751 return query.get(0); 3752 } 3753 // If we have saved a preference for a preferred activity for 3754 // this Intent, use that. 3755 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3756 flags, query, r0.priority, true, false, debug, userId); 3757 if (ri != null) { 3758 return ri; 3759 } 3760 if (userId != 0) { 3761 ri = new ResolveInfo(mResolveInfo); 3762 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3763 ri.activityInfo.applicationInfo = new ApplicationInfo( 3764 ri.activityInfo.applicationInfo); 3765 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3766 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3767 return ri; 3768 } 3769 return mResolveInfo; 3770 } 3771 } 3772 return null; 3773 } 3774 3775 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3776 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3777 final int N = query.size(); 3778 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3779 .get(userId); 3780 // Get the list of persistent preferred activities that handle the intent 3781 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3782 List<PersistentPreferredActivity> pprefs = ppir != null 3783 ? ppir.queryIntent(intent, resolvedType, 3784 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3785 : null; 3786 if (pprefs != null && pprefs.size() > 0) { 3787 final int M = pprefs.size(); 3788 for (int i=0; i<M; i++) { 3789 final PersistentPreferredActivity ppa = pprefs.get(i); 3790 if (DEBUG_PREFERRED || debug) { 3791 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3792 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3793 + "\n component=" + ppa.mComponent); 3794 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3795 } 3796 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3797 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3798 if (DEBUG_PREFERRED || debug) { 3799 Slog.v(TAG, "Found persistent preferred activity:"); 3800 if (ai != null) { 3801 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3802 } else { 3803 Slog.v(TAG, " null"); 3804 } 3805 } 3806 if (ai == null) { 3807 // This previously registered persistent preferred activity 3808 // component is no longer known. Ignore it and do NOT remove it. 3809 continue; 3810 } 3811 for (int j=0; j<N; j++) { 3812 final ResolveInfo ri = query.get(j); 3813 if (!ri.activityInfo.applicationInfo.packageName 3814 .equals(ai.applicationInfo.packageName)) { 3815 continue; 3816 } 3817 if (!ri.activityInfo.name.equals(ai.name)) { 3818 continue; 3819 } 3820 // Found a persistent preference that can handle the intent. 3821 if (DEBUG_PREFERRED || debug) { 3822 Slog.v(TAG, "Returning persistent preferred activity: " + 3823 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3824 } 3825 return ri; 3826 } 3827 } 3828 } 3829 return null; 3830 } 3831 3832 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3833 List<ResolveInfo> query, int priority, boolean always, 3834 boolean removeMatches, boolean debug, int userId) { 3835 if (!sUserManager.exists(userId)) return null; 3836 // writer 3837 synchronized (mPackages) { 3838 if (intent.getSelector() != null) { 3839 intent = intent.getSelector(); 3840 } 3841 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3842 3843 // Try to find a matching persistent preferred activity. 3844 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3845 debug, userId); 3846 3847 // If a persistent preferred activity matched, use it. 3848 if (pri != null) { 3849 return pri; 3850 } 3851 3852 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3853 // Get the list of preferred activities that handle the intent 3854 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3855 List<PreferredActivity> prefs = pir != null 3856 ? pir.queryIntent(intent, resolvedType, 3857 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3858 : null; 3859 if (prefs != null && prefs.size() > 0) { 3860 boolean changed = false; 3861 try { 3862 // First figure out how good the original match set is. 3863 // We will only allow preferred activities that came 3864 // from the same match quality. 3865 int match = 0; 3866 3867 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3868 3869 final int N = query.size(); 3870 for (int j=0; j<N; j++) { 3871 final ResolveInfo ri = query.get(j); 3872 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3873 + ": 0x" + Integer.toHexString(match)); 3874 if (ri.match > match) { 3875 match = ri.match; 3876 } 3877 } 3878 3879 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3880 + Integer.toHexString(match)); 3881 3882 match &= IntentFilter.MATCH_CATEGORY_MASK; 3883 final int M = prefs.size(); 3884 for (int i=0; i<M; i++) { 3885 final PreferredActivity pa = prefs.get(i); 3886 if (DEBUG_PREFERRED || debug) { 3887 Slog.v(TAG, "Checking PreferredActivity ds=" 3888 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3889 + "\n component=" + pa.mPref.mComponent); 3890 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3891 } 3892 if (pa.mPref.mMatch != match) { 3893 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3894 + Integer.toHexString(pa.mPref.mMatch)); 3895 continue; 3896 } 3897 // If it's not an "always" type preferred activity and that's what we're 3898 // looking for, skip it. 3899 if (always && !pa.mPref.mAlways) { 3900 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3901 continue; 3902 } 3903 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3904 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3905 if (DEBUG_PREFERRED || debug) { 3906 Slog.v(TAG, "Found preferred activity:"); 3907 if (ai != null) { 3908 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3909 } else { 3910 Slog.v(TAG, " null"); 3911 } 3912 } 3913 if (ai == null) { 3914 // This previously registered preferred activity 3915 // component is no longer known. Most likely an update 3916 // to the app was installed and in the new version this 3917 // component no longer exists. Clean it up by removing 3918 // it from the preferred activities list, and skip it. 3919 Slog.w(TAG, "Removing dangling preferred activity: " 3920 + pa.mPref.mComponent); 3921 pir.removeFilter(pa); 3922 changed = true; 3923 continue; 3924 } 3925 for (int j=0; j<N; j++) { 3926 final ResolveInfo ri = query.get(j); 3927 if (!ri.activityInfo.applicationInfo.packageName 3928 .equals(ai.applicationInfo.packageName)) { 3929 continue; 3930 } 3931 if (!ri.activityInfo.name.equals(ai.name)) { 3932 continue; 3933 } 3934 3935 if (removeMatches) { 3936 pir.removeFilter(pa); 3937 changed = true; 3938 if (DEBUG_PREFERRED) { 3939 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3940 } 3941 break; 3942 } 3943 3944 // Okay we found a previously set preferred or last chosen app. 3945 // If the result set is different from when this 3946 // was created, we need to clear it and re-ask the 3947 // user their preference, if we're looking for an "always" type entry. 3948 if (always && !pa.mPref.sameSet(query)) { 3949 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3950 + intent + " type " + resolvedType); 3951 if (DEBUG_PREFERRED) { 3952 Slog.v(TAG, "Removing preferred activity since set changed " 3953 + pa.mPref.mComponent); 3954 } 3955 pir.removeFilter(pa); 3956 // Re-add the filter as a "last chosen" entry (!always) 3957 PreferredActivity lastChosen = new PreferredActivity( 3958 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3959 pir.addFilter(lastChosen); 3960 changed = true; 3961 return null; 3962 } 3963 3964 // Yay! Either the set matched or we're looking for the last chosen 3965 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3966 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3967 return ri; 3968 } 3969 } 3970 } finally { 3971 if (changed) { 3972 if (DEBUG_PREFERRED) { 3973 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3974 } 3975 scheduleWritePackageRestrictionsLocked(userId); 3976 } 3977 } 3978 } 3979 } 3980 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3981 return null; 3982 } 3983 3984 /* 3985 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3986 */ 3987 @Override 3988 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3989 int targetUserId) { 3990 mContext.enforceCallingOrSelfPermission( 3991 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3992 List<CrossProfileIntentFilter> matches = 3993 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3994 if (matches != null) { 3995 int size = matches.size(); 3996 for (int i = 0; i < size; i++) { 3997 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3998 } 3999 } 4000 return false; 4001 } 4002 4003 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4004 String resolvedType, int userId) { 4005 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4006 if (resolver != null) { 4007 return resolver.queryIntent(intent, resolvedType, false, userId); 4008 } 4009 return null; 4010 } 4011 4012 @Override 4013 public List<ResolveInfo> queryIntentActivities(Intent intent, 4014 String resolvedType, int flags, int userId) { 4015 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4016 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4017 ComponentName comp = intent.getComponent(); 4018 if (comp == null) { 4019 if (intent.getSelector() != null) { 4020 intent = intent.getSelector(); 4021 comp = intent.getComponent(); 4022 } 4023 } 4024 4025 if (comp != null) { 4026 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4027 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4028 if (ai != null) { 4029 final ResolveInfo ri = new ResolveInfo(); 4030 ri.activityInfo = ai; 4031 list.add(ri); 4032 } 4033 return list; 4034 } 4035 4036 // reader 4037 synchronized (mPackages) { 4038 final String pkgName = intent.getPackage(); 4039 if (pkgName == null) { 4040 List<CrossProfileIntentFilter> matchingFilters = 4041 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4042 // Check for results that need to skip the current profile. 4043 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4044 resolvedType, flags, userId); 4045 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4046 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4047 result.add(resolveInfo); 4048 return filterIfNotPrimaryUser(result, userId); 4049 } 4050 4051 // Check for results in the current profile. 4052 List<ResolveInfo> result = mActivities.queryIntent( 4053 intent, resolvedType, flags, userId); 4054 4055 // Check for cross profile results. 4056 resolveInfo = queryCrossProfileIntents( 4057 matchingFilters, intent, resolvedType, flags, userId); 4058 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4059 result.add(resolveInfo); 4060 Collections.sort(result, mResolvePrioritySorter); 4061 } 4062 result = filterIfNotPrimaryUser(result, userId); 4063 if (result.size() > 1 && hasWebURI(intent)) { 4064 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4065 } 4066 return result; 4067 } 4068 final PackageParser.Package pkg = mPackages.get(pkgName); 4069 if (pkg != null) { 4070 return filterIfNotPrimaryUser( 4071 mActivities.queryIntentForPackage( 4072 intent, resolvedType, flags, pkg.activities, userId), 4073 userId); 4074 } 4075 return new ArrayList<ResolveInfo>(); 4076 } 4077 } 4078 4079 private boolean isUserEnabled(int userId) { 4080 long callingId = Binder.clearCallingIdentity(); 4081 try { 4082 UserInfo userInfo = sUserManager.getUserInfo(userId); 4083 return userInfo != null && userInfo.isEnabled(); 4084 } finally { 4085 Binder.restoreCallingIdentity(callingId); 4086 } 4087 } 4088 4089 /** 4090 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4091 * 4092 * @return filtered list 4093 */ 4094 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4095 if (userId == UserHandle.USER_OWNER) { 4096 return resolveInfos; 4097 } 4098 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4099 ResolveInfo info = resolveInfos.get(i); 4100 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4101 resolveInfos.remove(i); 4102 } 4103 } 4104 return resolveInfos; 4105 } 4106 4107 private static boolean hasWebURI(Intent intent) { 4108 if (intent.getData() == null) { 4109 return false; 4110 } 4111 final String scheme = intent.getScheme(); 4112 if (TextUtils.isEmpty(scheme)) { 4113 return false; 4114 } 4115 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4116 } 4117 4118 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4119 int flags, List<ResolveInfo> candidates) { 4120 if (DEBUG_PREFERRED) { 4121 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4122 candidates.size()); 4123 } 4124 4125 final int userId = UserHandle.getCallingUserId(); 4126 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4127 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4128 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4129 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4130 4131 synchronized (mPackages) { 4132 final int count = candidates.size(); 4133 // First, try to use the domain prefered App 4134 for (int n=0; n<count; n++) { 4135 ResolveInfo info = candidates.get(n); 4136 String packageName = info.activityInfo.packageName; 4137 PackageSetting ps = mSettings.mPackages.get(packageName); 4138 if (ps != null) { 4139 // Add to the special match all list (Browser use case) 4140 if (info.handleAllWebDataURI) { 4141 matchAllList.add(info); 4142 continue; 4143 } 4144 // Try to get the status from User settings first 4145 int status = getDomainVerificationStatusLPr(ps, userId); 4146 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4147 result.add(info); 4148 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4149 neverList.add(info); 4150 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4151 undefinedList.add(info); 4152 } 4153 } 4154 } 4155 // If there is nothing selected, add all candidates and remove the ones that the User 4156 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and 4157 // also remove any Browser Apps ones. 4158 // If there is still none after this pass, add all undefined one and Browser Apps and 4159 // let the User decide with the Disambiguation dialog if there are several ones. 4160 if (result.size() == 0) { 4161 result.addAll(candidates); 4162 } 4163 result.removeAll(neverList); 4164 result.removeAll(matchAllList); 4165 if (result.size() == 0) { 4166 result.addAll(undefinedList); 4167 if ((flags & MATCH_ALL) != 0) { 4168 result.addAll(matchAllList); 4169 } else { 4170 // Try to add the Default Browser if we can 4171 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4172 UserHandle.myUserId()); 4173 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4174 boolean defaultBrowserFound = false; 4175 final int browserCount = matchAllList.size(); 4176 for (int n=0; n<browserCount; n++) { 4177 ResolveInfo browser = matchAllList.get(n); 4178 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4179 result.add(browser); 4180 defaultBrowserFound = true; 4181 break; 4182 } 4183 } 4184 if (!defaultBrowserFound) { 4185 result.addAll(matchAllList); 4186 } 4187 } else { 4188 result.addAll(matchAllList); 4189 } 4190 } 4191 } 4192 } 4193 if (DEBUG_PREFERRED) { 4194 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4195 result.size()); 4196 } 4197 return result; 4198 } 4199 4200 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4201 int status = ps.getDomainVerificationStatusForUser(userId); 4202 // if none available, get the master status 4203 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4204 if (ps.getIntentFilterVerificationInfo() != null) { 4205 status = ps.getIntentFilterVerificationInfo().getStatus(); 4206 } 4207 } 4208 return status; 4209 } 4210 4211 private ResolveInfo querySkipCurrentProfileIntents( 4212 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4213 int flags, int sourceUserId) { 4214 if (matchingFilters != null) { 4215 int size = matchingFilters.size(); 4216 for (int i = 0; i < size; i ++) { 4217 CrossProfileIntentFilter filter = matchingFilters.get(i); 4218 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4219 // Checking if there are activities in the target user that can handle the 4220 // intent. 4221 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4222 flags, sourceUserId); 4223 if (resolveInfo != null) { 4224 return resolveInfo; 4225 } 4226 } 4227 } 4228 } 4229 return null; 4230 } 4231 4232 // Return matching ResolveInfo if any for skip current profile intent filters. 4233 private ResolveInfo queryCrossProfileIntents( 4234 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4235 int flags, int sourceUserId) { 4236 if (matchingFilters != null) { 4237 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4238 // match the same intent. For performance reasons, it is better not to 4239 // run queryIntent twice for the same userId 4240 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4241 int size = matchingFilters.size(); 4242 for (int i = 0; i < size; i++) { 4243 CrossProfileIntentFilter filter = matchingFilters.get(i); 4244 int targetUserId = filter.getTargetUserId(); 4245 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4246 && !alreadyTriedUserIds.get(targetUserId)) { 4247 // Checking if there are activities in the target user that can handle the 4248 // intent. 4249 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4250 flags, sourceUserId); 4251 if (resolveInfo != null) return resolveInfo; 4252 alreadyTriedUserIds.put(targetUserId, true); 4253 } 4254 } 4255 } 4256 return null; 4257 } 4258 4259 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4260 String resolvedType, int flags, int sourceUserId) { 4261 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4262 resolvedType, flags, filter.getTargetUserId()); 4263 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4264 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4265 } 4266 return null; 4267 } 4268 4269 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4270 int sourceUserId, int targetUserId) { 4271 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4272 String className; 4273 if (targetUserId == UserHandle.USER_OWNER) { 4274 className = FORWARD_INTENT_TO_USER_OWNER; 4275 } else { 4276 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4277 } 4278 ComponentName forwardingActivityComponentName = new ComponentName( 4279 mAndroidApplication.packageName, className); 4280 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4281 sourceUserId); 4282 if (targetUserId == UserHandle.USER_OWNER) { 4283 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4284 forwardingResolveInfo.noResourceId = true; 4285 } 4286 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4287 forwardingResolveInfo.priority = 0; 4288 forwardingResolveInfo.preferredOrder = 0; 4289 forwardingResolveInfo.match = 0; 4290 forwardingResolveInfo.isDefault = true; 4291 forwardingResolveInfo.filter = filter; 4292 forwardingResolveInfo.targetUserId = targetUserId; 4293 return forwardingResolveInfo; 4294 } 4295 4296 @Override 4297 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4298 Intent[] specifics, String[] specificTypes, Intent intent, 4299 String resolvedType, int flags, int userId) { 4300 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4301 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4302 false, "query intent activity options"); 4303 final String resultsAction = intent.getAction(); 4304 4305 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4306 | PackageManager.GET_RESOLVED_FILTER, userId); 4307 4308 if (DEBUG_INTENT_MATCHING) { 4309 Log.v(TAG, "Query " + intent + ": " + results); 4310 } 4311 4312 int specificsPos = 0; 4313 int N; 4314 4315 // todo: note that the algorithm used here is O(N^2). This 4316 // isn't a problem in our current environment, but if we start running 4317 // into situations where we have more than 5 or 10 matches then this 4318 // should probably be changed to something smarter... 4319 4320 // First we go through and resolve each of the specific items 4321 // that were supplied, taking care of removing any corresponding 4322 // duplicate items in the generic resolve list. 4323 if (specifics != null) { 4324 for (int i=0; i<specifics.length; i++) { 4325 final Intent sintent = specifics[i]; 4326 if (sintent == null) { 4327 continue; 4328 } 4329 4330 if (DEBUG_INTENT_MATCHING) { 4331 Log.v(TAG, "Specific #" + i + ": " + sintent); 4332 } 4333 4334 String action = sintent.getAction(); 4335 if (resultsAction != null && resultsAction.equals(action)) { 4336 // If this action was explicitly requested, then don't 4337 // remove things that have it. 4338 action = null; 4339 } 4340 4341 ResolveInfo ri = null; 4342 ActivityInfo ai = null; 4343 4344 ComponentName comp = sintent.getComponent(); 4345 if (comp == null) { 4346 ri = resolveIntent( 4347 sintent, 4348 specificTypes != null ? specificTypes[i] : null, 4349 flags, userId); 4350 if (ri == null) { 4351 continue; 4352 } 4353 if (ri == mResolveInfo) { 4354 // ACK! Must do something better with this. 4355 } 4356 ai = ri.activityInfo; 4357 comp = new ComponentName(ai.applicationInfo.packageName, 4358 ai.name); 4359 } else { 4360 ai = getActivityInfo(comp, flags, userId); 4361 if (ai == null) { 4362 continue; 4363 } 4364 } 4365 4366 // Look for any generic query activities that are duplicates 4367 // of this specific one, and remove them from the results. 4368 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4369 N = results.size(); 4370 int j; 4371 for (j=specificsPos; j<N; j++) { 4372 ResolveInfo sri = results.get(j); 4373 if ((sri.activityInfo.name.equals(comp.getClassName()) 4374 && sri.activityInfo.applicationInfo.packageName.equals( 4375 comp.getPackageName())) 4376 || (action != null && sri.filter.matchAction(action))) { 4377 results.remove(j); 4378 if (DEBUG_INTENT_MATCHING) Log.v( 4379 TAG, "Removing duplicate item from " + j 4380 + " due to specific " + specificsPos); 4381 if (ri == null) { 4382 ri = sri; 4383 } 4384 j--; 4385 N--; 4386 } 4387 } 4388 4389 // Add this specific item to its proper place. 4390 if (ri == null) { 4391 ri = new ResolveInfo(); 4392 ri.activityInfo = ai; 4393 } 4394 results.add(specificsPos, ri); 4395 ri.specificIndex = i; 4396 specificsPos++; 4397 } 4398 } 4399 4400 // Now we go through the remaining generic results and remove any 4401 // duplicate actions that are found here. 4402 N = results.size(); 4403 for (int i=specificsPos; i<N-1; i++) { 4404 final ResolveInfo rii = results.get(i); 4405 if (rii.filter == null) { 4406 continue; 4407 } 4408 4409 // Iterate over all of the actions of this result's intent 4410 // filter... typically this should be just one. 4411 final Iterator<String> it = rii.filter.actionsIterator(); 4412 if (it == null) { 4413 continue; 4414 } 4415 while (it.hasNext()) { 4416 final String action = it.next(); 4417 if (resultsAction != null && resultsAction.equals(action)) { 4418 // If this action was explicitly requested, then don't 4419 // remove things that have it. 4420 continue; 4421 } 4422 for (int j=i+1; j<N; j++) { 4423 final ResolveInfo rij = results.get(j); 4424 if (rij.filter != null && rij.filter.hasAction(action)) { 4425 results.remove(j); 4426 if (DEBUG_INTENT_MATCHING) Log.v( 4427 TAG, "Removing duplicate item from " + j 4428 + " due to action " + action + " at " + i); 4429 j--; 4430 N--; 4431 } 4432 } 4433 } 4434 4435 // If the caller didn't request filter information, drop it now 4436 // so we don't have to marshall/unmarshall it. 4437 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4438 rii.filter = null; 4439 } 4440 } 4441 4442 // Filter out the caller activity if so requested. 4443 if (caller != null) { 4444 N = results.size(); 4445 for (int i=0; i<N; i++) { 4446 ActivityInfo ainfo = results.get(i).activityInfo; 4447 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4448 && caller.getClassName().equals(ainfo.name)) { 4449 results.remove(i); 4450 break; 4451 } 4452 } 4453 } 4454 4455 // If the caller didn't request filter information, 4456 // drop them now so we don't have to 4457 // marshall/unmarshall it. 4458 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4459 N = results.size(); 4460 for (int i=0; i<N; i++) { 4461 results.get(i).filter = null; 4462 } 4463 } 4464 4465 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4466 return results; 4467 } 4468 4469 @Override 4470 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4471 int userId) { 4472 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4473 ComponentName comp = intent.getComponent(); 4474 if (comp == null) { 4475 if (intent.getSelector() != null) { 4476 intent = intent.getSelector(); 4477 comp = intent.getComponent(); 4478 } 4479 } 4480 if (comp != null) { 4481 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4482 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4483 if (ai != null) { 4484 ResolveInfo ri = new ResolveInfo(); 4485 ri.activityInfo = ai; 4486 list.add(ri); 4487 } 4488 return list; 4489 } 4490 4491 // reader 4492 synchronized (mPackages) { 4493 String pkgName = intent.getPackage(); 4494 if (pkgName == null) { 4495 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4496 } 4497 final PackageParser.Package pkg = mPackages.get(pkgName); 4498 if (pkg != null) { 4499 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4500 userId); 4501 } 4502 return null; 4503 } 4504 } 4505 4506 @Override 4507 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4508 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4509 if (!sUserManager.exists(userId)) return null; 4510 if (query != null) { 4511 if (query.size() >= 1) { 4512 // If there is more than one service with the same priority, 4513 // just arbitrarily pick the first one. 4514 return query.get(0); 4515 } 4516 } 4517 return null; 4518 } 4519 4520 @Override 4521 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4522 int userId) { 4523 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4524 ComponentName comp = intent.getComponent(); 4525 if (comp == null) { 4526 if (intent.getSelector() != null) { 4527 intent = intent.getSelector(); 4528 comp = intent.getComponent(); 4529 } 4530 } 4531 if (comp != null) { 4532 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4533 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4534 if (si != null) { 4535 final ResolveInfo ri = new ResolveInfo(); 4536 ri.serviceInfo = si; 4537 list.add(ri); 4538 } 4539 return list; 4540 } 4541 4542 // reader 4543 synchronized (mPackages) { 4544 String pkgName = intent.getPackage(); 4545 if (pkgName == null) { 4546 return mServices.queryIntent(intent, resolvedType, flags, userId); 4547 } 4548 final PackageParser.Package pkg = mPackages.get(pkgName); 4549 if (pkg != null) { 4550 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4551 userId); 4552 } 4553 return null; 4554 } 4555 } 4556 4557 @Override 4558 public List<ResolveInfo> queryIntentContentProviders( 4559 Intent intent, String resolvedType, int flags, int userId) { 4560 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4561 ComponentName comp = intent.getComponent(); 4562 if (comp == null) { 4563 if (intent.getSelector() != null) { 4564 intent = intent.getSelector(); 4565 comp = intent.getComponent(); 4566 } 4567 } 4568 if (comp != null) { 4569 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4570 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4571 if (pi != null) { 4572 final ResolveInfo ri = new ResolveInfo(); 4573 ri.providerInfo = pi; 4574 list.add(ri); 4575 } 4576 return list; 4577 } 4578 4579 // reader 4580 synchronized (mPackages) { 4581 String pkgName = intent.getPackage(); 4582 if (pkgName == null) { 4583 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4584 } 4585 final PackageParser.Package pkg = mPackages.get(pkgName); 4586 if (pkg != null) { 4587 return mProviders.queryIntentForPackage( 4588 intent, resolvedType, flags, pkg.providers, userId); 4589 } 4590 return null; 4591 } 4592 } 4593 4594 @Override 4595 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4596 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4597 4598 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4599 4600 // writer 4601 synchronized (mPackages) { 4602 ArrayList<PackageInfo> list; 4603 if (listUninstalled) { 4604 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4605 for (PackageSetting ps : mSettings.mPackages.values()) { 4606 PackageInfo pi; 4607 if (ps.pkg != null) { 4608 pi = generatePackageInfo(ps.pkg, flags, userId); 4609 } else { 4610 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4611 } 4612 if (pi != null) { 4613 list.add(pi); 4614 } 4615 } 4616 } else { 4617 list = new ArrayList<PackageInfo>(mPackages.size()); 4618 for (PackageParser.Package p : mPackages.values()) { 4619 PackageInfo pi = generatePackageInfo(p, flags, userId); 4620 if (pi != null) { 4621 list.add(pi); 4622 } 4623 } 4624 } 4625 4626 return new ParceledListSlice<PackageInfo>(list); 4627 } 4628 } 4629 4630 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4631 String[] permissions, boolean[] tmp, int flags, int userId) { 4632 int numMatch = 0; 4633 final PermissionsState permissionsState = ps.getPermissionsState(); 4634 for (int i=0; i<permissions.length; i++) { 4635 final String permission = permissions[i]; 4636 if (permissionsState.hasPermission(permission, userId)) { 4637 tmp[i] = true; 4638 numMatch++; 4639 } else { 4640 tmp[i] = false; 4641 } 4642 } 4643 if (numMatch == 0) { 4644 return; 4645 } 4646 PackageInfo pi; 4647 if (ps.pkg != null) { 4648 pi = generatePackageInfo(ps.pkg, flags, userId); 4649 } else { 4650 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4651 } 4652 // The above might return null in cases of uninstalled apps or install-state 4653 // skew across users/profiles. 4654 if (pi != null) { 4655 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4656 if (numMatch == permissions.length) { 4657 pi.requestedPermissions = permissions; 4658 } else { 4659 pi.requestedPermissions = new String[numMatch]; 4660 numMatch = 0; 4661 for (int i=0; i<permissions.length; i++) { 4662 if (tmp[i]) { 4663 pi.requestedPermissions[numMatch] = permissions[i]; 4664 numMatch++; 4665 } 4666 } 4667 } 4668 } 4669 list.add(pi); 4670 } 4671 } 4672 4673 @Override 4674 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4675 String[] permissions, int flags, int userId) { 4676 if (!sUserManager.exists(userId)) return null; 4677 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4678 4679 // writer 4680 synchronized (mPackages) { 4681 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4682 boolean[] tmpBools = new boolean[permissions.length]; 4683 if (listUninstalled) { 4684 for (PackageSetting ps : mSettings.mPackages.values()) { 4685 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4686 } 4687 } else { 4688 for (PackageParser.Package pkg : mPackages.values()) { 4689 PackageSetting ps = (PackageSetting)pkg.mExtras; 4690 if (ps != null) { 4691 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4692 userId); 4693 } 4694 } 4695 } 4696 4697 return new ParceledListSlice<PackageInfo>(list); 4698 } 4699 } 4700 4701 @Override 4702 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4703 if (!sUserManager.exists(userId)) return null; 4704 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4705 4706 // writer 4707 synchronized (mPackages) { 4708 ArrayList<ApplicationInfo> list; 4709 if (listUninstalled) { 4710 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4711 for (PackageSetting ps : mSettings.mPackages.values()) { 4712 ApplicationInfo ai; 4713 if (ps.pkg != null) { 4714 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4715 ps.readUserState(userId), userId); 4716 } else { 4717 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4718 } 4719 if (ai != null) { 4720 list.add(ai); 4721 } 4722 } 4723 } else { 4724 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4725 for (PackageParser.Package p : mPackages.values()) { 4726 if (p.mExtras != null) { 4727 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4728 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4729 if (ai != null) { 4730 list.add(ai); 4731 } 4732 } 4733 } 4734 } 4735 4736 return new ParceledListSlice<ApplicationInfo>(list); 4737 } 4738 } 4739 4740 public List<ApplicationInfo> getPersistentApplications(int flags) { 4741 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4742 4743 // reader 4744 synchronized (mPackages) { 4745 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4746 final int userId = UserHandle.getCallingUserId(); 4747 while (i.hasNext()) { 4748 final PackageParser.Package p = i.next(); 4749 if (p.applicationInfo != null 4750 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4751 && (!mSafeMode || isSystemApp(p))) { 4752 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4753 if (ps != null) { 4754 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4755 ps.readUserState(userId), userId); 4756 if (ai != null) { 4757 finalList.add(ai); 4758 } 4759 } 4760 } 4761 } 4762 } 4763 4764 return finalList; 4765 } 4766 4767 @Override 4768 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4769 if (!sUserManager.exists(userId)) return null; 4770 // reader 4771 synchronized (mPackages) { 4772 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4773 PackageSetting ps = provider != null 4774 ? mSettings.mPackages.get(provider.owner.packageName) 4775 : null; 4776 return ps != null 4777 && mSettings.isEnabledLPr(provider.info, flags, userId) 4778 && (!mSafeMode || (provider.info.applicationInfo.flags 4779 &ApplicationInfo.FLAG_SYSTEM) != 0) 4780 ? PackageParser.generateProviderInfo(provider, flags, 4781 ps.readUserState(userId), userId) 4782 : null; 4783 } 4784 } 4785 4786 /** 4787 * @deprecated 4788 */ 4789 @Deprecated 4790 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4791 // reader 4792 synchronized (mPackages) { 4793 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4794 .entrySet().iterator(); 4795 final int userId = UserHandle.getCallingUserId(); 4796 while (i.hasNext()) { 4797 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4798 PackageParser.Provider p = entry.getValue(); 4799 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4800 4801 if (ps != null && p.syncable 4802 && (!mSafeMode || (p.info.applicationInfo.flags 4803 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4804 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4805 ps.readUserState(userId), userId); 4806 if (info != null) { 4807 outNames.add(entry.getKey()); 4808 outInfo.add(info); 4809 } 4810 } 4811 } 4812 } 4813 } 4814 4815 @Override 4816 public List<ProviderInfo> queryContentProviders(String processName, 4817 int uid, int flags) { 4818 ArrayList<ProviderInfo> finalList = null; 4819 // reader 4820 synchronized (mPackages) { 4821 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4822 final int userId = processName != null ? 4823 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4824 while (i.hasNext()) { 4825 final PackageParser.Provider p = i.next(); 4826 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4827 if (ps != null && p.info.authority != null 4828 && (processName == null 4829 || (p.info.processName.equals(processName) 4830 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4831 && mSettings.isEnabledLPr(p.info, flags, userId) 4832 && (!mSafeMode 4833 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4834 if (finalList == null) { 4835 finalList = new ArrayList<ProviderInfo>(3); 4836 } 4837 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4838 ps.readUserState(userId), userId); 4839 if (info != null) { 4840 finalList.add(info); 4841 } 4842 } 4843 } 4844 } 4845 4846 if (finalList != null) { 4847 Collections.sort(finalList, mProviderInitOrderSorter); 4848 } 4849 4850 return finalList; 4851 } 4852 4853 @Override 4854 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4855 int flags) { 4856 // reader 4857 synchronized (mPackages) { 4858 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4859 return PackageParser.generateInstrumentationInfo(i, flags); 4860 } 4861 } 4862 4863 @Override 4864 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4865 int flags) { 4866 ArrayList<InstrumentationInfo> finalList = 4867 new ArrayList<InstrumentationInfo>(); 4868 4869 // reader 4870 synchronized (mPackages) { 4871 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4872 while (i.hasNext()) { 4873 final PackageParser.Instrumentation p = i.next(); 4874 if (targetPackage == null 4875 || targetPackage.equals(p.info.targetPackage)) { 4876 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4877 flags); 4878 if (ii != null) { 4879 finalList.add(ii); 4880 } 4881 } 4882 } 4883 } 4884 4885 return finalList; 4886 } 4887 4888 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4889 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4890 if (overlays == null) { 4891 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4892 return; 4893 } 4894 for (PackageParser.Package opkg : overlays.values()) { 4895 // Not much to do if idmap fails: we already logged the error 4896 // and we certainly don't want to abort installation of pkg simply 4897 // because an overlay didn't fit properly. For these reasons, 4898 // ignore the return value of createIdmapForPackagePairLI. 4899 createIdmapForPackagePairLI(pkg, opkg); 4900 } 4901 } 4902 4903 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4904 PackageParser.Package opkg) { 4905 if (!opkg.mTrustedOverlay) { 4906 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4907 opkg.baseCodePath + ": overlay not trusted"); 4908 return false; 4909 } 4910 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4911 if (overlaySet == null) { 4912 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4913 opkg.baseCodePath + " but target package has no known overlays"); 4914 return false; 4915 } 4916 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4917 // TODO: generate idmap for split APKs 4918 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4919 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4920 + opkg.baseCodePath); 4921 return false; 4922 } 4923 PackageParser.Package[] overlayArray = 4924 overlaySet.values().toArray(new PackageParser.Package[0]); 4925 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4926 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4927 return p1.mOverlayPriority - p2.mOverlayPriority; 4928 } 4929 }; 4930 Arrays.sort(overlayArray, cmp); 4931 4932 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4933 int i = 0; 4934 for (PackageParser.Package p : overlayArray) { 4935 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4936 } 4937 return true; 4938 } 4939 4940 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4941 final File[] files = dir.listFiles(); 4942 if (ArrayUtils.isEmpty(files)) { 4943 Log.d(TAG, "No files in app dir " + dir); 4944 return; 4945 } 4946 4947 if (DEBUG_PACKAGE_SCANNING) { 4948 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4949 + " flags=0x" + Integer.toHexString(parseFlags)); 4950 } 4951 4952 for (File file : files) { 4953 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4954 && !PackageInstallerService.isStageName(file.getName()); 4955 if (!isPackage) { 4956 // Ignore entries which are not packages 4957 continue; 4958 } 4959 try { 4960 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4961 scanFlags, currentTime, null); 4962 } catch (PackageManagerException e) { 4963 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4964 4965 // Delete invalid userdata apps 4966 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4967 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4968 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4969 if (file.isDirectory()) { 4970 mInstaller.rmPackageDir(file.getAbsolutePath()); 4971 } else { 4972 file.delete(); 4973 } 4974 } 4975 } 4976 } 4977 } 4978 4979 private static File getSettingsProblemFile() { 4980 File dataDir = Environment.getDataDirectory(); 4981 File systemDir = new File(dataDir, "system"); 4982 File fname = new File(systemDir, "uiderrors.txt"); 4983 return fname; 4984 } 4985 4986 static void reportSettingsProblem(int priority, String msg) { 4987 logCriticalInfo(priority, msg); 4988 } 4989 4990 static void logCriticalInfo(int priority, String msg) { 4991 Slog.println(priority, TAG, msg); 4992 EventLogTags.writePmCriticalInfo(msg); 4993 try { 4994 File fname = getSettingsProblemFile(); 4995 FileOutputStream out = new FileOutputStream(fname, true); 4996 PrintWriter pw = new FastPrintWriter(out); 4997 SimpleDateFormat formatter = new SimpleDateFormat(); 4998 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4999 pw.println(dateString + ": " + msg); 5000 pw.close(); 5001 FileUtils.setPermissions( 5002 fname.toString(), 5003 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5004 -1, -1); 5005 } catch (java.io.IOException e) { 5006 } 5007 } 5008 5009 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5010 PackageParser.Package pkg, File srcFile, int parseFlags) 5011 throws PackageManagerException { 5012 if (ps != null 5013 && ps.codePath.equals(srcFile) 5014 && ps.timeStamp == srcFile.lastModified() 5015 && !isCompatSignatureUpdateNeeded(pkg) 5016 && !isRecoverSignatureUpdateNeeded(pkg)) { 5017 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5018 if (ps.signatures.mSignatures != null 5019 && ps.signatures.mSignatures.length != 0 5020 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5021 // Optimization: reuse the existing cached certificates 5022 // if the package appears to be unchanged. 5023 pkg.mSignatures = ps.signatures.mSignatures; 5024 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5025 synchronized (mPackages) { 5026 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5027 } 5028 return; 5029 } 5030 5031 Slog.w(TAG, "PackageSetting for " + ps.name 5032 + " is missing signatures. Collecting certs again to recover them."); 5033 } else { 5034 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5035 } 5036 5037 try { 5038 pp.collectCertificates(pkg, parseFlags); 5039 pp.collectManifestDigest(pkg); 5040 } catch (PackageParserException e) { 5041 throw PackageManagerException.from(e); 5042 } 5043 } 5044 5045 /* 5046 * Scan a package and return the newly parsed package. 5047 * Returns null in case of errors and the error code is stored in mLastScanError 5048 */ 5049 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5050 long currentTime, UserHandle user) throws PackageManagerException { 5051 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5052 parseFlags |= mDefParseFlags; 5053 PackageParser pp = new PackageParser(); 5054 pp.setSeparateProcesses(mSeparateProcesses); 5055 pp.setOnlyCoreApps(mOnlyCore); 5056 pp.setDisplayMetrics(mMetrics); 5057 5058 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5059 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5060 } 5061 5062 final PackageParser.Package pkg; 5063 try { 5064 pkg = pp.parsePackage(scanFile, parseFlags); 5065 } catch (PackageParserException e) { 5066 throw PackageManagerException.from(e); 5067 } 5068 5069 PackageSetting ps = null; 5070 PackageSetting updatedPkg; 5071 // reader 5072 synchronized (mPackages) { 5073 // Look to see if we already know about this package. 5074 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5075 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5076 // This package has been renamed to its original name. Let's 5077 // use that. 5078 ps = mSettings.peekPackageLPr(oldName); 5079 } 5080 // If there was no original package, see one for the real package name. 5081 if (ps == null) { 5082 ps = mSettings.peekPackageLPr(pkg.packageName); 5083 } 5084 // Check to see if this package could be hiding/updating a system 5085 // package. Must look for it either under the original or real 5086 // package name depending on our state. 5087 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5088 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5089 } 5090 boolean updatedPkgBetter = false; 5091 // First check if this is a system package that may involve an update 5092 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5093 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5094 // it needs to drop FLAG_PRIVILEGED. 5095 if (locationIsPrivileged(scanFile)) { 5096 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5097 } else { 5098 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5099 } 5100 5101 if (ps != null && !ps.codePath.equals(scanFile)) { 5102 // The path has changed from what was last scanned... check the 5103 // version of the new path against what we have stored to determine 5104 // what to do. 5105 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5106 if (pkg.mVersionCode <= ps.versionCode) { 5107 // The system package has been updated and the code path does not match 5108 // Ignore entry. Skip it. 5109 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5110 + " ignored: updated version " + ps.versionCode 5111 + " better than this " + pkg.mVersionCode); 5112 if (!updatedPkg.codePath.equals(scanFile)) { 5113 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5114 + ps.name + " changing from " + updatedPkg.codePathString 5115 + " to " + scanFile); 5116 updatedPkg.codePath = scanFile; 5117 updatedPkg.codePathString = scanFile.toString(); 5118 updatedPkg.resourcePath = scanFile; 5119 updatedPkg.resourcePathString = scanFile.toString(); 5120 } 5121 updatedPkg.pkg = pkg; 5122 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5123 } else { 5124 // The current app on the system partition is better than 5125 // what we have updated to on the data partition; switch 5126 // back to the system partition version. 5127 // At this point, its safely assumed that package installation for 5128 // apps in system partition will go through. If not there won't be a working 5129 // version of the app 5130 // writer 5131 synchronized (mPackages) { 5132 // Just remove the loaded entries from package lists. 5133 mPackages.remove(ps.name); 5134 } 5135 5136 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5137 + " reverting from " + ps.codePathString 5138 + ": new version " + pkg.mVersionCode 5139 + " better than installed " + ps.versionCode); 5140 5141 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5142 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5143 synchronized (mInstallLock) { 5144 args.cleanUpResourcesLI(); 5145 } 5146 synchronized (mPackages) { 5147 mSettings.enableSystemPackageLPw(ps.name); 5148 } 5149 updatedPkgBetter = true; 5150 } 5151 } 5152 } 5153 5154 if (updatedPkg != null) { 5155 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5156 // initially 5157 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5158 5159 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5160 // flag set initially 5161 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5162 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5163 } 5164 } 5165 5166 // Verify certificates against what was last scanned 5167 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5168 5169 /* 5170 * A new system app appeared, but we already had a non-system one of the 5171 * same name installed earlier. 5172 */ 5173 boolean shouldHideSystemApp = false; 5174 if (updatedPkg == null && ps != null 5175 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5176 /* 5177 * Check to make sure the signatures match first. If they don't, 5178 * wipe the installed application and its data. 5179 */ 5180 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5181 != PackageManager.SIGNATURE_MATCH) { 5182 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5183 + " signatures don't match existing userdata copy; removing"); 5184 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5185 ps = null; 5186 } else { 5187 /* 5188 * If the newly-added system app is an older version than the 5189 * already installed version, hide it. It will be scanned later 5190 * and re-added like an update. 5191 */ 5192 if (pkg.mVersionCode <= ps.versionCode) { 5193 shouldHideSystemApp = true; 5194 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5195 + " but new version " + pkg.mVersionCode + " better than installed " 5196 + ps.versionCode + "; hiding system"); 5197 } else { 5198 /* 5199 * The newly found system app is a newer version that the 5200 * one previously installed. Simply remove the 5201 * already-installed application and replace it with our own 5202 * while keeping the application data. 5203 */ 5204 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5205 + " reverting from " + ps.codePathString + ": new version " 5206 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5207 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5208 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5209 synchronized (mInstallLock) { 5210 args.cleanUpResourcesLI(); 5211 } 5212 } 5213 } 5214 } 5215 5216 // The apk is forward locked (not public) if its code and resources 5217 // are kept in different files. (except for app in either system or 5218 // vendor path). 5219 // TODO grab this value from PackageSettings 5220 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5221 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5222 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5223 } 5224 } 5225 5226 // TODO: extend to support forward-locked splits 5227 String resourcePath = null; 5228 String baseResourcePath = null; 5229 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5230 if (ps != null && ps.resourcePathString != null) { 5231 resourcePath = ps.resourcePathString; 5232 baseResourcePath = ps.resourcePathString; 5233 } else { 5234 // Should not happen at all. Just log an error. 5235 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5236 } 5237 } else { 5238 resourcePath = pkg.codePath; 5239 baseResourcePath = pkg.baseCodePath; 5240 } 5241 5242 // Set application objects path explicitly. 5243 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5244 pkg.applicationInfo.setCodePath(pkg.codePath); 5245 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5246 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5247 pkg.applicationInfo.setResourcePath(resourcePath); 5248 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5249 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5250 5251 // Note that we invoke the following method only if we are about to unpack an application 5252 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5253 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5254 5255 /* 5256 * If the system app should be overridden by a previously installed 5257 * data, hide the system app now and let the /data/app scan pick it up 5258 * again. 5259 */ 5260 if (shouldHideSystemApp) { 5261 synchronized (mPackages) { 5262 /* 5263 * We have to grant systems permissions before we hide, because 5264 * grantPermissions will assume the package update is trying to 5265 * expand its permissions. 5266 */ 5267 grantPermissionsLPw(pkg, true, pkg.packageName); 5268 mSettings.disableSystemPackageLPw(pkg.packageName); 5269 } 5270 } 5271 5272 return scannedPkg; 5273 } 5274 5275 private static String fixProcessName(String defProcessName, 5276 String processName, int uid) { 5277 if (processName == null) { 5278 return defProcessName; 5279 } 5280 return processName; 5281 } 5282 5283 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5284 throws PackageManagerException { 5285 if (pkgSetting.signatures.mSignatures != null) { 5286 // Already existing package. Make sure signatures match 5287 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5288 == PackageManager.SIGNATURE_MATCH; 5289 if (!match) { 5290 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5291 == PackageManager.SIGNATURE_MATCH; 5292 } 5293 if (!match) { 5294 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5295 == PackageManager.SIGNATURE_MATCH; 5296 } 5297 if (!match) { 5298 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5299 + pkg.packageName + " signatures do not match the " 5300 + "previously installed version; ignoring!"); 5301 } 5302 } 5303 5304 // Check for shared user signatures 5305 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5306 // Already existing package. Make sure signatures match 5307 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5308 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5309 if (!match) { 5310 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5311 == PackageManager.SIGNATURE_MATCH; 5312 } 5313 if (!match) { 5314 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5315 == PackageManager.SIGNATURE_MATCH; 5316 } 5317 if (!match) { 5318 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5319 "Package " + pkg.packageName 5320 + " has no signatures that match those in shared user " 5321 + pkgSetting.sharedUser.name + "; ignoring!"); 5322 } 5323 } 5324 } 5325 5326 /** 5327 * Enforces that only the system UID or root's UID can call a method exposed 5328 * via Binder. 5329 * 5330 * @param message used as message if SecurityException is thrown 5331 * @throws SecurityException if the caller is not system or root 5332 */ 5333 private static final void enforceSystemOrRoot(String message) { 5334 final int uid = Binder.getCallingUid(); 5335 if (uid != Process.SYSTEM_UID && uid != 0) { 5336 throw new SecurityException(message); 5337 } 5338 } 5339 5340 @Override 5341 public void performBootDexOpt() { 5342 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5343 5344 // Before everything else, see whether we need to fstrim. 5345 try { 5346 IMountService ms = PackageHelper.getMountService(); 5347 if (ms != null) { 5348 final boolean isUpgrade = isUpgrade(); 5349 boolean doTrim = isUpgrade; 5350 if (doTrim) { 5351 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5352 } else { 5353 final long interval = android.provider.Settings.Global.getLong( 5354 mContext.getContentResolver(), 5355 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5356 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5357 if (interval > 0) { 5358 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5359 if (timeSinceLast > interval) { 5360 doTrim = true; 5361 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5362 + "; running immediately"); 5363 } 5364 } 5365 } 5366 if (doTrim) { 5367 if (!isFirstBoot()) { 5368 try { 5369 ActivityManagerNative.getDefault().showBootMessage( 5370 mContext.getResources().getString( 5371 R.string.android_upgrading_fstrim), true); 5372 } catch (RemoteException e) { 5373 } 5374 } 5375 ms.runMaintenance(); 5376 } 5377 } else { 5378 Slog.e(TAG, "Mount service unavailable!"); 5379 } 5380 } catch (RemoteException e) { 5381 // Can't happen; MountService is local 5382 } 5383 5384 final ArraySet<PackageParser.Package> pkgs; 5385 synchronized (mPackages) { 5386 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5387 } 5388 5389 if (pkgs != null) { 5390 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5391 // in case the device runs out of space. 5392 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5393 // Give priority to core apps. 5394 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5395 PackageParser.Package pkg = it.next(); 5396 if (pkg.coreApp) { 5397 if (DEBUG_DEXOPT) { 5398 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5399 } 5400 sortedPkgs.add(pkg); 5401 it.remove(); 5402 } 5403 } 5404 // Give priority to system apps that listen for pre boot complete. 5405 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5406 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5407 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5408 PackageParser.Package pkg = it.next(); 5409 if (pkgNames.contains(pkg.packageName)) { 5410 if (DEBUG_DEXOPT) { 5411 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5412 } 5413 sortedPkgs.add(pkg); 5414 it.remove(); 5415 } 5416 } 5417 // Give priority to system apps. 5418 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5419 PackageParser.Package pkg = it.next(); 5420 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5421 if (DEBUG_DEXOPT) { 5422 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5423 } 5424 sortedPkgs.add(pkg); 5425 it.remove(); 5426 } 5427 } 5428 // Give priority to updated system apps. 5429 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5430 PackageParser.Package pkg = it.next(); 5431 if (pkg.isUpdatedSystemApp()) { 5432 if (DEBUG_DEXOPT) { 5433 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5434 } 5435 sortedPkgs.add(pkg); 5436 it.remove(); 5437 } 5438 } 5439 // Give priority to apps that listen for boot complete. 5440 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5441 pkgNames = getPackageNamesForIntent(intent); 5442 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5443 PackageParser.Package pkg = it.next(); 5444 if (pkgNames.contains(pkg.packageName)) { 5445 if (DEBUG_DEXOPT) { 5446 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5447 } 5448 sortedPkgs.add(pkg); 5449 it.remove(); 5450 } 5451 } 5452 // Filter out packages that aren't recently used. 5453 filterRecentlyUsedApps(pkgs); 5454 // Add all remaining apps. 5455 for (PackageParser.Package pkg : pkgs) { 5456 if (DEBUG_DEXOPT) { 5457 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5458 } 5459 sortedPkgs.add(pkg); 5460 } 5461 5462 // If we want to be lazy, filter everything that wasn't recently used. 5463 if (mLazyDexOpt) { 5464 filterRecentlyUsedApps(sortedPkgs); 5465 } 5466 5467 int i = 0; 5468 int total = sortedPkgs.size(); 5469 File dataDir = Environment.getDataDirectory(); 5470 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5471 if (lowThreshold == 0) { 5472 throw new IllegalStateException("Invalid low memory threshold"); 5473 } 5474 for (PackageParser.Package pkg : sortedPkgs) { 5475 long usableSpace = dataDir.getUsableSpace(); 5476 if (usableSpace < lowThreshold) { 5477 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5478 break; 5479 } 5480 performBootDexOpt(pkg, ++i, total); 5481 } 5482 } 5483 } 5484 5485 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5486 // Filter out packages that aren't recently used. 5487 // 5488 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5489 // should do a full dexopt. 5490 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5491 int total = pkgs.size(); 5492 int skipped = 0; 5493 long now = System.currentTimeMillis(); 5494 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5495 PackageParser.Package pkg = i.next(); 5496 long then = pkg.mLastPackageUsageTimeInMills; 5497 if (then + mDexOptLRUThresholdInMills < now) { 5498 if (DEBUG_DEXOPT) { 5499 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5500 ((then == 0) ? "never" : new Date(then))); 5501 } 5502 i.remove(); 5503 skipped++; 5504 } 5505 } 5506 if (DEBUG_DEXOPT) { 5507 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5508 } 5509 } 5510 } 5511 5512 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5513 List<ResolveInfo> ris = null; 5514 try { 5515 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5516 intent, null, 0, UserHandle.USER_OWNER); 5517 } catch (RemoteException e) { 5518 } 5519 ArraySet<String> pkgNames = new ArraySet<String>(); 5520 if (ris != null) { 5521 for (ResolveInfo ri : ris) { 5522 pkgNames.add(ri.activityInfo.packageName); 5523 } 5524 } 5525 return pkgNames; 5526 } 5527 5528 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5529 if (DEBUG_DEXOPT) { 5530 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5531 } 5532 if (!isFirstBoot()) { 5533 try { 5534 ActivityManagerNative.getDefault().showBootMessage( 5535 mContext.getResources().getString(R.string.android_upgrading_apk, 5536 curr, total), true); 5537 } catch (RemoteException e) { 5538 } 5539 } 5540 PackageParser.Package p = pkg; 5541 synchronized (mInstallLock) { 5542 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5543 false /* force dex */, false /* defer */, true /* include dependencies */); 5544 } 5545 } 5546 5547 @Override 5548 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5549 return performDexOpt(packageName, instructionSet, false); 5550 } 5551 5552 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5553 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5554 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5555 if (!dexopt && !updateUsage) { 5556 // We aren't going to dexopt or update usage, so bail early. 5557 return false; 5558 } 5559 PackageParser.Package p; 5560 final String targetInstructionSet; 5561 synchronized (mPackages) { 5562 p = mPackages.get(packageName); 5563 if (p == null) { 5564 return false; 5565 } 5566 if (updateUsage) { 5567 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5568 } 5569 mPackageUsage.write(false); 5570 if (!dexopt) { 5571 // We aren't going to dexopt, so bail early. 5572 return false; 5573 } 5574 5575 targetInstructionSet = instructionSet != null ? instructionSet : 5576 getPrimaryInstructionSet(p.applicationInfo); 5577 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5578 return false; 5579 } 5580 } 5581 5582 synchronized (mInstallLock) { 5583 final String[] instructionSets = new String[] { targetInstructionSet }; 5584 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5585 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5586 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5587 } 5588 } 5589 5590 public ArraySet<String> getPackagesThatNeedDexOpt() { 5591 ArraySet<String> pkgs = null; 5592 synchronized (mPackages) { 5593 for (PackageParser.Package p : mPackages.values()) { 5594 if (DEBUG_DEXOPT) { 5595 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5596 } 5597 if (!p.mDexOptPerformed.isEmpty()) { 5598 continue; 5599 } 5600 if (pkgs == null) { 5601 pkgs = new ArraySet<String>(); 5602 } 5603 pkgs.add(p.packageName); 5604 } 5605 } 5606 return pkgs; 5607 } 5608 5609 public void shutdown() { 5610 mPackageUsage.write(true); 5611 } 5612 5613 @Override 5614 public void forceDexOpt(String packageName) { 5615 enforceSystemOrRoot("forceDexOpt"); 5616 5617 PackageParser.Package pkg; 5618 synchronized (mPackages) { 5619 pkg = mPackages.get(packageName); 5620 if (pkg == null) { 5621 throw new IllegalArgumentException("Missing package: " + packageName); 5622 } 5623 } 5624 5625 synchronized (mInstallLock) { 5626 final String[] instructionSets = new String[] { 5627 getPrimaryInstructionSet(pkg.applicationInfo) }; 5628 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5629 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5630 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5631 throw new IllegalStateException("Failed to dexopt: " + res); 5632 } 5633 } 5634 } 5635 5636 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5637 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5638 Slog.w(TAG, "Unable to update from " + oldPkg.name 5639 + " to " + newPkg.packageName 5640 + ": old package not in system partition"); 5641 return false; 5642 } else if (mPackages.get(oldPkg.name) != null) { 5643 Slog.w(TAG, "Unable to update from " + oldPkg.name 5644 + " to " + newPkg.packageName 5645 + ": old package still exists"); 5646 return false; 5647 } 5648 return true; 5649 } 5650 5651 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5652 int[] users = sUserManager.getUserIds(); 5653 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5654 if (res < 0) { 5655 return res; 5656 } 5657 for (int user : users) { 5658 if (user != 0) { 5659 res = mInstaller.createUserData(volumeUuid, packageName, 5660 UserHandle.getUid(user, uid), user, seinfo); 5661 if (res < 0) { 5662 return res; 5663 } 5664 } 5665 } 5666 return res; 5667 } 5668 5669 private int removeDataDirsLI(String volumeUuid, String packageName) { 5670 int[] users = sUserManager.getUserIds(); 5671 int res = 0; 5672 for (int user : users) { 5673 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5674 if (resInner < 0) { 5675 res = resInner; 5676 } 5677 } 5678 5679 return res; 5680 } 5681 5682 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5683 int[] users = sUserManager.getUserIds(); 5684 int res = 0; 5685 for (int user : users) { 5686 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5687 if (resInner < 0) { 5688 res = resInner; 5689 } 5690 } 5691 return res; 5692 } 5693 5694 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5695 PackageParser.Package changingLib) { 5696 if (file.path != null) { 5697 usesLibraryFiles.add(file.path); 5698 return; 5699 } 5700 PackageParser.Package p = mPackages.get(file.apk); 5701 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5702 // If we are doing this while in the middle of updating a library apk, 5703 // then we need to make sure to use that new apk for determining the 5704 // dependencies here. (We haven't yet finished committing the new apk 5705 // to the package manager state.) 5706 if (p == null || p.packageName.equals(changingLib.packageName)) { 5707 p = changingLib; 5708 } 5709 } 5710 if (p != null) { 5711 usesLibraryFiles.addAll(p.getAllCodePaths()); 5712 } 5713 } 5714 5715 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5716 PackageParser.Package changingLib) throws PackageManagerException { 5717 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5718 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5719 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5720 for (int i=0; i<N; i++) { 5721 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5722 if (file == null) { 5723 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5724 "Package " + pkg.packageName + " requires unavailable shared library " 5725 + pkg.usesLibraries.get(i) + "; failing!"); 5726 } 5727 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5728 } 5729 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5730 for (int i=0; i<N; i++) { 5731 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5732 if (file == null) { 5733 Slog.w(TAG, "Package " + pkg.packageName 5734 + " desires unavailable shared library " 5735 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5736 } else { 5737 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5738 } 5739 } 5740 N = usesLibraryFiles.size(); 5741 if (N > 0) { 5742 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5743 } else { 5744 pkg.usesLibraryFiles = null; 5745 } 5746 } 5747 } 5748 5749 private static boolean hasString(List<String> list, List<String> which) { 5750 if (list == null) { 5751 return false; 5752 } 5753 for (int i=list.size()-1; i>=0; i--) { 5754 for (int j=which.size()-1; j>=0; j--) { 5755 if (which.get(j).equals(list.get(i))) { 5756 return true; 5757 } 5758 } 5759 } 5760 return false; 5761 } 5762 5763 private void updateAllSharedLibrariesLPw() { 5764 for (PackageParser.Package pkg : mPackages.values()) { 5765 try { 5766 updateSharedLibrariesLPw(pkg, null); 5767 } catch (PackageManagerException e) { 5768 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5769 } 5770 } 5771 } 5772 5773 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5774 PackageParser.Package changingPkg) { 5775 ArrayList<PackageParser.Package> res = null; 5776 for (PackageParser.Package pkg : mPackages.values()) { 5777 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5778 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5779 if (res == null) { 5780 res = new ArrayList<PackageParser.Package>(); 5781 } 5782 res.add(pkg); 5783 try { 5784 updateSharedLibrariesLPw(pkg, changingPkg); 5785 } catch (PackageManagerException e) { 5786 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5787 } 5788 } 5789 } 5790 return res; 5791 } 5792 5793 /** 5794 * Derive the value of the {@code cpuAbiOverride} based on the provided 5795 * value and an optional stored value from the package settings. 5796 */ 5797 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5798 String cpuAbiOverride = null; 5799 5800 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5801 cpuAbiOverride = null; 5802 } else if (abiOverride != null) { 5803 cpuAbiOverride = abiOverride; 5804 } else if (settings != null) { 5805 cpuAbiOverride = settings.cpuAbiOverrideString; 5806 } 5807 5808 return cpuAbiOverride; 5809 } 5810 5811 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5812 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5813 boolean success = false; 5814 try { 5815 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5816 currentTime, user); 5817 success = true; 5818 return res; 5819 } finally { 5820 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5821 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5822 } 5823 } 5824 } 5825 5826 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5827 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5828 final File scanFile = new File(pkg.codePath); 5829 if (pkg.applicationInfo.getCodePath() == null || 5830 pkg.applicationInfo.getResourcePath() == null) { 5831 // Bail out. The resource and code paths haven't been set. 5832 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5833 "Code and resource paths haven't been set correctly"); 5834 } 5835 5836 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5837 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5838 } else { 5839 // Only allow system apps to be flagged as core apps. 5840 pkg.coreApp = false; 5841 } 5842 5843 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5844 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5845 } 5846 5847 if (mCustomResolverComponentName != null && 5848 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5849 setUpCustomResolverActivity(pkg); 5850 } 5851 5852 if (pkg.packageName.equals("android")) { 5853 synchronized (mPackages) { 5854 if (mAndroidApplication != null) { 5855 Slog.w(TAG, "*************************************************"); 5856 Slog.w(TAG, "Core android package being redefined. Skipping."); 5857 Slog.w(TAG, " file=" + scanFile); 5858 Slog.w(TAG, "*************************************************"); 5859 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5860 "Core android package being redefined. Skipping."); 5861 } 5862 5863 // Set up information for our fall-back user intent resolution activity. 5864 mPlatformPackage = pkg; 5865 pkg.mVersionCode = mSdkVersion; 5866 mAndroidApplication = pkg.applicationInfo; 5867 5868 if (!mResolverReplaced) { 5869 mResolveActivity.applicationInfo = mAndroidApplication; 5870 mResolveActivity.name = ResolverActivity.class.getName(); 5871 mResolveActivity.packageName = mAndroidApplication.packageName; 5872 mResolveActivity.processName = "system:ui"; 5873 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5874 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5875 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5876 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5877 mResolveActivity.exported = true; 5878 mResolveActivity.enabled = true; 5879 mResolveInfo.activityInfo = mResolveActivity; 5880 mResolveInfo.priority = 0; 5881 mResolveInfo.preferredOrder = 0; 5882 mResolveInfo.match = 0; 5883 mResolveComponentName = new ComponentName( 5884 mAndroidApplication.packageName, mResolveActivity.name); 5885 } 5886 } 5887 } 5888 5889 if (DEBUG_PACKAGE_SCANNING) { 5890 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5891 Log.d(TAG, "Scanning package " + pkg.packageName); 5892 } 5893 5894 if (mPackages.containsKey(pkg.packageName) 5895 || mSharedLibraries.containsKey(pkg.packageName)) { 5896 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5897 "Application package " + pkg.packageName 5898 + " already installed. Skipping duplicate."); 5899 } 5900 5901 // If we're only installing presumed-existing packages, require that the 5902 // scanned APK is both already known and at the path previously established 5903 // for it. Previously unknown packages we pick up normally, but if we have an 5904 // a priori expectation about this package's install presence, enforce it. 5905 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5906 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5907 if (known != null) { 5908 if (DEBUG_PACKAGE_SCANNING) { 5909 Log.d(TAG, "Examining " + pkg.codePath 5910 + " and requiring known paths " + known.codePathString 5911 + " & " + known.resourcePathString); 5912 } 5913 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 5914 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 5915 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 5916 "Application package " + pkg.packageName 5917 + " found at " + pkg.applicationInfo.getCodePath() 5918 + " but expected at " + known.codePathString + "; ignoring."); 5919 } 5920 } 5921 } 5922 5923 // Initialize package source and resource directories 5924 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5925 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5926 5927 SharedUserSetting suid = null; 5928 PackageSetting pkgSetting = null; 5929 5930 if (!isSystemApp(pkg)) { 5931 // Only system apps can use these features. 5932 pkg.mOriginalPackages = null; 5933 pkg.mRealPackage = null; 5934 pkg.mAdoptPermissions = null; 5935 } 5936 5937 // writer 5938 synchronized (mPackages) { 5939 if (pkg.mSharedUserId != null) { 5940 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5941 if (suid == null) { 5942 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5943 "Creating application package " + pkg.packageName 5944 + " for shared user failed"); 5945 } 5946 if (DEBUG_PACKAGE_SCANNING) { 5947 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5948 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5949 + "): packages=" + suid.packages); 5950 } 5951 } 5952 5953 // Check if we are renaming from an original package name. 5954 PackageSetting origPackage = null; 5955 String realName = null; 5956 if (pkg.mOriginalPackages != null) { 5957 // This package may need to be renamed to a previously 5958 // installed name. Let's check on that... 5959 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5960 if (pkg.mOriginalPackages.contains(renamed)) { 5961 // This package had originally been installed as the 5962 // original name, and we have already taken care of 5963 // transitioning to the new one. Just update the new 5964 // one to continue using the old name. 5965 realName = pkg.mRealPackage; 5966 if (!pkg.packageName.equals(renamed)) { 5967 // Callers into this function may have already taken 5968 // care of renaming the package; only do it here if 5969 // it is not already done. 5970 pkg.setPackageName(renamed); 5971 } 5972 5973 } else { 5974 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5975 if ((origPackage = mSettings.peekPackageLPr( 5976 pkg.mOriginalPackages.get(i))) != null) { 5977 // We do have the package already installed under its 5978 // original name... should we use it? 5979 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5980 // New package is not compatible with original. 5981 origPackage = null; 5982 continue; 5983 } else if (origPackage.sharedUser != null) { 5984 // Make sure uid is compatible between packages. 5985 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5986 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5987 + " to " + pkg.packageName + ": old uid " 5988 + origPackage.sharedUser.name 5989 + " differs from " + pkg.mSharedUserId); 5990 origPackage = null; 5991 continue; 5992 } 5993 } else { 5994 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5995 + pkg.packageName + " to old name " + origPackage.name); 5996 } 5997 break; 5998 } 5999 } 6000 } 6001 } 6002 6003 if (mTransferedPackages.contains(pkg.packageName)) { 6004 Slog.w(TAG, "Package " + pkg.packageName 6005 + " was transferred to another, but its .apk remains"); 6006 } 6007 6008 // Just create the setting, don't add it yet. For already existing packages 6009 // the PkgSetting exists already and doesn't have to be created. 6010 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6011 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6012 pkg.applicationInfo.primaryCpuAbi, 6013 pkg.applicationInfo.secondaryCpuAbi, 6014 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6015 user, false); 6016 if (pkgSetting == null) { 6017 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6018 "Creating application package " + pkg.packageName + " failed"); 6019 } 6020 6021 if (pkgSetting.origPackage != null) { 6022 // If we are first transitioning from an original package, 6023 // fix up the new package's name now. We need to do this after 6024 // looking up the package under its new name, so getPackageLP 6025 // can take care of fiddling things correctly. 6026 pkg.setPackageName(origPackage.name); 6027 6028 // File a report about this. 6029 String msg = "New package " + pkgSetting.realName 6030 + " renamed to replace old package " + pkgSetting.name; 6031 reportSettingsProblem(Log.WARN, msg); 6032 6033 // Make a note of it. 6034 mTransferedPackages.add(origPackage.name); 6035 6036 // No longer need to retain this. 6037 pkgSetting.origPackage = null; 6038 } 6039 6040 if (realName != null) { 6041 // Make a note of it. 6042 mTransferedPackages.add(pkg.packageName); 6043 } 6044 6045 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6047 } 6048 6049 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6050 // Check all shared libraries and map to their actual file path. 6051 // We only do this here for apps not on a system dir, because those 6052 // are the only ones that can fail an install due to this. We 6053 // will take care of the system apps by updating all of their 6054 // library paths after the scan is done. 6055 updateSharedLibrariesLPw(pkg, null); 6056 } 6057 6058 if (mFoundPolicyFile) { 6059 SELinuxMMAC.assignSeinfoValue(pkg); 6060 } 6061 6062 pkg.applicationInfo.uid = pkgSetting.appId; 6063 pkg.mExtras = pkgSetting; 6064 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 6065 try { 6066 verifySignaturesLP(pkgSetting, pkg); 6067 // We just determined the app is signed correctly, so bring 6068 // over the latest parsed certs. 6069 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6070 } catch (PackageManagerException e) { 6071 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6072 throw e; 6073 } 6074 // The signature has changed, but this package is in the system 6075 // image... let's recover! 6076 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6077 // However... if this package is part of a shared user, but it 6078 // doesn't match the signature of the shared user, let's fail. 6079 // What this means is that you can't change the signatures 6080 // associated with an overall shared user, which doesn't seem all 6081 // that unreasonable. 6082 if (pkgSetting.sharedUser != null) { 6083 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6084 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6085 throw new PackageManagerException( 6086 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6087 "Signature mismatch for shared user : " 6088 + pkgSetting.sharedUser); 6089 } 6090 } 6091 // File a report about this. 6092 String msg = "System package " + pkg.packageName 6093 + " signature changed; retaining data."; 6094 reportSettingsProblem(Log.WARN, msg); 6095 } 6096 } else { 6097 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6098 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6099 + pkg.packageName + " upgrade keys do not match the " 6100 + "previously installed version"); 6101 } else { 6102 // We just determined the app is signed correctly, so bring 6103 // over the latest parsed certs. 6104 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6105 } 6106 } 6107 // Verify that this new package doesn't have any content providers 6108 // that conflict with existing packages. Only do this if the 6109 // package isn't already installed, since we don't want to break 6110 // things that are installed. 6111 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6112 final int N = pkg.providers.size(); 6113 int i; 6114 for (i=0; i<N; i++) { 6115 PackageParser.Provider p = pkg.providers.get(i); 6116 if (p.info.authority != null) { 6117 String names[] = p.info.authority.split(";"); 6118 for (int j = 0; j < names.length; j++) { 6119 if (mProvidersByAuthority.containsKey(names[j])) { 6120 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6121 final String otherPackageName = 6122 ((other != null && other.getComponentName() != null) ? 6123 other.getComponentName().getPackageName() : "?"); 6124 throw new PackageManagerException( 6125 INSTALL_FAILED_CONFLICTING_PROVIDER, 6126 "Can't install because provider name " + names[j] 6127 + " (in package " + pkg.applicationInfo.packageName 6128 + ") is already used by " + otherPackageName); 6129 } 6130 } 6131 } 6132 } 6133 } 6134 6135 if (pkg.mAdoptPermissions != null) { 6136 // This package wants to adopt ownership of permissions from 6137 // another package. 6138 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6139 final String origName = pkg.mAdoptPermissions.get(i); 6140 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6141 if (orig != null) { 6142 if (verifyPackageUpdateLPr(orig, pkg)) { 6143 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6144 + pkg.packageName); 6145 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6146 } 6147 } 6148 } 6149 } 6150 } 6151 6152 final String pkgName = pkg.packageName; 6153 6154 final long scanFileTime = scanFile.lastModified(); 6155 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6156 pkg.applicationInfo.processName = fixProcessName( 6157 pkg.applicationInfo.packageName, 6158 pkg.applicationInfo.processName, 6159 pkg.applicationInfo.uid); 6160 6161 File dataPath; 6162 if (mPlatformPackage == pkg) { 6163 // The system package is special. 6164 dataPath = new File(Environment.getDataDirectory(), "system"); 6165 6166 pkg.applicationInfo.dataDir = dataPath.getPath(); 6167 6168 } else { 6169 // This is a normal package, need to make its data directory. 6170 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6171 UserHandle.USER_OWNER); 6172 6173 boolean uidError = false; 6174 if (dataPath.exists()) { 6175 int currentUid = 0; 6176 try { 6177 StructStat stat = Os.stat(dataPath.getPath()); 6178 currentUid = stat.st_uid; 6179 } catch (ErrnoException e) { 6180 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6181 } 6182 6183 // If we have mismatched owners for the data path, we have a problem. 6184 if (currentUid != pkg.applicationInfo.uid) { 6185 boolean recovered = false; 6186 if (currentUid == 0) { 6187 // The directory somehow became owned by root. Wow. 6188 // This is probably because the system was stopped while 6189 // installd was in the middle of messing with its libs 6190 // directory. Ask installd to fix that. 6191 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6192 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6193 if (ret >= 0) { 6194 recovered = true; 6195 String msg = "Package " + pkg.packageName 6196 + " unexpectedly changed to uid 0; recovered to " + 6197 + pkg.applicationInfo.uid; 6198 reportSettingsProblem(Log.WARN, msg); 6199 } 6200 } 6201 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6202 || (scanFlags&SCAN_BOOTING) != 0)) { 6203 // If this is a system app, we can at least delete its 6204 // current data so the application will still work. 6205 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6206 if (ret >= 0) { 6207 // TODO: Kill the processes first 6208 // Old data gone! 6209 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6210 ? "System package " : "Third party package "; 6211 String msg = prefix + pkg.packageName 6212 + " has changed from uid: " 6213 + currentUid + " to " 6214 + pkg.applicationInfo.uid + "; old data erased"; 6215 reportSettingsProblem(Log.WARN, msg); 6216 recovered = true; 6217 6218 // And now re-install the app. 6219 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6220 pkg.applicationInfo.seinfo); 6221 if (ret == -1) { 6222 // Ack should not happen! 6223 msg = prefix + pkg.packageName 6224 + " could not have data directory re-created after delete."; 6225 reportSettingsProblem(Log.WARN, msg); 6226 throw new PackageManagerException( 6227 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6228 } 6229 } 6230 if (!recovered) { 6231 mHasSystemUidErrors = true; 6232 } 6233 } else if (!recovered) { 6234 // If we allow this install to proceed, we will be broken. 6235 // Abort, abort! 6236 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6237 "scanPackageLI"); 6238 } 6239 if (!recovered) { 6240 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6241 + pkg.applicationInfo.uid + "/fs_" 6242 + currentUid; 6243 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6244 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6245 String msg = "Package " + pkg.packageName 6246 + " has mismatched uid: " 6247 + currentUid + " on disk, " 6248 + pkg.applicationInfo.uid + " in settings"; 6249 // writer 6250 synchronized (mPackages) { 6251 mSettings.mReadMessages.append(msg); 6252 mSettings.mReadMessages.append('\n'); 6253 uidError = true; 6254 if (!pkgSetting.uidError) { 6255 reportSettingsProblem(Log.ERROR, msg); 6256 } 6257 } 6258 } 6259 } 6260 pkg.applicationInfo.dataDir = dataPath.getPath(); 6261 if (mShouldRestoreconData) { 6262 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6263 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6264 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6265 } 6266 } else { 6267 if (DEBUG_PACKAGE_SCANNING) { 6268 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6269 Log.v(TAG, "Want this data dir: " + dataPath); 6270 } 6271 //invoke installer to do the actual installation 6272 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6273 pkg.applicationInfo.seinfo); 6274 if (ret < 0) { 6275 // Error from installer 6276 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6277 "Unable to create data dirs [errorCode=" + ret + "]"); 6278 } 6279 6280 if (dataPath.exists()) { 6281 pkg.applicationInfo.dataDir = dataPath.getPath(); 6282 } else { 6283 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6284 pkg.applicationInfo.dataDir = null; 6285 } 6286 } 6287 6288 pkgSetting.uidError = uidError; 6289 } 6290 6291 final String path = scanFile.getPath(); 6292 final String codePath = pkg.applicationInfo.getCodePath(); 6293 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6294 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 6295 setBundledAppAbisAndRoots(pkg, pkgSetting); 6296 6297 // If we haven't found any native libraries for the app, check if it has 6298 // renderscript code. We'll need to force the app to 32 bit if it has 6299 // renderscript bitcode. 6300 if (pkg.applicationInfo.primaryCpuAbi == null 6301 && pkg.applicationInfo.secondaryCpuAbi == null 6302 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6303 NativeLibraryHelper.Handle handle = null; 6304 try { 6305 handle = NativeLibraryHelper.Handle.create(scanFile); 6306 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6307 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6308 } 6309 } catch (IOException ioe) { 6310 Slog.w(TAG, "Error scanning system app : " + ioe); 6311 } finally { 6312 IoUtils.closeQuietly(handle); 6313 } 6314 } 6315 6316 setNativeLibraryPaths(pkg); 6317 } else { 6318 // TODO: We can probably be smarter about this stuff. For installed apps, 6319 // we can calculate this information at install time once and for all. For 6320 // system apps, we can probably assume that this information doesn't change 6321 // after the first boot scan. As things stand, we do lots of unnecessary work. 6322 6323 // Give ourselves some initial paths; we'll come back for another 6324 // pass once we've determined ABI below. 6325 setNativeLibraryPaths(pkg); 6326 6327 final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg); 6328 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6329 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6330 6331 NativeLibraryHelper.Handle handle = null; 6332 try { 6333 handle = NativeLibraryHelper.Handle.create(scanFile); 6334 // TODO(multiArch): This can be null for apps that didn't go through the 6335 // usual installation process. We can calculate it again, like we 6336 // do during install time. 6337 // 6338 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6339 // unnecessary. 6340 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6341 6342 // Null out the abis so that they can be recalculated. 6343 pkg.applicationInfo.primaryCpuAbi = null; 6344 pkg.applicationInfo.secondaryCpuAbi = null; 6345 if (isMultiArch(pkg.applicationInfo)) { 6346 // Warn if we've set an abiOverride for multi-lib packages.. 6347 // By definition, we need to copy both 32 and 64 bit libraries for 6348 // such packages. 6349 if (pkg.cpuAbiOverride != null 6350 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 6351 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 6352 } 6353 6354 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 6355 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 6356 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 6357 if (isAsec) { 6358 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 6359 } else { 6360 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6361 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 6362 useIsaSpecificSubdirs); 6363 } 6364 } 6365 6366 maybeThrowExceptionForMultiArchCopy( 6367 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 6368 6369 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 6370 if (isAsec) { 6371 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 6372 } else { 6373 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6374 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 6375 useIsaSpecificSubdirs); 6376 } 6377 } 6378 6379 maybeThrowExceptionForMultiArchCopy( 6380 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 6381 6382 if (abi64 >= 0) { 6383 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 6384 } 6385 6386 if (abi32 >= 0) { 6387 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 6388 if (abi64 >= 0) { 6389 pkg.applicationInfo.secondaryCpuAbi = abi; 6390 } else { 6391 pkg.applicationInfo.primaryCpuAbi = abi; 6392 } 6393 } 6394 } else { 6395 String[] abiList = (cpuAbiOverride != null) ? 6396 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 6397 6398 // Enable gross and lame hacks for apps that are built with old 6399 // SDK tools. We must scan their APKs for renderscript bitcode and 6400 // not launch them if it's present. Don't bother checking on devices 6401 // that don't have 64 bit support. 6402 boolean needsRenderScriptOverride = false; 6403 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 6404 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 6405 abiList = Build.SUPPORTED_32_BIT_ABIS; 6406 needsRenderScriptOverride = true; 6407 } 6408 6409 final int copyRet; 6410 if (isAsec) { 6411 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6412 } else { 6413 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 6414 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 6415 } 6416 6417 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 6418 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6419 "Error unpackaging native libs for app, errorCode=" + copyRet); 6420 } 6421 6422 if (copyRet >= 0) { 6423 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 6424 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 6425 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 6426 } else if (needsRenderScriptOverride) { 6427 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 6428 } 6429 } 6430 } catch (IOException ioe) { 6431 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 6432 } finally { 6433 IoUtils.closeQuietly(handle); 6434 } 6435 6436 // Now that we've calculated the ABIs and determined if it's an internal app, 6437 // we will go ahead and populate the nativeLibraryPath. 6438 setNativeLibraryPaths(pkg); 6439 6440 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6441 final int[] userIds = sUserManager.getUserIds(); 6442 synchronized (mInstallLock) { 6443 // Create a native library symlink only if we have native libraries 6444 // and if the native libraries are 32 bit libraries. We do not provide 6445 // this symlink for 64 bit libraries. 6446 if (pkg.applicationInfo.primaryCpuAbi != null && 6447 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6448 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6449 for (int userId : userIds) { 6450 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6451 nativeLibPath, userId) < 0) { 6452 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6453 "Failed linking native library dir (user=" + userId + ")"); 6454 } 6455 } 6456 } 6457 } 6458 } 6459 6460 // This is a special case for the "system" package, where the ABI is 6461 // dictated by the zygote configuration (and init.rc). We should keep track 6462 // of this ABI so that we can deal with "normal" applications that run under 6463 // the same UID correctly. 6464 if (mPlatformPackage == pkg) { 6465 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6466 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6467 } 6468 6469 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6470 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6471 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6472 // Copy the derived override back to the parsed package, so that we can 6473 // update the package settings accordingly. 6474 pkg.cpuAbiOverride = cpuAbiOverride; 6475 6476 if (DEBUG_ABI_SELECTION) { 6477 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6478 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6479 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6480 } 6481 6482 // Push the derived path down into PackageSettings so we know what to 6483 // clean up at uninstall time. 6484 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6485 6486 if (DEBUG_ABI_SELECTION) { 6487 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6488 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6489 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6490 } 6491 6492 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6493 // We don't do this here during boot because we can do it all 6494 // at once after scanning all existing packages. 6495 // 6496 // We also do this *before* we perform dexopt on this package, so that 6497 // we can avoid redundant dexopts, and also to make sure we've got the 6498 // code and package path correct. 6499 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6500 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6501 } 6502 6503 if ((scanFlags & SCAN_NO_DEX) == 0) { 6504 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6505 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6506 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6507 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6508 } 6509 } 6510 if (mFactoryTest && pkg.requestedPermissions.contains( 6511 android.Manifest.permission.FACTORY_TEST)) { 6512 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6513 } 6514 6515 ArrayList<PackageParser.Package> clientLibPkgs = null; 6516 6517 // writer 6518 synchronized (mPackages) { 6519 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6520 // Only system apps can add new shared libraries. 6521 if (pkg.libraryNames != null) { 6522 for (int i=0; i<pkg.libraryNames.size(); i++) { 6523 String name = pkg.libraryNames.get(i); 6524 boolean allowed = false; 6525 if (pkg.isUpdatedSystemApp()) { 6526 // New library entries can only be added through the 6527 // system image. This is important to get rid of a lot 6528 // of nasty edge cases: for example if we allowed a non- 6529 // system update of the app to add a library, then uninstalling 6530 // the update would make the library go away, and assumptions 6531 // we made such as through app install filtering would now 6532 // have allowed apps on the device which aren't compatible 6533 // with it. Better to just have the restriction here, be 6534 // conservative, and create many fewer cases that can negatively 6535 // impact the user experience. 6536 final PackageSetting sysPs = mSettings 6537 .getDisabledSystemPkgLPr(pkg.packageName); 6538 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6539 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6540 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6541 allowed = true; 6542 allowed = true; 6543 break; 6544 } 6545 } 6546 } 6547 } else { 6548 allowed = true; 6549 } 6550 if (allowed) { 6551 if (!mSharedLibraries.containsKey(name)) { 6552 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6553 } else if (!name.equals(pkg.packageName)) { 6554 Slog.w(TAG, "Package " + pkg.packageName + " library " 6555 + name + " already exists; skipping"); 6556 } 6557 } else { 6558 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6559 + name + " that is not declared on system image; skipping"); 6560 } 6561 } 6562 if ((scanFlags&SCAN_BOOTING) == 0) { 6563 // If we are not booting, we need to update any applications 6564 // that are clients of our shared library. If we are booting, 6565 // this will all be done once the scan is complete. 6566 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6567 } 6568 } 6569 } 6570 } 6571 6572 // We also need to dexopt any apps that are dependent on this library. Note that 6573 // if these fail, we should abort the install since installing the library will 6574 // result in some apps being broken. 6575 if (clientLibPkgs != null) { 6576 if ((scanFlags & SCAN_NO_DEX) == 0) { 6577 for (int i = 0; i < clientLibPkgs.size(); i++) { 6578 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6579 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6580 null /* instruction sets */, forceDex, 6581 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6582 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6583 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6584 "scanPackageLI failed to dexopt clientLibPkgs"); 6585 } 6586 } 6587 } 6588 } 6589 6590 // Also need to kill any apps that are dependent on the library. 6591 if (clientLibPkgs != null) { 6592 for (int i=0; i<clientLibPkgs.size(); i++) { 6593 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6594 killApplication(clientPkg.applicationInfo.packageName, 6595 clientPkg.applicationInfo.uid, "update lib"); 6596 } 6597 } 6598 6599 // writer 6600 synchronized (mPackages) { 6601 // We don't expect installation to fail beyond this point 6602 6603 // Add the new setting to mSettings 6604 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6605 // Add the new setting to mPackages 6606 mPackages.put(pkg.applicationInfo.packageName, pkg); 6607 // Make sure we don't accidentally delete its data. 6608 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6609 while (iter.hasNext()) { 6610 PackageCleanItem item = iter.next(); 6611 if (pkgName.equals(item.packageName)) { 6612 iter.remove(); 6613 } 6614 } 6615 6616 // Take care of first install / last update times. 6617 if (currentTime != 0) { 6618 if (pkgSetting.firstInstallTime == 0) { 6619 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6620 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6621 pkgSetting.lastUpdateTime = currentTime; 6622 } 6623 } else if (pkgSetting.firstInstallTime == 0) { 6624 // We need *something*. Take time time stamp of the file. 6625 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6626 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6627 if (scanFileTime != pkgSetting.timeStamp) { 6628 // A package on the system image has changed; consider this 6629 // to be an update. 6630 pkgSetting.lastUpdateTime = scanFileTime; 6631 } 6632 } 6633 6634 // Add the package's KeySets to the global KeySetManagerService 6635 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6636 try { 6637 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6638 if (pkg.mKeySetMapping != null) { 6639 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6640 if (pkg.mUpgradeKeySets != null) { 6641 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6642 } 6643 } 6644 } catch (NullPointerException e) { 6645 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6646 } catch (IllegalArgumentException e) { 6647 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6648 } 6649 6650 int N = pkg.providers.size(); 6651 StringBuilder r = null; 6652 int i; 6653 for (i=0; i<N; i++) { 6654 PackageParser.Provider p = pkg.providers.get(i); 6655 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6656 p.info.processName, pkg.applicationInfo.uid); 6657 mProviders.addProvider(p); 6658 p.syncable = p.info.isSyncable; 6659 if (p.info.authority != null) { 6660 String names[] = p.info.authority.split(";"); 6661 p.info.authority = null; 6662 for (int j = 0; j < names.length; j++) { 6663 if (j == 1 && p.syncable) { 6664 // We only want the first authority for a provider to possibly be 6665 // syncable, so if we already added this provider using a different 6666 // authority clear the syncable flag. We copy the provider before 6667 // changing it because the mProviders object contains a reference 6668 // to a provider that we don't want to change. 6669 // Only do this for the second authority since the resulting provider 6670 // object can be the same for all future authorities for this provider. 6671 p = new PackageParser.Provider(p); 6672 p.syncable = false; 6673 } 6674 if (!mProvidersByAuthority.containsKey(names[j])) { 6675 mProvidersByAuthority.put(names[j], p); 6676 if (p.info.authority == null) { 6677 p.info.authority = names[j]; 6678 } else { 6679 p.info.authority = p.info.authority + ";" + names[j]; 6680 } 6681 if (DEBUG_PACKAGE_SCANNING) { 6682 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6683 Log.d(TAG, "Registered content provider: " + names[j] 6684 + ", className = " + p.info.name + ", isSyncable = " 6685 + p.info.isSyncable); 6686 } 6687 } else { 6688 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6689 Slog.w(TAG, "Skipping provider name " + names[j] + 6690 " (in package " + pkg.applicationInfo.packageName + 6691 "): name already used by " 6692 + ((other != null && other.getComponentName() != null) 6693 ? other.getComponentName().getPackageName() : "?")); 6694 } 6695 } 6696 } 6697 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6698 if (r == null) { 6699 r = new StringBuilder(256); 6700 } else { 6701 r.append(' '); 6702 } 6703 r.append(p.info.name); 6704 } 6705 } 6706 if (r != null) { 6707 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6708 } 6709 6710 N = pkg.services.size(); 6711 r = null; 6712 for (i=0; i<N; i++) { 6713 PackageParser.Service s = pkg.services.get(i); 6714 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6715 s.info.processName, pkg.applicationInfo.uid); 6716 mServices.addService(s); 6717 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6718 if (r == null) { 6719 r = new StringBuilder(256); 6720 } else { 6721 r.append(' '); 6722 } 6723 r.append(s.info.name); 6724 } 6725 } 6726 if (r != null) { 6727 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6728 } 6729 6730 N = pkg.receivers.size(); 6731 r = null; 6732 for (i=0; i<N; i++) { 6733 PackageParser.Activity a = pkg.receivers.get(i); 6734 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6735 a.info.processName, pkg.applicationInfo.uid); 6736 mReceivers.addActivity(a, "receiver"); 6737 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6738 if (r == null) { 6739 r = new StringBuilder(256); 6740 } else { 6741 r.append(' '); 6742 } 6743 r.append(a.info.name); 6744 } 6745 } 6746 if (r != null) { 6747 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6748 } 6749 6750 N = pkg.activities.size(); 6751 r = null; 6752 for (i=0; i<N; i++) { 6753 PackageParser.Activity a = pkg.activities.get(i); 6754 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6755 a.info.processName, pkg.applicationInfo.uid); 6756 mActivities.addActivity(a, "activity"); 6757 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6758 if (r == null) { 6759 r = new StringBuilder(256); 6760 } else { 6761 r.append(' '); 6762 } 6763 r.append(a.info.name); 6764 } 6765 } 6766 if (r != null) { 6767 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6768 } 6769 6770 N = pkg.permissionGroups.size(); 6771 r = null; 6772 for (i=0; i<N; i++) { 6773 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6774 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6775 if (cur == null) { 6776 mPermissionGroups.put(pg.info.name, pg); 6777 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6778 if (r == null) { 6779 r = new StringBuilder(256); 6780 } else { 6781 r.append(' '); 6782 } 6783 r.append(pg.info.name); 6784 } 6785 } else { 6786 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6787 + pg.info.packageName + " ignored: original from " 6788 + cur.info.packageName); 6789 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6790 if (r == null) { 6791 r = new StringBuilder(256); 6792 } else { 6793 r.append(' '); 6794 } 6795 r.append("DUP:"); 6796 r.append(pg.info.name); 6797 } 6798 } 6799 } 6800 if (r != null) { 6801 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6802 } 6803 6804 N = pkg.permissions.size(); 6805 r = null; 6806 for (i=0; i<N; i++) { 6807 PackageParser.Permission p = pkg.permissions.get(i); 6808 6809 // Now that permission groups have a special meaning, we ignore permission 6810 // groups for legacy apps to prevent unexpected behavior. In particular, 6811 // permissions for one app being granted to someone just becuase they happen 6812 // to be in a group defined by another app (before this had no implications). 6813 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6814 p.group = mPermissionGroups.get(p.info.group); 6815 // Warn for a permission in an unknown group. 6816 if (p.info.group != null && p.group == null) { 6817 Slog.w(TAG, "Permission " + p.info.name + " from package " 6818 + p.info.packageName + " in an unknown group " + p.info.group); 6819 } 6820 } 6821 6822 ArrayMap<String, BasePermission> permissionMap = 6823 p.tree ? mSettings.mPermissionTrees 6824 : mSettings.mPermissions; 6825 BasePermission bp = permissionMap.get(p.info.name); 6826 6827 // Allow system apps to redefine non-system permissions 6828 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6829 final boolean currentOwnerIsSystem = (bp.perm != null 6830 && isSystemApp(bp.perm.owner)); 6831 if (isSystemApp(p.owner)) { 6832 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6833 // It's a built-in permission and no owner, take ownership now 6834 bp.packageSetting = pkgSetting; 6835 bp.perm = p; 6836 bp.uid = pkg.applicationInfo.uid; 6837 bp.sourcePackage = p.info.packageName; 6838 } else if (!currentOwnerIsSystem) { 6839 String msg = "New decl " + p.owner + " of permission " 6840 + p.info.name + " is system; overriding " + bp.sourcePackage; 6841 reportSettingsProblem(Log.WARN, msg); 6842 bp = null; 6843 } 6844 } 6845 } 6846 6847 if (bp == null) { 6848 bp = new BasePermission(p.info.name, p.info.packageName, 6849 BasePermission.TYPE_NORMAL); 6850 permissionMap.put(p.info.name, bp); 6851 } 6852 6853 if (bp.perm == null) { 6854 if (bp.sourcePackage == null 6855 || bp.sourcePackage.equals(p.info.packageName)) { 6856 BasePermission tree = findPermissionTreeLP(p.info.name); 6857 if (tree == null 6858 || tree.sourcePackage.equals(p.info.packageName)) { 6859 bp.packageSetting = pkgSetting; 6860 bp.perm = p; 6861 bp.uid = pkg.applicationInfo.uid; 6862 bp.sourcePackage = p.info.packageName; 6863 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6864 if (r == null) { 6865 r = new StringBuilder(256); 6866 } else { 6867 r.append(' '); 6868 } 6869 r.append(p.info.name); 6870 } 6871 } else { 6872 Slog.w(TAG, "Permission " + p.info.name + " from package " 6873 + p.info.packageName + " ignored: base tree " 6874 + tree.name + " is from package " 6875 + tree.sourcePackage); 6876 } 6877 } else { 6878 Slog.w(TAG, "Permission " + p.info.name + " from package " 6879 + p.info.packageName + " ignored: original from " 6880 + bp.sourcePackage); 6881 } 6882 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6883 if (r == null) { 6884 r = new StringBuilder(256); 6885 } else { 6886 r.append(' '); 6887 } 6888 r.append("DUP:"); 6889 r.append(p.info.name); 6890 } 6891 if (bp.perm == p) { 6892 bp.protectionLevel = p.info.protectionLevel; 6893 } 6894 } 6895 6896 if (r != null) { 6897 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6898 } 6899 6900 N = pkg.instrumentation.size(); 6901 r = null; 6902 for (i=0; i<N; i++) { 6903 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6904 a.info.packageName = pkg.applicationInfo.packageName; 6905 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6906 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6907 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6908 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6909 a.info.dataDir = pkg.applicationInfo.dataDir; 6910 6911 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6912 // need other information about the application, like the ABI and what not ? 6913 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6914 mInstrumentation.put(a.getComponentName(), a); 6915 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6916 if (r == null) { 6917 r = new StringBuilder(256); 6918 } else { 6919 r.append(' '); 6920 } 6921 r.append(a.info.name); 6922 } 6923 } 6924 if (r != null) { 6925 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6926 } 6927 6928 if (pkg.protectedBroadcasts != null) { 6929 N = pkg.protectedBroadcasts.size(); 6930 for (i=0; i<N; i++) { 6931 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6932 } 6933 } 6934 6935 pkgSetting.setTimeStamp(scanFileTime); 6936 6937 // Create idmap files for pairs of (packages, overlay packages). 6938 // Note: "android", ie framework-res.apk, is handled by native layers. 6939 if (pkg.mOverlayTarget != null) { 6940 // This is an overlay package. 6941 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6942 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6943 mOverlays.put(pkg.mOverlayTarget, 6944 new ArrayMap<String, PackageParser.Package>()); 6945 } 6946 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6947 map.put(pkg.packageName, pkg); 6948 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6949 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6950 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6951 "scanPackageLI failed to createIdmap"); 6952 } 6953 } 6954 } else if (mOverlays.containsKey(pkg.packageName) && 6955 !pkg.packageName.equals("android")) { 6956 // This is a regular package, with one or more known overlay packages. 6957 createIdmapsForPackageLI(pkg); 6958 } 6959 } 6960 6961 return pkg; 6962 } 6963 6964 /** 6965 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6966 * i.e, so that all packages can be run inside a single process if required. 6967 * 6968 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6969 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6970 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6971 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6972 * updating a package that belongs to a shared user. 6973 * 6974 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6975 * adds unnecessary complexity. 6976 */ 6977 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6978 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6979 String requiredInstructionSet = null; 6980 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6981 requiredInstructionSet = VMRuntime.getInstructionSet( 6982 scannedPackage.applicationInfo.primaryCpuAbi); 6983 } 6984 6985 PackageSetting requirer = null; 6986 for (PackageSetting ps : packagesForUser) { 6987 // If packagesForUser contains scannedPackage, we skip it. This will happen 6988 // when scannedPackage is an update of an existing package. Without this check, 6989 // we will never be able to change the ABI of any package belonging to a shared 6990 // user, even if it's compatible with other packages. 6991 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6992 if (ps.primaryCpuAbiString == null) { 6993 continue; 6994 } 6995 6996 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6997 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6998 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6999 // this but there's not much we can do. 7000 String errorMessage = "Instruction set mismatch, " 7001 + ((requirer == null) ? "[caller]" : requirer) 7002 + " requires " + requiredInstructionSet + " whereas " + ps 7003 + " requires " + instructionSet; 7004 Slog.w(TAG, errorMessage); 7005 } 7006 7007 if (requiredInstructionSet == null) { 7008 requiredInstructionSet = instructionSet; 7009 requirer = ps; 7010 } 7011 } 7012 } 7013 7014 if (requiredInstructionSet != null) { 7015 String adjustedAbi; 7016 if (requirer != null) { 7017 // requirer != null implies that either scannedPackage was null or that scannedPackage 7018 // did not require an ABI, in which case we have to adjust scannedPackage to match 7019 // the ABI of the set (which is the same as requirer's ABI) 7020 adjustedAbi = requirer.primaryCpuAbiString; 7021 if (scannedPackage != null) { 7022 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7023 } 7024 } else { 7025 // requirer == null implies that we're updating all ABIs in the set to 7026 // match scannedPackage. 7027 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7028 } 7029 7030 for (PackageSetting ps : packagesForUser) { 7031 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7032 if (ps.primaryCpuAbiString != null) { 7033 continue; 7034 } 7035 7036 ps.primaryCpuAbiString = adjustedAbi; 7037 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7038 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7039 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7040 7041 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7042 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7043 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7044 ps.primaryCpuAbiString = null; 7045 ps.pkg.applicationInfo.primaryCpuAbi = null; 7046 return; 7047 } else { 7048 mInstaller.rmdex(ps.codePathString, 7049 getDexCodeInstructionSet(getPreferredInstructionSet())); 7050 } 7051 } 7052 } 7053 } 7054 } 7055 } 7056 7057 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7058 synchronized (mPackages) { 7059 mResolverReplaced = true; 7060 // Set up information for custom user intent resolution activity. 7061 mResolveActivity.applicationInfo = pkg.applicationInfo; 7062 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7063 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7064 mResolveActivity.processName = pkg.applicationInfo.packageName; 7065 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7066 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7067 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7068 mResolveActivity.theme = 0; 7069 mResolveActivity.exported = true; 7070 mResolveActivity.enabled = true; 7071 mResolveInfo.activityInfo = mResolveActivity; 7072 mResolveInfo.priority = 0; 7073 mResolveInfo.preferredOrder = 0; 7074 mResolveInfo.match = 0; 7075 mResolveComponentName = mCustomResolverComponentName; 7076 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7077 mResolveComponentName); 7078 } 7079 } 7080 7081 private static String calculateBundledApkRoot(final String codePathString) { 7082 final File codePath = new File(codePathString); 7083 final File codeRoot; 7084 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7085 codeRoot = Environment.getRootDirectory(); 7086 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7087 codeRoot = Environment.getOemDirectory(); 7088 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7089 codeRoot = Environment.getVendorDirectory(); 7090 } else { 7091 // Unrecognized code path; take its top real segment as the apk root: 7092 // e.g. /something/app/blah.apk => /something 7093 try { 7094 File f = codePath.getCanonicalFile(); 7095 File parent = f.getParentFile(); // non-null because codePath is a file 7096 File tmp; 7097 while ((tmp = parent.getParentFile()) != null) { 7098 f = parent; 7099 parent = tmp; 7100 } 7101 codeRoot = f; 7102 Slog.w(TAG, "Unrecognized code path " 7103 + codePath + " - using " + codeRoot); 7104 } catch (IOException e) { 7105 // Can't canonicalize the code path -- shenanigans? 7106 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7107 return Environment.getRootDirectory().getPath(); 7108 } 7109 } 7110 return codeRoot.getPath(); 7111 } 7112 7113 /** 7114 * Derive and set the location of native libraries for the given package, 7115 * which varies depending on where and how the package was installed. 7116 */ 7117 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7118 final ApplicationInfo info = pkg.applicationInfo; 7119 final String codePath = pkg.codePath; 7120 final File codeFile = new File(codePath); 7121 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7122 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7123 7124 info.nativeLibraryRootDir = null; 7125 info.nativeLibraryRootRequiresIsa = false; 7126 info.nativeLibraryDir = null; 7127 info.secondaryNativeLibraryDir = null; 7128 7129 if (isApkFile(codeFile)) { 7130 // Monolithic install 7131 if (bundledApp) { 7132 // If "/system/lib64/apkname" exists, assume that is the per-package 7133 // native library directory to use; otherwise use "/system/lib/apkname". 7134 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7135 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7136 getPrimaryInstructionSet(info)); 7137 7138 // This is a bundled system app so choose the path based on the ABI. 7139 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7140 // is just the default path. 7141 final String apkName = deriveCodePathName(codePath); 7142 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7143 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7144 apkName).getAbsolutePath(); 7145 7146 if (info.secondaryCpuAbi != null) { 7147 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7148 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7149 secondaryLibDir, apkName).getAbsolutePath(); 7150 } 7151 } else if (asecApp) { 7152 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7153 .getAbsolutePath(); 7154 } else { 7155 final String apkName = deriveCodePathName(codePath); 7156 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7157 .getAbsolutePath(); 7158 } 7159 7160 info.nativeLibraryRootRequiresIsa = false; 7161 info.nativeLibraryDir = info.nativeLibraryRootDir; 7162 } else { 7163 // Cluster install 7164 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7165 info.nativeLibraryRootRequiresIsa = true; 7166 7167 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7168 getPrimaryInstructionSet(info)).getAbsolutePath(); 7169 7170 if (info.secondaryCpuAbi != null) { 7171 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7172 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7173 } 7174 } 7175 } 7176 7177 /** 7178 * Calculate the abis and roots for a bundled app. These can uniquely 7179 * be determined from the contents of the system partition, i.e whether 7180 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7181 * of this information, and instead assume that the system was built 7182 * sensibly. 7183 */ 7184 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7185 PackageSetting pkgSetting) { 7186 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7187 7188 // If "/system/lib64/apkname" exists, assume that is the per-package 7189 // native library directory to use; otherwise use "/system/lib/apkname". 7190 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7191 setBundledAppAbi(pkg, apkRoot, apkName); 7192 // pkgSetting might be null during rescan following uninstall of updates 7193 // to a bundled app, so accommodate that possibility. The settings in 7194 // that case will be established later from the parsed package. 7195 // 7196 // If the settings aren't null, sync them up with what we've just derived. 7197 // note that apkRoot isn't stored in the package settings. 7198 if (pkgSetting != null) { 7199 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7200 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7201 } 7202 } 7203 7204 /** 7205 * Deduces the ABI of a bundled app and sets the relevant fields on the 7206 * parsed pkg object. 7207 * 7208 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7209 * under which system libraries are installed. 7210 * @param apkName the name of the installed package. 7211 */ 7212 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7213 final File codeFile = new File(pkg.codePath); 7214 7215 final boolean has64BitLibs; 7216 final boolean has32BitLibs; 7217 if (isApkFile(codeFile)) { 7218 // Monolithic install 7219 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7220 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7221 } else { 7222 // Cluster install 7223 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7224 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7225 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7226 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7227 has64BitLibs = (new File(rootDir, isa)).exists(); 7228 } else { 7229 has64BitLibs = false; 7230 } 7231 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7232 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7233 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7234 has32BitLibs = (new File(rootDir, isa)).exists(); 7235 } else { 7236 has32BitLibs = false; 7237 } 7238 } 7239 7240 if (has64BitLibs && !has32BitLibs) { 7241 // The package has 64 bit libs, but not 32 bit libs. Its primary 7242 // ABI should be 64 bit. We can safely assume here that the bundled 7243 // native libraries correspond to the most preferred ABI in the list. 7244 7245 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7246 pkg.applicationInfo.secondaryCpuAbi = null; 7247 } else if (has32BitLibs && !has64BitLibs) { 7248 // The package has 32 bit libs but not 64 bit libs. Its primary 7249 // ABI should be 32 bit. 7250 7251 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7252 pkg.applicationInfo.secondaryCpuAbi = null; 7253 } else if (has32BitLibs && has64BitLibs) { 7254 // The application has both 64 and 32 bit bundled libraries. We check 7255 // here that the app declares multiArch support, and warn if it doesn't. 7256 // 7257 // We will be lenient here and record both ABIs. The primary will be the 7258 // ABI that's higher on the list, i.e, a device that's configured to prefer 7259 // 64 bit apps will see a 64 bit primary ABI, 7260 7261 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7262 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7263 } 7264 7265 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7266 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7267 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7268 } else { 7269 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7270 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7271 } 7272 } else { 7273 pkg.applicationInfo.primaryCpuAbi = null; 7274 pkg.applicationInfo.secondaryCpuAbi = null; 7275 } 7276 } 7277 7278 private void killApplication(String pkgName, int appId, String reason) { 7279 // Request the ActivityManager to kill the process(only for existing packages) 7280 // so that we do not end up in a confused state while the user is still using the older 7281 // version of the application while the new one gets installed. 7282 IActivityManager am = ActivityManagerNative.getDefault(); 7283 if (am != null) { 7284 try { 7285 am.killApplicationWithAppId(pkgName, appId, reason); 7286 } catch (RemoteException e) { 7287 } 7288 } 7289 } 7290 7291 void removePackageLI(PackageSetting ps, boolean chatty) { 7292 if (DEBUG_INSTALL) { 7293 if (chatty) 7294 Log.d(TAG, "Removing package " + ps.name); 7295 } 7296 7297 // writer 7298 synchronized (mPackages) { 7299 mPackages.remove(ps.name); 7300 final PackageParser.Package pkg = ps.pkg; 7301 if (pkg != null) { 7302 cleanPackageDataStructuresLILPw(pkg, chatty); 7303 } 7304 } 7305 } 7306 7307 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7308 if (DEBUG_INSTALL) { 7309 if (chatty) 7310 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7311 } 7312 7313 // writer 7314 synchronized (mPackages) { 7315 mPackages.remove(pkg.applicationInfo.packageName); 7316 cleanPackageDataStructuresLILPw(pkg, chatty); 7317 } 7318 } 7319 7320 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7321 int N = pkg.providers.size(); 7322 StringBuilder r = null; 7323 int i; 7324 for (i=0; i<N; i++) { 7325 PackageParser.Provider p = pkg.providers.get(i); 7326 mProviders.removeProvider(p); 7327 if (p.info.authority == null) { 7328 7329 /* There was another ContentProvider with this authority when 7330 * this app was installed so this authority is null, 7331 * Ignore it as we don't have to unregister the provider. 7332 */ 7333 continue; 7334 } 7335 String names[] = p.info.authority.split(";"); 7336 for (int j = 0; j < names.length; j++) { 7337 if (mProvidersByAuthority.get(names[j]) == p) { 7338 mProvidersByAuthority.remove(names[j]); 7339 if (DEBUG_REMOVE) { 7340 if (chatty) 7341 Log.d(TAG, "Unregistered content provider: " + names[j] 7342 + ", className = " + p.info.name + ", isSyncable = " 7343 + p.info.isSyncable); 7344 } 7345 } 7346 } 7347 if (DEBUG_REMOVE && chatty) { 7348 if (r == null) { 7349 r = new StringBuilder(256); 7350 } else { 7351 r.append(' '); 7352 } 7353 r.append(p.info.name); 7354 } 7355 } 7356 if (r != null) { 7357 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7358 } 7359 7360 N = pkg.services.size(); 7361 r = null; 7362 for (i=0; i<N; i++) { 7363 PackageParser.Service s = pkg.services.get(i); 7364 mServices.removeService(s); 7365 if (chatty) { 7366 if (r == null) { 7367 r = new StringBuilder(256); 7368 } else { 7369 r.append(' '); 7370 } 7371 r.append(s.info.name); 7372 } 7373 } 7374 if (r != null) { 7375 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7376 } 7377 7378 N = pkg.receivers.size(); 7379 r = null; 7380 for (i=0; i<N; i++) { 7381 PackageParser.Activity a = pkg.receivers.get(i); 7382 mReceivers.removeActivity(a, "receiver"); 7383 if (DEBUG_REMOVE && chatty) { 7384 if (r == null) { 7385 r = new StringBuilder(256); 7386 } else { 7387 r.append(' '); 7388 } 7389 r.append(a.info.name); 7390 } 7391 } 7392 if (r != null) { 7393 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7394 } 7395 7396 N = pkg.activities.size(); 7397 r = null; 7398 for (i=0; i<N; i++) { 7399 PackageParser.Activity a = pkg.activities.get(i); 7400 mActivities.removeActivity(a, "activity"); 7401 if (DEBUG_REMOVE && chatty) { 7402 if (r == null) { 7403 r = new StringBuilder(256); 7404 } else { 7405 r.append(' '); 7406 } 7407 r.append(a.info.name); 7408 } 7409 } 7410 if (r != null) { 7411 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7412 } 7413 7414 N = pkg.permissions.size(); 7415 r = null; 7416 for (i=0; i<N; i++) { 7417 PackageParser.Permission p = pkg.permissions.get(i); 7418 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7419 if (bp == null) { 7420 bp = mSettings.mPermissionTrees.get(p.info.name); 7421 } 7422 if (bp != null && bp.perm == p) { 7423 bp.perm = null; 7424 if (DEBUG_REMOVE && chatty) { 7425 if (r == null) { 7426 r = new StringBuilder(256); 7427 } else { 7428 r.append(' '); 7429 } 7430 r.append(p.info.name); 7431 } 7432 } 7433 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7434 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7435 if (appOpPerms != null) { 7436 appOpPerms.remove(pkg.packageName); 7437 } 7438 } 7439 } 7440 if (r != null) { 7441 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7442 } 7443 7444 N = pkg.requestedPermissions.size(); 7445 r = null; 7446 for (i=0; i<N; i++) { 7447 String perm = pkg.requestedPermissions.get(i); 7448 BasePermission bp = mSettings.mPermissions.get(perm); 7449 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7450 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7451 if (appOpPerms != null) { 7452 appOpPerms.remove(pkg.packageName); 7453 if (appOpPerms.isEmpty()) { 7454 mAppOpPermissionPackages.remove(perm); 7455 } 7456 } 7457 } 7458 } 7459 if (r != null) { 7460 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7461 } 7462 7463 N = pkg.instrumentation.size(); 7464 r = null; 7465 for (i=0; i<N; i++) { 7466 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7467 mInstrumentation.remove(a.getComponentName()); 7468 if (DEBUG_REMOVE && chatty) { 7469 if (r == null) { 7470 r = new StringBuilder(256); 7471 } else { 7472 r.append(' '); 7473 } 7474 r.append(a.info.name); 7475 } 7476 } 7477 if (r != null) { 7478 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7479 } 7480 7481 r = null; 7482 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7483 // Only system apps can hold shared libraries. 7484 if (pkg.libraryNames != null) { 7485 for (i=0; i<pkg.libraryNames.size(); i++) { 7486 String name = pkg.libraryNames.get(i); 7487 SharedLibraryEntry cur = mSharedLibraries.get(name); 7488 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7489 mSharedLibraries.remove(name); 7490 if (DEBUG_REMOVE && chatty) { 7491 if (r == null) { 7492 r = new StringBuilder(256); 7493 } else { 7494 r.append(' '); 7495 } 7496 r.append(name); 7497 } 7498 } 7499 } 7500 } 7501 } 7502 if (r != null) { 7503 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7504 } 7505 } 7506 7507 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7508 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7509 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7510 return true; 7511 } 7512 } 7513 return false; 7514 } 7515 7516 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7517 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7518 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7519 7520 private void updatePermissionsLPw(String changingPkg, 7521 PackageParser.Package pkgInfo, int flags) { 7522 // Make sure there are no dangling permission trees. 7523 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7524 while (it.hasNext()) { 7525 final BasePermission bp = it.next(); 7526 if (bp.packageSetting == null) { 7527 // We may not yet have parsed the package, so just see if 7528 // we still know about its settings. 7529 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7530 } 7531 if (bp.packageSetting == null) { 7532 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7533 + " from package " + bp.sourcePackage); 7534 it.remove(); 7535 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7536 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7537 Slog.i(TAG, "Removing old permission tree: " + bp.name 7538 + " from package " + bp.sourcePackage); 7539 flags |= UPDATE_PERMISSIONS_ALL; 7540 it.remove(); 7541 } 7542 } 7543 } 7544 7545 // Make sure all dynamic permissions have been assigned to a package, 7546 // and make sure there are no dangling permissions. 7547 it = mSettings.mPermissions.values().iterator(); 7548 while (it.hasNext()) { 7549 final BasePermission bp = it.next(); 7550 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7551 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7552 + bp.name + " pkg=" + bp.sourcePackage 7553 + " info=" + bp.pendingInfo); 7554 if (bp.packageSetting == null && bp.pendingInfo != null) { 7555 final BasePermission tree = findPermissionTreeLP(bp.name); 7556 if (tree != null && tree.perm != null) { 7557 bp.packageSetting = tree.packageSetting; 7558 bp.perm = new PackageParser.Permission(tree.perm.owner, 7559 new PermissionInfo(bp.pendingInfo)); 7560 bp.perm.info.packageName = tree.perm.info.packageName; 7561 bp.perm.info.name = bp.name; 7562 bp.uid = tree.uid; 7563 } 7564 } 7565 } 7566 if (bp.packageSetting == null) { 7567 // We may not yet have parsed the package, so just see if 7568 // we still know about its settings. 7569 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7570 } 7571 if (bp.packageSetting == null) { 7572 Slog.w(TAG, "Removing dangling permission: " + bp.name 7573 + " from package " + bp.sourcePackage); 7574 it.remove(); 7575 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7576 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7577 Slog.i(TAG, "Removing old permission: " + bp.name 7578 + " from package " + bp.sourcePackage); 7579 flags |= UPDATE_PERMISSIONS_ALL; 7580 it.remove(); 7581 } 7582 } 7583 } 7584 7585 // Now update the permissions for all packages, in particular 7586 // replace the granted permissions of the system packages. 7587 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7588 for (PackageParser.Package pkg : mPackages.values()) { 7589 if (pkg != pkgInfo) { 7590 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7591 changingPkg); 7592 } 7593 } 7594 } 7595 7596 if (pkgInfo != null) { 7597 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7598 } 7599 } 7600 7601 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7602 String packageOfInterest) { 7603 // IMPORTANT: There are two types of permissions: install and runtime. 7604 // Install time permissions are granted when the app is installed to 7605 // all device users and users added in the future. Runtime permissions 7606 // are granted at runtime explicitly to specific users. Normal and signature 7607 // protected permissions are install time permissions. Dangerous permissions 7608 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7609 // otherwise they are runtime permissions. This function does not manage 7610 // runtime permissions except for the case an app targeting Lollipop MR1 7611 // being upgraded to target a newer SDK, in which case dangerous permissions 7612 // are transformed from install time to runtime ones. 7613 7614 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7615 if (ps == null) { 7616 return; 7617 } 7618 7619 PermissionsState permissionsState = ps.getPermissionsState(); 7620 PermissionsState origPermissions = permissionsState; 7621 7622 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7623 7624 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7625 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7626 7627 boolean changedInstallPermission = false; 7628 7629 if (replace) { 7630 ps.installPermissionsFixed = false; 7631 if (!ps.isSharedUser()) { 7632 origPermissions = new PermissionsState(permissionsState); 7633 permissionsState.reset(); 7634 } 7635 } 7636 7637 permissionsState.setGlobalGids(mGlobalGids); 7638 7639 final int N = pkg.requestedPermissions.size(); 7640 for (int i=0; i<N; i++) { 7641 final String name = pkg.requestedPermissions.get(i); 7642 final BasePermission bp = mSettings.mPermissions.get(name); 7643 7644 if (DEBUG_INSTALL) { 7645 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7646 } 7647 7648 if (bp == null || bp.packageSetting == null) { 7649 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7650 Slog.w(TAG, "Unknown permission " + name 7651 + " in package " + pkg.packageName); 7652 } 7653 continue; 7654 } 7655 7656 final String perm = bp.name; 7657 boolean allowedSig = false; 7658 int grant = GRANT_DENIED; 7659 7660 // Keep track of app op permissions. 7661 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7662 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7663 if (pkgs == null) { 7664 pkgs = new ArraySet<>(); 7665 mAppOpPermissionPackages.put(bp.name, pkgs); 7666 } 7667 pkgs.add(pkg.packageName); 7668 } 7669 7670 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7671 switch (level) { 7672 case PermissionInfo.PROTECTION_NORMAL: { 7673 // For all apps normal permissions are install time ones. 7674 grant = GRANT_INSTALL; 7675 } break; 7676 7677 case PermissionInfo.PROTECTION_DANGEROUS: { 7678 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7679 // For legacy apps dangerous permissions are install time ones. 7680 grant = GRANT_INSTALL; 7681 } else if (ps.isSystem()) { 7682 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7683 if (origPermissions.hasInstallPermission(bp.name)) { 7684 // If a system app had an install permission, then the app was 7685 // upgraded and we grant the permissions as runtime to all users. 7686 grant = GRANT_UPGRADE; 7687 upgradeUserIds = currentUserIds; 7688 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7689 // If users changed since the last permissions update for a 7690 // system app, we grant the permission as runtime to the new users. 7691 grant = GRANT_UPGRADE; 7692 upgradeUserIds = currentUserIds; 7693 for (int userId : updatedUserIds) { 7694 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7695 } 7696 } else { 7697 // Otherwise, we grant the permission as runtime if the app 7698 // already had it, i.e. we preserve runtime permissions. 7699 grant = GRANT_RUNTIME; 7700 } 7701 } else if (origPermissions.hasInstallPermission(bp.name)) { 7702 // For legacy apps that became modern, install becomes runtime. 7703 grant = GRANT_UPGRADE; 7704 upgradeUserIds = currentUserIds; 7705 } else if (replace) { 7706 // For upgraded modern apps keep runtime permissions unchanged. 7707 grant = GRANT_RUNTIME; 7708 } 7709 } break; 7710 7711 case PermissionInfo.PROTECTION_SIGNATURE: { 7712 // For all apps signature permissions are install time ones. 7713 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7714 if (allowedSig) { 7715 grant = GRANT_INSTALL; 7716 } 7717 } break; 7718 } 7719 7720 if (DEBUG_INSTALL) { 7721 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7722 } 7723 7724 if (grant != GRANT_DENIED) { 7725 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7726 // If this is an existing, non-system package, then 7727 // we can't add any new permissions to it. 7728 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7729 // Except... if this is a permission that was added 7730 // to the platform (note: need to only do this when 7731 // updating the platform). 7732 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7733 grant = GRANT_DENIED; 7734 } 7735 } 7736 } 7737 7738 switch (grant) { 7739 case GRANT_INSTALL: { 7740 // Grant an install permission. 7741 if (permissionsState.grantInstallPermission(bp) != 7742 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7743 changedInstallPermission = true; 7744 } 7745 } break; 7746 7747 case GRANT_RUNTIME: { 7748 // Grant previously granted runtime permissions. 7749 for (int userId : UserManagerService.getInstance().getUserIds()) { 7750 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7751 PermissionState permissionState = origPermissions 7752 .getRuntimePermissionState(bp.name, userId); 7753 final int flags = permissionState.getFlags(); 7754 if (permissionsState.grantRuntimePermission(bp, userId) == 7755 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7756 // If we cannot put the permission as it was, we have to write. 7757 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7758 changedRuntimePermissionUserIds, userId); 7759 } else { 7760 // Propagate the permission flags. 7761 permissionsState.updatePermissionFlags(bp, userId, 7762 flags, flags); 7763 } 7764 } 7765 } 7766 } break; 7767 7768 case GRANT_UPGRADE: { 7769 // Grant runtime permissions for a previously held install permission. 7770 PermissionState permissionState = origPermissions 7771 .getInstallPermissionState(bp.name); 7772 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7773 7774 origPermissions.revokeInstallPermission(bp); 7775 // We will be transferring the permission flags, so clear them. 7776 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7777 PackageManager.MASK_PERMISSION_FLAGS, 0); 7778 7779 // If the permission is not to be promoted to runtime we ignore it and 7780 // also its other flags as they are not applicable to install permissions. 7781 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7782 for (int userId : upgradeUserIds) { 7783 if (permissionsState.grantRuntimePermission(bp, userId) != 7784 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7785 // Transfer the permission flags. 7786 permissionsState.updatePermissionFlags(bp, userId, 7787 flags, flags); 7788 // If we granted the permission, we have to write. 7789 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7790 changedRuntimePermissionUserIds, userId); 7791 } 7792 } 7793 } 7794 } break; 7795 7796 default: { 7797 if (packageOfInterest == null 7798 || packageOfInterest.equals(pkg.packageName)) { 7799 Slog.w(TAG, "Not granting permission " + perm 7800 + " to package " + pkg.packageName 7801 + " because it was previously installed without"); 7802 } 7803 } break; 7804 } 7805 } else { 7806 if (permissionsState.revokeInstallPermission(bp) != 7807 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7808 // Also drop the permission flags. 7809 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7810 PackageManager.MASK_PERMISSION_FLAGS, 0); 7811 changedInstallPermission = true; 7812 Slog.i(TAG, "Un-granting permission " + perm 7813 + " from package " + pkg.packageName 7814 + " (protectionLevel=" + bp.protectionLevel 7815 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7816 + ")"); 7817 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7818 // Don't print warning for app op permissions, since it is fine for them 7819 // not to be granted, there is a UI for the user to decide. 7820 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7821 Slog.w(TAG, "Not granting permission " + perm 7822 + " to package " + pkg.packageName 7823 + " (protectionLevel=" + bp.protectionLevel 7824 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7825 + ")"); 7826 } 7827 } 7828 } 7829 } 7830 7831 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7832 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7833 // This is the first that we have heard about this package, so the 7834 // permissions we have now selected are fixed until explicitly 7835 // changed. 7836 ps.installPermissionsFixed = true; 7837 } 7838 7839 ps.setPermissionsUpdatedForUserIds(currentUserIds); 7840 7841 // Persist the runtime permissions state for users with changes. 7842 for (int userId : changedRuntimePermissionUserIds) { 7843 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 7844 } 7845 } 7846 7847 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7848 boolean allowed = false; 7849 final int NP = PackageParser.NEW_PERMISSIONS.length; 7850 for (int ip=0; ip<NP; ip++) { 7851 final PackageParser.NewPermissionInfo npi 7852 = PackageParser.NEW_PERMISSIONS[ip]; 7853 if (npi.name.equals(perm) 7854 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7855 allowed = true; 7856 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7857 + pkg.packageName); 7858 break; 7859 } 7860 } 7861 return allowed; 7862 } 7863 7864 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7865 BasePermission bp, PermissionsState origPermissions) { 7866 boolean allowed; 7867 allowed = (compareSignatures( 7868 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7869 == PackageManager.SIGNATURE_MATCH) 7870 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7871 == PackageManager.SIGNATURE_MATCH); 7872 if (!allowed && (bp.protectionLevel 7873 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7874 if (isSystemApp(pkg)) { 7875 // For updated system applications, a system permission 7876 // is granted only if it had been defined by the original application. 7877 if (pkg.isUpdatedSystemApp()) { 7878 final PackageSetting sysPs = mSettings 7879 .getDisabledSystemPkgLPr(pkg.packageName); 7880 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 7881 // If the original was granted this permission, we take 7882 // that grant decision as read and propagate it to the 7883 // update. 7884 if (sysPs.isPrivileged()) { 7885 allowed = true; 7886 } 7887 } else { 7888 // The system apk may have been updated with an older 7889 // version of the one on the data partition, but which 7890 // granted a new system permission that it didn't have 7891 // before. In this case we do want to allow the app to 7892 // now get the new permission if the ancestral apk is 7893 // privileged to get it. 7894 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7895 for (int j=0; 7896 j<sysPs.pkg.requestedPermissions.size(); j++) { 7897 if (perm.equals( 7898 sysPs.pkg.requestedPermissions.get(j))) { 7899 allowed = true; 7900 break; 7901 } 7902 } 7903 } 7904 } 7905 } else { 7906 allowed = isPrivilegedApp(pkg); 7907 } 7908 } 7909 } 7910 if (!allowed && (bp.protectionLevel 7911 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7912 // For development permissions, a development permission 7913 // is granted only if it was already granted. 7914 allowed = origPermissions.hasInstallPermission(perm); 7915 } 7916 return allowed; 7917 } 7918 7919 final class ActivityIntentResolver 7920 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7921 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7922 boolean defaultOnly, int userId) { 7923 if (!sUserManager.exists(userId)) return null; 7924 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7925 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7926 } 7927 7928 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7929 int userId) { 7930 if (!sUserManager.exists(userId)) return null; 7931 mFlags = flags; 7932 return super.queryIntent(intent, resolvedType, 7933 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7934 } 7935 7936 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7937 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7938 if (!sUserManager.exists(userId)) return null; 7939 if (packageActivities == null) { 7940 return null; 7941 } 7942 mFlags = flags; 7943 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7944 final int N = packageActivities.size(); 7945 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7946 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7947 7948 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7949 for (int i = 0; i < N; ++i) { 7950 intentFilters = packageActivities.get(i).intents; 7951 if (intentFilters != null && intentFilters.size() > 0) { 7952 PackageParser.ActivityIntentInfo[] array = 7953 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7954 intentFilters.toArray(array); 7955 listCut.add(array); 7956 } 7957 } 7958 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7959 } 7960 7961 public final void addActivity(PackageParser.Activity a, String type) { 7962 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 7963 mActivities.put(a.getComponentName(), a); 7964 if (DEBUG_SHOW_INFO) 7965 Log.v( 7966 TAG, " " + type + " " + 7967 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7968 if (DEBUG_SHOW_INFO) 7969 Log.v(TAG, " Class=" + a.info.name); 7970 final int NI = a.intents.size(); 7971 for (int j=0; j<NI; j++) { 7972 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7973 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7974 intent.setPriority(0); 7975 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7976 + a.className + " with priority > 0, forcing to 0"); 7977 } 7978 if (DEBUG_SHOW_INFO) { 7979 Log.v(TAG, " IntentFilter:"); 7980 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7981 } 7982 if (!intent.debugCheck()) { 7983 Log.w(TAG, "==> For Activity " + a.info.name); 7984 } 7985 addFilter(intent); 7986 } 7987 } 7988 7989 public final void removeActivity(PackageParser.Activity a, String type) { 7990 mActivities.remove(a.getComponentName()); 7991 if (DEBUG_SHOW_INFO) { 7992 Log.v(TAG, " " + type + " " 7993 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7994 : a.info.name) + ":"); 7995 Log.v(TAG, " Class=" + a.info.name); 7996 } 7997 final int NI = a.intents.size(); 7998 for (int j=0; j<NI; j++) { 7999 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8000 if (DEBUG_SHOW_INFO) { 8001 Log.v(TAG, " IntentFilter:"); 8002 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8003 } 8004 removeFilter(intent); 8005 } 8006 } 8007 8008 @Override 8009 protected boolean allowFilterResult( 8010 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8011 ActivityInfo filterAi = filter.activity.info; 8012 for (int i=dest.size()-1; i>=0; i--) { 8013 ActivityInfo destAi = dest.get(i).activityInfo; 8014 if (destAi.name == filterAi.name 8015 && destAi.packageName == filterAi.packageName) { 8016 return false; 8017 } 8018 } 8019 return true; 8020 } 8021 8022 @Override 8023 protected ActivityIntentInfo[] newArray(int size) { 8024 return new ActivityIntentInfo[size]; 8025 } 8026 8027 @Override 8028 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8029 if (!sUserManager.exists(userId)) return true; 8030 PackageParser.Package p = filter.activity.owner; 8031 if (p != null) { 8032 PackageSetting ps = (PackageSetting)p.mExtras; 8033 if (ps != null) { 8034 // System apps are never considered stopped for purposes of 8035 // filtering, because there may be no way for the user to 8036 // actually re-launch them. 8037 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8038 && ps.getStopped(userId); 8039 } 8040 } 8041 return false; 8042 } 8043 8044 @Override 8045 protected boolean isPackageForFilter(String packageName, 8046 PackageParser.ActivityIntentInfo info) { 8047 return packageName.equals(info.activity.owner.packageName); 8048 } 8049 8050 @Override 8051 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8052 int match, int userId) { 8053 if (!sUserManager.exists(userId)) return null; 8054 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8055 return null; 8056 } 8057 final PackageParser.Activity activity = info.activity; 8058 if (mSafeMode && (activity.info.applicationInfo.flags 8059 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8060 return null; 8061 } 8062 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8063 if (ps == null) { 8064 return null; 8065 } 8066 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8067 ps.readUserState(userId), userId); 8068 if (ai == null) { 8069 return null; 8070 } 8071 final ResolveInfo res = new ResolveInfo(); 8072 res.activityInfo = ai; 8073 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8074 res.filter = info; 8075 } 8076 if (info != null) { 8077 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8078 } 8079 res.priority = info.getPriority(); 8080 res.preferredOrder = activity.owner.mPreferredOrder; 8081 //System.out.println("Result: " + res.activityInfo.className + 8082 // " = " + res.priority); 8083 res.match = match; 8084 res.isDefault = info.hasDefault; 8085 res.labelRes = info.labelRes; 8086 res.nonLocalizedLabel = info.nonLocalizedLabel; 8087 if (userNeedsBadging(userId)) { 8088 res.noResourceId = true; 8089 } else { 8090 res.icon = info.icon; 8091 } 8092 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8093 return res; 8094 } 8095 8096 @Override 8097 protected void sortResults(List<ResolveInfo> results) { 8098 Collections.sort(results, mResolvePrioritySorter); 8099 } 8100 8101 @Override 8102 protected void dumpFilter(PrintWriter out, String prefix, 8103 PackageParser.ActivityIntentInfo filter) { 8104 out.print(prefix); out.print( 8105 Integer.toHexString(System.identityHashCode(filter.activity))); 8106 out.print(' '); 8107 filter.activity.printComponentShortName(out); 8108 out.print(" filter "); 8109 out.println(Integer.toHexString(System.identityHashCode(filter))); 8110 } 8111 8112 @Override 8113 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8114 return filter.activity; 8115 } 8116 8117 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8118 PackageParser.Activity activity = (PackageParser.Activity)label; 8119 out.print(prefix); out.print( 8120 Integer.toHexString(System.identityHashCode(activity))); 8121 out.print(' '); 8122 activity.printComponentShortName(out); 8123 if (count > 1) { 8124 out.print(" ("); out.print(count); out.print(" filters)"); 8125 } 8126 out.println(); 8127 } 8128 8129// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8130// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8131// final List<ResolveInfo> retList = Lists.newArrayList(); 8132// while (i.hasNext()) { 8133// final ResolveInfo resolveInfo = i.next(); 8134// if (isEnabledLP(resolveInfo.activityInfo)) { 8135// retList.add(resolveInfo); 8136// } 8137// } 8138// return retList; 8139// } 8140 8141 // Keys are String (activity class name), values are Activity. 8142 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8143 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8144 private int mFlags; 8145 } 8146 8147 private final class ServiceIntentResolver 8148 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8149 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8150 boolean defaultOnly, int userId) { 8151 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8152 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8153 } 8154 8155 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8156 int userId) { 8157 if (!sUserManager.exists(userId)) return null; 8158 mFlags = flags; 8159 return super.queryIntent(intent, resolvedType, 8160 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8161 } 8162 8163 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8164 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8165 if (!sUserManager.exists(userId)) return null; 8166 if (packageServices == null) { 8167 return null; 8168 } 8169 mFlags = flags; 8170 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8171 final int N = packageServices.size(); 8172 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8173 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8174 8175 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8176 for (int i = 0; i < N; ++i) { 8177 intentFilters = packageServices.get(i).intents; 8178 if (intentFilters != null && intentFilters.size() > 0) { 8179 PackageParser.ServiceIntentInfo[] array = 8180 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8181 intentFilters.toArray(array); 8182 listCut.add(array); 8183 } 8184 } 8185 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8186 } 8187 8188 public final void addService(PackageParser.Service s) { 8189 mServices.put(s.getComponentName(), s); 8190 if (DEBUG_SHOW_INFO) { 8191 Log.v(TAG, " " 8192 + (s.info.nonLocalizedLabel != null 8193 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8194 Log.v(TAG, " Class=" + s.info.name); 8195 } 8196 final int NI = s.intents.size(); 8197 int j; 8198 for (j=0; j<NI; j++) { 8199 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8200 if (DEBUG_SHOW_INFO) { 8201 Log.v(TAG, " IntentFilter:"); 8202 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8203 } 8204 if (!intent.debugCheck()) { 8205 Log.w(TAG, "==> For Service " + s.info.name); 8206 } 8207 addFilter(intent); 8208 } 8209 } 8210 8211 public final void removeService(PackageParser.Service s) { 8212 mServices.remove(s.getComponentName()); 8213 if (DEBUG_SHOW_INFO) { 8214 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8215 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8216 Log.v(TAG, " Class=" + s.info.name); 8217 } 8218 final int NI = s.intents.size(); 8219 int j; 8220 for (j=0; j<NI; j++) { 8221 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8222 if (DEBUG_SHOW_INFO) { 8223 Log.v(TAG, " IntentFilter:"); 8224 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8225 } 8226 removeFilter(intent); 8227 } 8228 } 8229 8230 @Override 8231 protected boolean allowFilterResult( 8232 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8233 ServiceInfo filterSi = filter.service.info; 8234 for (int i=dest.size()-1; i>=0; i--) { 8235 ServiceInfo destAi = dest.get(i).serviceInfo; 8236 if (destAi.name == filterSi.name 8237 && destAi.packageName == filterSi.packageName) { 8238 return false; 8239 } 8240 } 8241 return true; 8242 } 8243 8244 @Override 8245 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8246 return new PackageParser.ServiceIntentInfo[size]; 8247 } 8248 8249 @Override 8250 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8251 if (!sUserManager.exists(userId)) return true; 8252 PackageParser.Package p = filter.service.owner; 8253 if (p != null) { 8254 PackageSetting ps = (PackageSetting)p.mExtras; 8255 if (ps != null) { 8256 // System apps are never considered stopped for purposes of 8257 // filtering, because there may be no way for the user to 8258 // actually re-launch them. 8259 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8260 && ps.getStopped(userId); 8261 } 8262 } 8263 return false; 8264 } 8265 8266 @Override 8267 protected boolean isPackageForFilter(String packageName, 8268 PackageParser.ServiceIntentInfo info) { 8269 return packageName.equals(info.service.owner.packageName); 8270 } 8271 8272 @Override 8273 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8274 int match, int userId) { 8275 if (!sUserManager.exists(userId)) return null; 8276 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8277 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8278 return null; 8279 } 8280 final PackageParser.Service service = info.service; 8281 if (mSafeMode && (service.info.applicationInfo.flags 8282 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8283 return null; 8284 } 8285 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8286 if (ps == null) { 8287 return null; 8288 } 8289 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8290 ps.readUserState(userId), userId); 8291 if (si == null) { 8292 return null; 8293 } 8294 final ResolveInfo res = new ResolveInfo(); 8295 res.serviceInfo = si; 8296 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8297 res.filter = filter; 8298 } 8299 res.priority = info.getPriority(); 8300 res.preferredOrder = service.owner.mPreferredOrder; 8301 res.match = match; 8302 res.isDefault = info.hasDefault; 8303 res.labelRes = info.labelRes; 8304 res.nonLocalizedLabel = info.nonLocalizedLabel; 8305 res.icon = info.icon; 8306 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8307 return res; 8308 } 8309 8310 @Override 8311 protected void sortResults(List<ResolveInfo> results) { 8312 Collections.sort(results, mResolvePrioritySorter); 8313 } 8314 8315 @Override 8316 protected void dumpFilter(PrintWriter out, String prefix, 8317 PackageParser.ServiceIntentInfo filter) { 8318 out.print(prefix); out.print( 8319 Integer.toHexString(System.identityHashCode(filter.service))); 8320 out.print(' '); 8321 filter.service.printComponentShortName(out); 8322 out.print(" filter "); 8323 out.println(Integer.toHexString(System.identityHashCode(filter))); 8324 } 8325 8326 @Override 8327 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8328 return filter.service; 8329 } 8330 8331 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8332 PackageParser.Service service = (PackageParser.Service)label; 8333 out.print(prefix); out.print( 8334 Integer.toHexString(System.identityHashCode(service))); 8335 out.print(' '); 8336 service.printComponentShortName(out); 8337 if (count > 1) { 8338 out.print(" ("); out.print(count); out.print(" filters)"); 8339 } 8340 out.println(); 8341 } 8342 8343// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8344// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8345// final List<ResolveInfo> retList = Lists.newArrayList(); 8346// while (i.hasNext()) { 8347// final ResolveInfo resolveInfo = (ResolveInfo) i; 8348// if (isEnabledLP(resolveInfo.serviceInfo)) { 8349// retList.add(resolveInfo); 8350// } 8351// } 8352// return retList; 8353// } 8354 8355 // Keys are String (activity class name), values are Activity. 8356 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8357 = new ArrayMap<ComponentName, PackageParser.Service>(); 8358 private int mFlags; 8359 }; 8360 8361 private final class ProviderIntentResolver 8362 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8363 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8364 boolean defaultOnly, int userId) { 8365 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8366 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8367 } 8368 8369 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8370 int userId) { 8371 if (!sUserManager.exists(userId)) 8372 return null; 8373 mFlags = flags; 8374 return super.queryIntent(intent, resolvedType, 8375 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8376 } 8377 8378 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8379 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8380 if (!sUserManager.exists(userId)) 8381 return null; 8382 if (packageProviders == null) { 8383 return null; 8384 } 8385 mFlags = flags; 8386 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8387 final int N = packageProviders.size(); 8388 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8389 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8390 8391 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8392 for (int i = 0; i < N; ++i) { 8393 intentFilters = packageProviders.get(i).intents; 8394 if (intentFilters != null && intentFilters.size() > 0) { 8395 PackageParser.ProviderIntentInfo[] array = 8396 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8397 intentFilters.toArray(array); 8398 listCut.add(array); 8399 } 8400 } 8401 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8402 } 8403 8404 public final void addProvider(PackageParser.Provider p) { 8405 if (mProviders.containsKey(p.getComponentName())) { 8406 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8407 return; 8408 } 8409 8410 mProviders.put(p.getComponentName(), p); 8411 if (DEBUG_SHOW_INFO) { 8412 Log.v(TAG, " " 8413 + (p.info.nonLocalizedLabel != null 8414 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8415 Log.v(TAG, " Class=" + p.info.name); 8416 } 8417 final int NI = p.intents.size(); 8418 int j; 8419 for (j = 0; j < NI; j++) { 8420 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8421 if (DEBUG_SHOW_INFO) { 8422 Log.v(TAG, " IntentFilter:"); 8423 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8424 } 8425 if (!intent.debugCheck()) { 8426 Log.w(TAG, "==> For Provider " + p.info.name); 8427 } 8428 addFilter(intent); 8429 } 8430 } 8431 8432 public final void removeProvider(PackageParser.Provider p) { 8433 mProviders.remove(p.getComponentName()); 8434 if (DEBUG_SHOW_INFO) { 8435 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8436 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8437 Log.v(TAG, " Class=" + p.info.name); 8438 } 8439 final int NI = p.intents.size(); 8440 int j; 8441 for (j = 0; j < NI; j++) { 8442 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8443 if (DEBUG_SHOW_INFO) { 8444 Log.v(TAG, " IntentFilter:"); 8445 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8446 } 8447 removeFilter(intent); 8448 } 8449 } 8450 8451 @Override 8452 protected boolean allowFilterResult( 8453 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8454 ProviderInfo filterPi = filter.provider.info; 8455 for (int i = dest.size() - 1; i >= 0; i--) { 8456 ProviderInfo destPi = dest.get(i).providerInfo; 8457 if (destPi.name == filterPi.name 8458 && destPi.packageName == filterPi.packageName) { 8459 return false; 8460 } 8461 } 8462 return true; 8463 } 8464 8465 @Override 8466 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8467 return new PackageParser.ProviderIntentInfo[size]; 8468 } 8469 8470 @Override 8471 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8472 if (!sUserManager.exists(userId)) 8473 return true; 8474 PackageParser.Package p = filter.provider.owner; 8475 if (p != null) { 8476 PackageSetting ps = (PackageSetting) p.mExtras; 8477 if (ps != null) { 8478 // System apps are never considered stopped for purposes of 8479 // filtering, because there may be no way for the user to 8480 // actually re-launch them. 8481 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8482 && ps.getStopped(userId); 8483 } 8484 } 8485 return false; 8486 } 8487 8488 @Override 8489 protected boolean isPackageForFilter(String packageName, 8490 PackageParser.ProviderIntentInfo info) { 8491 return packageName.equals(info.provider.owner.packageName); 8492 } 8493 8494 @Override 8495 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8496 int match, int userId) { 8497 if (!sUserManager.exists(userId)) 8498 return null; 8499 final PackageParser.ProviderIntentInfo info = filter; 8500 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8501 return null; 8502 } 8503 final PackageParser.Provider provider = info.provider; 8504 if (mSafeMode && (provider.info.applicationInfo.flags 8505 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8506 return null; 8507 } 8508 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8509 if (ps == null) { 8510 return null; 8511 } 8512 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8513 ps.readUserState(userId), userId); 8514 if (pi == null) { 8515 return null; 8516 } 8517 final ResolveInfo res = new ResolveInfo(); 8518 res.providerInfo = pi; 8519 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8520 res.filter = filter; 8521 } 8522 res.priority = info.getPriority(); 8523 res.preferredOrder = provider.owner.mPreferredOrder; 8524 res.match = match; 8525 res.isDefault = info.hasDefault; 8526 res.labelRes = info.labelRes; 8527 res.nonLocalizedLabel = info.nonLocalizedLabel; 8528 res.icon = info.icon; 8529 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8530 return res; 8531 } 8532 8533 @Override 8534 protected void sortResults(List<ResolveInfo> results) { 8535 Collections.sort(results, mResolvePrioritySorter); 8536 } 8537 8538 @Override 8539 protected void dumpFilter(PrintWriter out, String prefix, 8540 PackageParser.ProviderIntentInfo filter) { 8541 out.print(prefix); 8542 out.print( 8543 Integer.toHexString(System.identityHashCode(filter.provider))); 8544 out.print(' '); 8545 filter.provider.printComponentShortName(out); 8546 out.print(" filter "); 8547 out.println(Integer.toHexString(System.identityHashCode(filter))); 8548 } 8549 8550 @Override 8551 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8552 return filter.provider; 8553 } 8554 8555 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8556 PackageParser.Provider provider = (PackageParser.Provider)label; 8557 out.print(prefix); out.print( 8558 Integer.toHexString(System.identityHashCode(provider))); 8559 out.print(' '); 8560 provider.printComponentShortName(out); 8561 if (count > 1) { 8562 out.print(" ("); out.print(count); out.print(" filters)"); 8563 } 8564 out.println(); 8565 } 8566 8567 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8568 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8569 private int mFlags; 8570 }; 8571 8572 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8573 new Comparator<ResolveInfo>() { 8574 public int compare(ResolveInfo r1, ResolveInfo r2) { 8575 int v1 = r1.priority; 8576 int v2 = r2.priority; 8577 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8578 if (v1 != v2) { 8579 return (v1 > v2) ? -1 : 1; 8580 } 8581 v1 = r1.preferredOrder; 8582 v2 = r2.preferredOrder; 8583 if (v1 != v2) { 8584 return (v1 > v2) ? -1 : 1; 8585 } 8586 if (r1.isDefault != r2.isDefault) { 8587 return r1.isDefault ? -1 : 1; 8588 } 8589 v1 = r1.match; 8590 v2 = r2.match; 8591 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8592 if (v1 != v2) { 8593 return (v1 > v2) ? -1 : 1; 8594 } 8595 if (r1.system != r2.system) { 8596 return r1.system ? -1 : 1; 8597 } 8598 return 0; 8599 } 8600 }; 8601 8602 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8603 new Comparator<ProviderInfo>() { 8604 public int compare(ProviderInfo p1, ProviderInfo p2) { 8605 final int v1 = p1.initOrder; 8606 final int v2 = p2.initOrder; 8607 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8608 } 8609 }; 8610 8611 final void sendPackageBroadcast(final String action, final String pkg, 8612 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8613 final int[] userIds) { 8614 mHandler.post(new Runnable() { 8615 @Override 8616 public void run() { 8617 try { 8618 final IActivityManager am = ActivityManagerNative.getDefault(); 8619 if (am == null) return; 8620 final int[] resolvedUserIds; 8621 if (userIds == null) { 8622 resolvedUserIds = am.getRunningUserIds(); 8623 } else { 8624 resolvedUserIds = userIds; 8625 } 8626 for (int id : resolvedUserIds) { 8627 final Intent intent = new Intent(action, 8628 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8629 if (extras != null) { 8630 intent.putExtras(extras); 8631 } 8632 if (targetPkg != null) { 8633 intent.setPackage(targetPkg); 8634 } 8635 // Modify the UID when posting to other users 8636 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8637 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8638 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8639 intent.putExtra(Intent.EXTRA_UID, uid); 8640 } 8641 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8642 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8643 if (DEBUG_BROADCASTS) { 8644 RuntimeException here = new RuntimeException("here"); 8645 here.fillInStackTrace(); 8646 Slog.d(TAG, "Sending to user " + id + ": " 8647 + intent.toShortString(false, true, false, false) 8648 + " " + intent.getExtras(), here); 8649 } 8650 am.broadcastIntent(null, intent, null, finishedReceiver, 8651 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8652 finishedReceiver != null, false, id); 8653 } 8654 } catch (RemoteException ex) { 8655 } 8656 } 8657 }); 8658 } 8659 8660 /** 8661 * Check if the external storage media is available. This is true if there 8662 * is a mounted external storage medium or if the external storage is 8663 * emulated. 8664 */ 8665 private boolean isExternalMediaAvailable() { 8666 return mMediaMounted || Environment.isExternalStorageEmulated(); 8667 } 8668 8669 @Override 8670 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8671 // writer 8672 synchronized (mPackages) { 8673 if (!isExternalMediaAvailable()) { 8674 // If the external storage is no longer mounted at this point, 8675 // the caller may not have been able to delete all of this 8676 // packages files and can not delete any more. Bail. 8677 return null; 8678 } 8679 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8680 if (lastPackage != null) { 8681 pkgs.remove(lastPackage); 8682 } 8683 if (pkgs.size() > 0) { 8684 return pkgs.get(0); 8685 } 8686 } 8687 return null; 8688 } 8689 8690 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8691 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8692 userId, andCode ? 1 : 0, packageName); 8693 if (mSystemReady) { 8694 msg.sendToTarget(); 8695 } else { 8696 if (mPostSystemReadyMessages == null) { 8697 mPostSystemReadyMessages = new ArrayList<>(); 8698 } 8699 mPostSystemReadyMessages.add(msg); 8700 } 8701 } 8702 8703 void startCleaningPackages() { 8704 // reader 8705 synchronized (mPackages) { 8706 if (!isExternalMediaAvailable()) { 8707 return; 8708 } 8709 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8710 return; 8711 } 8712 } 8713 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8714 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8715 IActivityManager am = ActivityManagerNative.getDefault(); 8716 if (am != null) { 8717 try { 8718 am.startService(null, intent, null, UserHandle.USER_OWNER); 8719 } catch (RemoteException e) { 8720 } 8721 } 8722 } 8723 8724 @Override 8725 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8726 int installFlags, String installerPackageName, VerificationParams verificationParams, 8727 String packageAbiOverride) { 8728 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8729 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8730 } 8731 8732 @Override 8733 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8734 int installFlags, String installerPackageName, VerificationParams verificationParams, 8735 String packageAbiOverride, int userId) { 8736 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8737 8738 final int callingUid = Binder.getCallingUid(); 8739 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8740 8741 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8742 try { 8743 if (observer != null) { 8744 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8745 } 8746 } catch (RemoteException re) { 8747 } 8748 return; 8749 } 8750 8751 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8752 installFlags |= PackageManager.INSTALL_FROM_ADB; 8753 8754 } else { 8755 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8756 // about installerPackageName. 8757 8758 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8759 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8760 } 8761 8762 UserHandle user; 8763 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8764 user = UserHandle.ALL; 8765 } else { 8766 user = new UserHandle(userId); 8767 } 8768 8769 // Only system components can circumvent runtime permissions when installing. 8770 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8771 && mContext.checkCallingOrSelfPermission(Manifest.permission 8772 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8773 throw new SecurityException("You need the " 8774 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8775 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8776 } 8777 8778 verificationParams.setInstallerUid(callingUid); 8779 8780 final File originFile = new File(originPath); 8781 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8782 8783 final Message msg = mHandler.obtainMessage(INIT_COPY); 8784 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8785 null, verificationParams, user, packageAbiOverride); 8786 mHandler.sendMessage(msg); 8787 } 8788 8789 void installStage(String packageName, File stagedDir, String stagedCid, 8790 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8791 String installerPackageName, int installerUid, UserHandle user) { 8792 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8793 params.referrerUri, installerUid, null); 8794 8795 final OriginInfo origin; 8796 if (stagedDir != null) { 8797 origin = OriginInfo.fromStagedFile(stagedDir); 8798 } else { 8799 origin = OriginInfo.fromStagedContainer(stagedCid); 8800 } 8801 8802 final Message msg = mHandler.obtainMessage(INIT_COPY); 8803 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8804 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8805 mHandler.sendMessage(msg); 8806 } 8807 8808 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8809 Bundle extras = new Bundle(1); 8810 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8811 8812 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8813 packageName, extras, null, null, new int[] {userId}); 8814 try { 8815 IActivityManager am = ActivityManagerNative.getDefault(); 8816 final boolean isSystem = 8817 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8818 if (isSystem && am.isUserRunning(userId, false)) { 8819 // The just-installed/enabled app is bundled on the system, so presumed 8820 // to be able to run automatically without needing an explicit launch. 8821 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8822 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8823 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8824 .setPackage(packageName); 8825 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8826 android.app.AppOpsManager.OP_NONE, false, false, userId); 8827 } 8828 } catch (RemoteException e) { 8829 // shouldn't happen 8830 Slog.w(TAG, "Unable to bootstrap installed package", e); 8831 } 8832 } 8833 8834 @Override 8835 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8836 int userId) { 8837 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8838 PackageSetting pkgSetting; 8839 final int uid = Binder.getCallingUid(); 8840 enforceCrossUserPermission(uid, userId, true, true, 8841 "setApplicationHiddenSetting for user " + userId); 8842 8843 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8844 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8845 return false; 8846 } 8847 8848 long callingId = Binder.clearCallingIdentity(); 8849 try { 8850 boolean sendAdded = false; 8851 boolean sendRemoved = false; 8852 // writer 8853 synchronized (mPackages) { 8854 pkgSetting = mSettings.mPackages.get(packageName); 8855 if (pkgSetting == null) { 8856 return false; 8857 } 8858 if (pkgSetting.getHidden(userId) != hidden) { 8859 pkgSetting.setHidden(hidden, userId); 8860 mSettings.writePackageRestrictionsLPr(userId); 8861 if (hidden) { 8862 sendRemoved = true; 8863 } else { 8864 sendAdded = true; 8865 } 8866 } 8867 } 8868 if (sendAdded) { 8869 sendPackageAddedForUser(packageName, pkgSetting, userId); 8870 return true; 8871 } 8872 if (sendRemoved) { 8873 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8874 "hiding pkg"); 8875 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8876 } 8877 } finally { 8878 Binder.restoreCallingIdentity(callingId); 8879 } 8880 return false; 8881 } 8882 8883 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8884 int userId) { 8885 final PackageRemovedInfo info = new PackageRemovedInfo(); 8886 info.removedPackage = packageName; 8887 info.removedUsers = new int[] {userId}; 8888 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8889 info.sendBroadcast(false, false, false); 8890 } 8891 8892 /** 8893 * Returns true if application is not found or there was an error. Otherwise it returns 8894 * the hidden state of the package for the given user. 8895 */ 8896 @Override 8897 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8898 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8899 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8900 false, "getApplicationHidden for user " + userId); 8901 PackageSetting pkgSetting; 8902 long callingId = Binder.clearCallingIdentity(); 8903 try { 8904 // writer 8905 synchronized (mPackages) { 8906 pkgSetting = mSettings.mPackages.get(packageName); 8907 if (pkgSetting == null) { 8908 return true; 8909 } 8910 return pkgSetting.getHidden(userId); 8911 } 8912 } finally { 8913 Binder.restoreCallingIdentity(callingId); 8914 } 8915 } 8916 8917 /** 8918 * @hide 8919 */ 8920 @Override 8921 public int installExistingPackageAsUser(String packageName, int userId) { 8922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8923 null); 8924 PackageSetting pkgSetting; 8925 final int uid = Binder.getCallingUid(); 8926 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8927 + userId); 8928 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8929 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8930 } 8931 8932 long callingId = Binder.clearCallingIdentity(); 8933 try { 8934 boolean sendAdded = false; 8935 8936 // writer 8937 synchronized (mPackages) { 8938 pkgSetting = mSettings.mPackages.get(packageName); 8939 if (pkgSetting == null) { 8940 return PackageManager.INSTALL_FAILED_INVALID_URI; 8941 } 8942 if (!pkgSetting.getInstalled(userId)) { 8943 pkgSetting.setInstalled(true, userId); 8944 pkgSetting.setHidden(false, userId); 8945 mSettings.writePackageRestrictionsLPr(userId); 8946 sendAdded = true; 8947 } 8948 } 8949 8950 if (sendAdded) { 8951 sendPackageAddedForUser(packageName, pkgSetting, userId); 8952 } 8953 } finally { 8954 Binder.restoreCallingIdentity(callingId); 8955 } 8956 8957 return PackageManager.INSTALL_SUCCEEDED; 8958 } 8959 8960 boolean isUserRestricted(int userId, String restrictionKey) { 8961 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8962 if (restrictions.getBoolean(restrictionKey, false)) { 8963 Log.w(TAG, "User is restricted: " + restrictionKey); 8964 return true; 8965 } 8966 return false; 8967 } 8968 8969 @Override 8970 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8971 mContext.enforceCallingOrSelfPermission( 8972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8973 "Only package verification agents can verify applications"); 8974 8975 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8976 final PackageVerificationResponse response = new PackageVerificationResponse( 8977 verificationCode, Binder.getCallingUid()); 8978 msg.arg1 = id; 8979 msg.obj = response; 8980 mHandler.sendMessage(msg); 8981 } 8982 8983 @Override 8984 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8985 long millisecondsToDelay) { 8986 mContext.enforceCallingOrSelfPermission( 8987 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8988 "Only package verification agents can extend verification timeouts"); 8989 8990 final PackageVerificationState state = mPendingVerification.get(id); 8991 final PackageVerificationResponse response = new PackageVerificationResponse( 8992 verificationCodeAtTimeout, Binder.getCallingUid()); 8993 8994 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8995 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8996 } 8997 if (millisecondsToDelay < 0) { 8998 millisecondsToDelay = 0; 8999 } 9000 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9001 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9002 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9003 } 9004 9005 if ((state != null) && !state.timeoutExtended()) { 9006 state.extendTimeout(); 9007 9008 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9009 msg.arg1 = id; 9010 msg.obj = response; 9011 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9012 } 9013 } 9014 9015 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9016 int verificationCode, UserHandle user) { 9017 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9018 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9019 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9020 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9021 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9022 9023 mContext.sendBroadcastAsUser(intent, user, 9024 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9025 } 9026 9027 private ComponentName matchComponentForVerifier(String packageName, 9028 List<ResolveInfo> receivers) { 9029 ActivityInfo targetReceiver = null; 9030 9031 final int NR = receivers.size(); 9032 for (int i = 0; i < NR; i++) { 9033 final ResolveInfo info = receivers.get(i); 9034 if (info.activityInfo == null) { 9035 continue; 9036 } 9037 9038 if (packageName.equals(info.activityInfo.packageName)) { 9039 targetReceiver = info.activityInfo; 9040 break; 9041 } 9042 } 9043 9044 if (targetReceiver == null) { 9045 return null; 9046 } 9047 9048 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9049 } 9050 9051 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9052 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9053 if (pkgInfo.verifiers.length == 0) { 9054 return null; 9055 } 9056 9057 final int N = pkgInfo.verifiers.length; 9058 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9059 for (int i = 0; i < N; i++) { 9060 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9061 9062 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9063 receivers); 9064 if (comp == null) { 9065 continue; 9066 } 9067 9068 final int verifierUid = getUidForVerifier(verifierInfo); 9069 if (verifierUid == -1) { 9070 continue; 9071 } 9072 9073 if (DEBUG_VERIFY) { 9074 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9075 + " with the correct signature"); 9076 } 9077 sufficientVerifiers.add(comp); 9078 verificationState.addSufficientVerifier(verifierUid); 9079 } 9080 9081 return sufficientVerifiers; 9082 } 9083 9084 private int getUidForVerifier(VerifierInfo verifierInfo) { 9085 synchronized (mPackages) { 9086 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9087 if (pkg == null) { 9088 return -1; 9089 } else if (pkg.mSignatures.length != 1) { 9090 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9091 + " has more than one signature; ignoring"); 9092 return -1; 9093 } 9094 9095 /* 9096 * If the public key of the package's signature does not match 9097 * our expected public key, then this is a different package and 9098 * we should skip. 9099 */ 9100 9101 final byte[] expectedPublicKey; 9102 try { 9103 final Signature verifierSig = pkg.mSignatures[0]; 9104 final PublicKey publicKey = verifierSig.getPublicKey(); 9105 expectedPublicKey = publicKey.getEncoded(); 9106 } catch (CertificateException e) { 9107 return -1; 9108 } 9109 9110 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9111 9112 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9113 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9114 + " does not have the expected public key; ignoring"); 9115 return -1; 9116 } 9117 9118 return pkg.applicationInfo.uid; 9119 } 9120 } 9121 9122 @Override 9123 public void finishPackageInstall(int token) { 9124 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9125 9126 if (DEBUG_INSTALL) { 9127 Slog.v(TAG, "BM finishing package install for " + token); 9128 } 9129 9130 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9131 mHandler.sendMessage(msg); 9132 } 9133 9134 /** 9135 * Get the verification agent timeout. 9136 * 9137 * @return verification timeout in milliseconds 9138 */ 9139 private long getVerificationTimeout() { 9140 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9141 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9142 DEFAULT_VERIFICATION_TIMEOUT); 9143 } 9144 9145 /** 9146 * Get the default verification agent response code. 9147 * 9148 * @return default verification response code 9149 */ 9150 private int getDefaultVerificationResponse() { 9151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9152 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9153 DEFAULT_VERIFICATION_RESPONSE); 9154 } 9155 9156 /** 9157 * Check whether or not package verification has been enabled. 9158 * 9159 * @return true if verification should be performed 9160 */ 9161 private boolean isVerificationEnabled(int userId, int installFlags) { 9162 if (!DEFAULT_VERIFY_ENABLE) { 9163 return false; 9164 } 9165 9166 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9167 9168 // Check if installing from ADB 9169 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9170 // Do not run verification in a test harness environment 9171 if (ActivityManager.isRunningInTestHarness()) { 9172 return false; 9173 } 9174 if (ensureVerifyAppsEnabled) { 9175 return true; 9176 } 9177 // Check if the developer does not want package verification for ADB installs 9178 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9179 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9180 return false; 9181 } 9182 } 9183 9184 if (ensureVerifyAppsEnabled) { 9185 return true; 9186 } 9187 9188 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9189 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9190 } 9191 9192 @Override 9193 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9194 throws RemoteException { 9195 mContext.enforceCallingOrSelfPermission( 9196 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9197 "Only intentfilter verification agents can verify applications"); 9198 9199 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9200 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9201 Binder.getCallingUid(), verificationCode, failedDomains); 9202 msg.arg1 = id; 9203 msg.obj = response; 9204 mHandler.sendMessage(msg); 9205 } 9206 9207 @Override 9208 public int getIntentVerificationStatus(String packageName, int userId) { 9209 synchronized (mPackages) { 9210 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9211 } 9212 } 9213 9214 @Override 9215 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9216 boolean result = false; 9217 synchronized (mPackages) { 9218 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9219 } 9220 scheduleWritePackageRestrictionsLocked(userId); 9221 return result; 9222 } 9223 9224 @Override 9225 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9226 synchronized (mPackages) { 9227 return mSettings.getIntentFilterVerificationsLPr(packageName); 9228 } 9229 } 9230 9231 @Override 9232 public List<IntentFilter> getAllIntentFilters(String packageName) { 9233 if (TextUtils.isEmpty(packageName)) { 9234 return Collections.<IntentFilter>emptyList(); 9235 } 9236 synchronized (mPackages) { 9237 PackageParser.Package pkg = mPackages.get(packageName); 9238 if (pkg == null || pkg.activities == null) { 9239 return Collections.<IntentFilter>emptyList(); 9240 } 9241 final int count = pkg.activities.size(); 9242 ArrayList<IntentFilter> result = new ArrayList<>(); 9243 for (int n=0; n<count; n++) { 9244 PackageParser.Activity activity = pkg.activities.get(n); 9245 if (activity.intents != null || activity.intents.size() > 0) { 9246 result.addAll(activity.intents); 9247 } 9248 } 9249 return result; 9250 } 9251 } 9252 9253 @Override 9254 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9255 synchronized (mPackages) { 9256 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9257 result |= updateIntentVerificationStatus(packageName, 9258 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9259 UserHandle.myUserId()); 9260 return result; 9261 } 9262 } 9263 9264 @Override 9265 public String getDefaultBrowserPackageName(int userId) { 9266 synchronized (mPackages) { 9267 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9268 } 9269 } 9270 9271 /** 9272 * Get the "allow unknown sources" setting. 9273 * 9274 * @return the current "allow unknown sources" setting 9275 */ 9276 private int getUnknownSourcesSettings() { 9277 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9278 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9279 -1); 9280 } 9281 9282 @Override 9283 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9284 final int uid = Binder.getCallingUid(); 9285 // writer 9286 synchronized (mPackages) { 9287 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9288 if (targetPackageSetting == null) { 9289 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9290 } 9291 9292 PackageSetting installerPackageSetting; 9293 if (installerPackageName != null) { 9294 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9295 if (installerPackageSetting == null) { 9296 throw new IllegalArgumentException("Unknown installer package: " 9297 + installerPackageName); 9298 } 9299 } else { 9300 installerPackageSetting = null; 9301 } 9302 9303 Signature[] callerSignature; 9304 Object obj = mSettings.getUserIdLPr(uid); 9305 if (obj != null) { 9306 if (obj instanceof SharedUserSetting) { 9307 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9308 } else if (obj instanceof PackageSetting) { 9309 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9310 } else { 9311 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9312 } 9313 } else { 9314 throw new SecurityException("Unknown calling uid " + uid); 9315 } 9316 9317 // Verify: can't set installerPackageName to a package that is 9318 // not signed with the same cert as the caller. 9319 if (installerPackageSetting != null) { 9320 if (compareSignatures(callerSignature, 9321 installerPackageSetting.signatures.mSignatures) 9322 != PackageManager.SIGNATURE_MATCH) { 9323 throw new SecurityException( 9324 "Caller does not have same cert as new installer package " 9325 + installerPackageName); 9326 } 9327 } 9328 9329 // Verify: if target already has an installer package, it must 9330 // be signed with the same cert as the caller. 9331 if (targetPackageSetting.installerPackageName != null) { 9332 PackageSetting setting = mSettings.mPackages.get( 9333 targetPackageSetting.installerPackageName); 9334 // If the currently set package isn't valid, then it's always 9335 // okay to change it. 9336 if (setting != null) { 9337 if (compareSignatures(callerSignature, 9338 setting.signatures.mSignatures) 9339 != PackageManager.SIGNATURE_MATCH) { 9340 throw new SecurityException( 9341 "Caller does not have same cert as old installer package " 9342 + targetPackageSetting.installerPackageName); 9343 } 9344 } 9345 } 9346 9347 // Okay! 9348 targetPackageSetting.installerPackageName = installerPackageName; 9349 scheduleWriteSettingsLocked(); 9350 } 9351 } 9352 9353 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9354 // Queue up an async operation since the package installation may take a little while. 9355 mHandler.post(new Runnable() { 9356 public void run() { 9357 mHandler.removeCallbacks(this); 9358 // Result object to be returned 9359 PackageInstalledInfo res = new PackageInstalledInfo(); 9360 res.returnCode = currentStatus; 9361 res.uid = -1; 9362 res.pkg = null; 9363 res.removedInfo = new PackageRemovedInfo(); 9364 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9365 args.doPreInstall(res.returnCode); 9366 synchronized (mInstallLock) { 9367 installPackageLI(args, res); 9368 } 9369 args.doPostInstall(res.returnCode, res.uid); 9370 } 9371 9372 // A restore should be performed at this point if (a) the install 9373 // succeeded, (b) the operation is not an update, and (c) the new 9374 // package has not opted out of backup participation. 9375 final boolean update = res.removedInfo.removedPackage != null; 9376 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9377 boolean doRestore = !update 9378 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9379 9380 // Set up the post-install work request bookkeeping. This will be used 9381 // and cleaned up by the post-install event handling regardless of whether 9382 // there's a restore pass performed. Token values are >= 1. 9383 int token; 9384 if (mNextInstallToken < 0) mNextInstallToken = 1; 9385 token = mNextInstallToken++; 9386 9387 PostInstallData data = new PostInstallData(args, res); 9388 mRunningInstalls.put(token, data); 9389 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9390 9391 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9392 // Pass responsibility to the Backup Manager. It will perform a 9393 // restore if appropriate, then pass responsibility back to the 9394 // Package Manager to run the post-install observer callbacks 9395 // and broadcasts. 9396 IBackupManager bm = IBackupManager.Stub.asInterface( 9397 ServiceManager.getService(Context.BACKUP_SERVICE)); 9398 if (bm != null) { 9399 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9400 + " to BM for possible restore"); 9401 try { 9402 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9403 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9404 } else { 9405 doRestore = false; 9406 } 9407 } catch (RemoteException e) { 9408 // can't happen; the backup manager is local 9409 } catch (Exception e) { 9410 Slog.e(TAG, "Exception trying to enqueue restore", e); 9411 doRestore = false; 9412 } 9413 } else { 9414 Slog.e(TAG, "Backup Manager not found!"); 9415 doRestore = false; 9416 } 9417 } 9418 9419 if (!doRestore) { 9420 // No restore possible, or the Backup Manager was mysteriously not 9421 // available -- just fire the post-install work request directly. 9422 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9423 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9424 mHandler.sendMessage(msg); 9425 } 9426 } 9427 }); 9428 } 9429 9430 private abstract class HandlerParams { 9431 private static final int MAX_RETRIES = 4; 9432 9433 /** 9434 * Number of times startCopy() has been attempted and had a non-fatal 9435 * error. 9436 */ 9437 private int mRetries = 0; 9438 9439 /** User handle for the user requesting the information or installation. */ 9440 private final UserHandle mUser; 9441 9442 HandlerParams(UserHandle user) { 9443 mUser = user; 9444 } 9445 9446 UserHandle getUser() { 9447 return mUser; 9448 } 9449 9450 final boolean startCopy() { 9451 boolean res; 9452 try { 9453 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9454 9455 if (++mRetries > MAX_RETRIES) { 9456 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9457 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9458 handleServiceError(); 9459 return false; 9460 } else { 9461 handleStartCopy(); 9462 res = true; 9463 } 9464 } catch (RemoteException e) { 9465 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9466 mHandler.sendEmptyMessage(MCS_RECONNECT); 9467 res = false; 9468 } 9469 handleReturnCode(); 9470 return res; 9471 } 9472 9473 final void serviceError() { 9474 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9475 handleServiceError(); 9476 handleReturnCode(); 9477 } 9478 9479 abstract void handleStartCopy() throws RemoteException; 9480 abstract void handleServiceError(); 9481 abstract void handleReturnCode(); 9482 } 9483 9484 class MeasureParams extends HandlerParams { 9485 private final PackageStats mStats; 9486 private boolean mSuccess; 9487 9488 private final IPackageStatsObserver mObserver; 9489 9490 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9491 super(new UserHandle(stats.userHandle)); 9492 mObserver = observer; 9493 mStats = stats; 9494 } 9495 9496 @Override 9497 public String toString() { 9498 return "MeasureParams{" 9499 + Integer.toHexString(System.identityHashCode(this)) 9500 + " " + mStats.packageName + "}"; 9501 } 9502 9503 @Override 9504 void handleStartCopy() throws RemoteException { 9505 synchronized (mInstallLock) { 9506 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9507 } 9508 9509 if (mSuccess) { 9510 final boolean mounted; 9511 if (Environment.isExternalStorageEmulated()) { 9512 mounted = true; 9513 } else { 9514 final String status = Environment.getExternalStorageState(); 9515 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9516 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9517 } 9518 9519 if (mounted) { 9520 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9521 9522 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9523 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9524 9525 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9526 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9527 9528 // Always subtract cache size, since it's a subdirectory 9529 mStats.externalDataSize -= mStats.externalCacheSize; 9530 9531 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9532 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9533 9534 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9535 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9536 } 9537 } 9538 } 9539 9540 @Override 9541 void handleReturnCode() { 9542 if (mObserver != null) { 9543 try { 9544 mObserver.onGetStatsCompleted(mStats, mSuccess); 9545 } catch (RemoteException e) { 9546 Slog.i(TAG, "Observer no longer exists."); 9547 } 9548 } 9549 } 9550 9551 @Override 9552 void handleServiceError() { 9553 Slog.e(TAG, "Could not measure application " + mStats.packageName 9554 + " external storage"); 9555 } 9556 } 9557 9558 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9559 throws RemoteException { 9560 long result = 0; 9561 for (File path : paths) { 9562 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9563 } 9564 return result; 9565 } 9566 9567 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9568 for (File path : paths) { 9569 try { 9570 mcs.clearDirectory(path.getAbsolutePath()); 9571 } catch (RemoteException e) { 9572 } 9573 } 9574 } 9575 9576 static class OriginInfo { 9577 /** 9578 * Location where install is coming from, before it has been 9579 * copied/renamed into place. This could be a single monolithic APK 9580 * file, or a cluster directory. This location may be untrusted. 9581 */ 9582 final File file; 9583 final String cid; 9584 9585 /** 9586 * Flag indicating that {@link #file} or {@link #cid} has already been 9587 * staged, meaning downstream users don't need to defensively copy the 9588 * contents. 9589 */ 9590 final boolean staged; 9591 9592 /** 9593 * Flag indicating that {@link #file} or {@link #cid} is an already 9594 * installed app that is being moved. 9595 */ 9596 final boolean existing; 9597 9598 final String resolvedPath; 9599 final File resolvedFile; 9600 9601 static OriginInfo fromNothing() { 9602 return new OriginInfo(null, null, false, false); 9603 } 9604 9605 static OriginInfo fromUntrustedFile(File file) { 9606 return new OriginInfo(file, null, false, false); 9607 } 9608 9609 static OriginInfo fromExistingFile(File file) { 9610 return new OriginInfo(file, null, false, true); 9611 } 9612 9613 static OriginInfo fromStagedFile(File file) { 9614 return new OriginInfo(file, null, true, false); 9615 } 9616 9617 static OriginInfo fromStagedContainer(String cid) { 9618 return new OriginInfo(null, cid, true, false); 9619 } 9620 9621 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9622 this.file = file; 9623 this.cid = cid; 9624 this.staged = staged; 9625 this.existing = existing; 9626 9627 if (cid != null) { 9628 resolvedPath = PackageHelper.getSdDir(cid); 9629 resolvedFile = new File(resolvedPath); 9630 } else if (file != null) { 9631 resolvedPath = file.getAbsolutePath(); 9632 resolvedFile = file; 9633 } else { 9634 resolvedPath = null; 9635 resolvedFile = null; 9636 } 9637 } 9638 } 9639 9640 class MoveInfo { 9641 final int moveId; 9642 final String fromUuid; 9643 final String toUuid; 9644 final String packageName; 9645 final String dataAppName; 9646 final int appId; 9647 final String seinfo; 9648 9649 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9650 String dataAppName, int appId, String seinfo) { 9651 this.moveId = moveId; 9652 this.fromUuid = fromUuid; 9653 this.toUuid = toUuid; 9654 this.packageName = packageName; 9655 this.dataAppName = dataAppName; 9656 this.appId = appId; 9657 this.seinfo = seinfo; 9658 } 9659 } 9660 9661 class InstallParams extends HandlerParams { 9662 final OriginInfo origin; 9663 final MoveInfo move; 9664 final IPackageInstallObserver2 observer; 9665 int installFlags; 9666 final String installerPackageName; 9667 final String volumeUuid; 9668 final VerificationParams verificationParams; 9669 private InstallArgs mArgs; 9670 private int mRet; 9671 final String packageAbiOverride; 9672 9673 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9674 int installFlags, String installerPackageName, String volumeUuid, 9675 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9676 super(user); 9677 this.origin = origin; 9678 this.move = move; 9679 this.observer = observer; 9680 this.installFlags = installFlags; 9681 this.installerPackageName = installerPackageName; 9682 this.volumeUuid = volumeUuid; 9683 this.verificationParams = verificationParams; 9684 this.packageAbiOverride = packageAbiOverride; 9685 } 9686 9687 @Override 9688 public String toString() { 9689 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9690 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9691 } 9692 9693 public ManifestDigest getManifestDigest() { 9694 if (verificationParams == null) { 9695 return null; 9696 } 9697 return verificationParams.getManifestDigest(); 9698 } 9699 9700 private int installLocationPolicy(PackageInfoLite pkgLite) { 9701 String packageName = pkgLite.packageName; 9702 int installLocation = pkgLite.installLocation; 9703 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9704 // reader 9705 synchronized (mPackages) { 9706 PackageParser.Package pkg = mPackages.get(packageName); 9707 if (pkg != null) { 9708 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9709 // Check for downgrading. 9710 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9711 try { 9712 checkDowngrade(pkg, pkgLite); 9713 } catch (PackageManagerException e) { 9714 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9715 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9716 } 9717 } 9718 // Check for updated system application. 9719 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9720 if (onSd) { 9721 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9722 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9723 } 9724 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9725 } else { 9726 if (onSd) { 9727 // Install flag overrides everything. 9728 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9729 } 9730 // If current upgrade specifies particular preference 9731 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9732 // Application explicitly specified internal. 9733 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9734 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9735 // App explictly prefers external. Let policy decide 9736 } else { 9737 // Prefer previous location 9738 if (isExternal(pkg)) { 9739 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9740 } 9741 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9742 } 9743 } 9744 } else { 9745 // Invalid install. Return error code 9746 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9747 } 9748 } 9749 } 9750 // All the special cases have been taken care of. 9751 // Return result based on recommended install location. 9752 if (onSd) { 9753 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9754 } 9755 return pkgLite.recommendedInstallLocation; 9756 } 9757 9758 /* 9759 * Invoke remote method to get package information and install 9760 * location values. Override install location based on default 9761 * policy if needed and then create install arguments based 9762 * on the install location. 9763 */ 9764 public void handleStartCopy() throws RemoteException { 9765 int ret = PackageManager.INSTALL_SUCCEEDED; 9766 9767 // If we're already staged, we've firmly committed to an install location 9768 if (origin.staged) { 9769 if (origin.file != null) { 9770 installFlags |= PackageManager.INSTALL_INTERNAL; 9771 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9772 } else if (origin.cid != null) { 9773 installFlags |= PackageManager.INSTALL_EXTERNAL; 9774 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9775 } else { 9776 throw new IllegalStateException("Invalid stage location"); 9777 } 9778 } 9779 9780 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9781 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9782 9783 PackageInfoLite pkgLite = null; 9784 9785 if (onInt && onSd) { 9786 // Check if both bits are set. 9787 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9788 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9789 } else { 9790 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9791 packageAbiOverride); 9792 9793 /* 9794 * If we have too little free space, try to free cache 9795 * before giving up. 9796 */ 9797 if (!origin.staged && pkgLite.recommendedInstallLocation 9798 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9799 // TODO: focus freeing disk space on the target device 9800 final StorageManager storage = StorageManager.from(mContext); 9801 final long lowThreshold = storage.getStorageLowBytes( 9802 Environment.getDataDirectory()); 9803 9804 final long sizeBytes = mContainerService.calculateInstalledSize( 9805 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9806 9807 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9808 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9809 installFlags, packageAbiOverride); 9810 } 9811 9812 /* 9813 * The cache free must have deleted the file we 9814 * downloaded to install. 9815 * 9816 * TODO: fix the "freeCache" call to not delete 9817 * the file we care about. 9818 */ 9819 if (pkgLite.recommendedInstallLocation 9820 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9821 pkgLite.recommendedInstallLocation 9822 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9823 } 9824 } 9825 } 9826 9827 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9828 int loc = pkgLite.recommendedInstallLocation; 9829 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9830 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9831 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9832 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9833 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9834 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9835 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9836 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9837 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9838 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9839 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9840 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9841 } else { 9842 // Override with defaults if needed. 9843 loc = installLocationPolicy(pkgLite); 9844 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9845 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9846 } else if (!onSd && !onInt) { 9847 // Override install location with flags 9848 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9849 // Set the flag to install on external media. 9850 installFlags |= PackageManager.INSTALL_EXTERNAL; 9851 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9852 } else { 9853 // Make sure the flag for installing on external 9854 // media is unset 9855 installFlags |= PackageManager.INSTALL_INTERNAL; 9856 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9857 } 9858 } 9859 } 9860 } 9861 9862 final InstallArgs args = createInstallArgs(this); 9863 mArgs = args; 9864 9865 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9866 /* 9867 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9868 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9869 */ 9870 int userIdentifier = getUser().getIdentifier(); 9871 if (userIdentifier == UserHandle.USER_ALL 9872 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9873 userIdentifier = UserHandle.USER_OWNER; 9874 } 9875 9876 /* 9877 * Determine if we have any installed package verifiers. If we 9878 * do, then we'll defer to them to verify the packages. 9879 */ 9880 final int requiredUid = mRequiredVerifierPackage == null ? -1 9881 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9882 if (!origin.existing && requiredUid != -1 9883 && isVerificationEnabled(userIdentifier, installFlags)) { 9884 final Intent verification = new Intent( 9885 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9886 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9887 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9888 PACKAGE_MIME_TYPE); 9889 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9890 9891 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9892 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9893 0 /* TODO: Which userId? */); 9894 9895 if (DEBUG_VERIFY) { 9896 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9897 + verification.toString() + " with " + pkgLite.verifiers.length 9898 + " optional verifiers"); 9899 } 9900 9901 final int verificationId = mPendingVerificationToken++; 9902 9903 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9904 9905 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9906 installerPackageName); 9907 9908 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9909 installFlags); 9910 9911 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9912 pkgLite.packageName); 9913 9914 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9915 pkgLite.versionCode); 9916 9917 if (verificationParams != null) { 9918 if (verificationParams.getVerificationURI() != null) { 9919 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9920 verificationParams.getVerificationURI()); 9921 } 9922 if (verificationParams.getOriginatingURI() != null) { 9923 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9924 verificationParams.getOriginatingURI()); 9925 } 9926 if (verificationParams.getReferrer() != null) { 9927 verification.putExtra(Intent.EXTRA_REFERRER, 9928 verificationParams.getReferrer()); 9929 } 9930 if (verificationParams.getOriginatingUid() >= 0) { 9931 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9932 verificationParams.getOriginatingUid()); 9933 } 9934 if (verificationParams.getInstallerUid() >= 0) { 9935 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9936 verificationParams.getInstallerUid()); 9937 } 9938 } 9939 9940 final PackageVerificationState verificationState = new PackageVerificationState( 9941 requiredUid, args); 9942 9943 mPendingVerification.append(verificationId, verificationState); 9944 9945 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9946 receivers, verificationState); 9947 9948 /* 9949 * If any sufficient verifiers were listed in the package 9950 * manifest, attempt to ask them. 9951 */ 9952 if (sufficientVerifiers != null) { 9953 final int N = sufficientVerifiers.size(); 9954 if (N == 0) { 9955 Slog.i(TAG, "Additional verifiers required, but none installed."); 9956 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9957 } else { 9958 for (int i = 0; i < N; i++) { 9959 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9960 9961 final Intent sufficientIntent = new Intent(verification); 9962 sufficientIntent.setComponent(verifierComponent); 9963 9964 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9965 } 9966 } 9967 } 9968 9969 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9970 mRequiredVerifierPackage, receivers); 9971 if (ret == PackageManager.INSTALL_SUCCEEDED 9972 && mRequiredVerifierPackage != null) { 9973 /* 9974 * Send the intent to the required verification agent, 9975 * but only start the verification timeout after the 9976 * target BroadcastReceivers have run. 9977 */ 9978 verification.setComponent(requiredVerifierComponent); 9979 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9980 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9981 new BroadcastReceiver() { 9982 @Override 9983 public void onReceive(Context context, Intent intent) { 9984 final Message msg = mHandler 9985 .obtainMessage(CHECK_PENDING_VERIFICATION); 9986 msg.arg1 = verificationId; 9987 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9988 } 9989 }, null, 0, null, null); 9990 9991 /* 9992 * We don't want the copy to proceed until verification 9993 * succeeds, so null out this field. 9994 */ 9995 mArgs = null; 9996 } 9997 } else { 9998 /* 9999 * No package verification is enabled, so immediately start 10000 * the remote call to initiate copy using temporary file. 10001 */ 10002 ret = args.copyApk(mContainerService, true); 10003 } 10004 } 10005 10006 mRet = ret; 10007 } 10008 10009 @Override 10010 void handleReturnCode() { 10011 // If mArgs is null, then MCS couldn't be reached. When it 10012 // reconnects, it will try again to install. At that point, this 10013 // will succeed. 10014 if (mArgs != null) { 10015 processPendingInstall(mArgs, mRet); 10016 } 10017 } 10018 10019 @Override 10020 void handleServiceError() { 10021 mArgs = createInstallArgs(this); 10022 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10023 } 10024 10025 public boolean isForwardLocked() { 10026 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10027 } 10028 } 10029 10030 /** 10031 * Used during creation of InstallArgs 10032 * 10033 * @param installFlags package installation flags 10034 * @return true if should be installed on external storage 10035 */ 10036 private static boolean installOnExternalAsec(int installFlags) { 10037 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10038 return false; 10039 } 10040 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10041 return true; 10042 } 10043 return false; 10044 } 10045 10046 /** 10047 * Used during creation of InstallArgs 10048 * 10049 * @param installFlags package installation flags 10050 * @return true if should be installed as forward locked 10051 */ 10052 private static boolean installForwardLocked(int installFlags) { 10053 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10054 } 10055 10056 private InstallArgs createInstallArgs(InstallParams params) { 10057 if (params.move != null) { 10058 return new MoveInstallArgs(params); 10059 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10060 return new AsecInstallArgs(params); 10061 } else { 10062 return new FileInstallArgs(params); 10063 } 10064 } 10065 10066 /** 10067 * Create args that describe an existing installed package. Typically used 10068 * when cleaning up old installs, or used as a move source. 10069 */ 10070 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10071 String resourcePath, String[] instructionSets) { 10072 final boolean isInAsec; 10073 if (installOnExternalAsec(installFlags)) { 10074 /* Apps on SD card are always in ASEC containers. */ 10075 isInAsec = true; 10076 } else if (installForwardLocked(installFlags) 10077 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10078 /* 10079 * Forward-locked apps are only in ASEC containers if they're the 10080 * new style 10081 */ 10082 isInAsec = true; 10083 } else { 10084 isInAsec = false; 10085 } 10086 10087 if (isInAsec) { 10088 return new AsecInstallArgs(codePath, instructionSets, 10089 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10090 } else { 10091 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10092 } 10093 } 10094 10095 static abstract class InstallArgs { 10096 /** @see InstallParams#origin */ 10097 final OriginInfo origin; 10098 /** @see InstallParams#move */ 10099 final MoveInfo move; 10100 10101 final IPackageInstallObserver2 observer; 10102 // Always refers to PackageManager flags only 10103 final int installFlags; 10104 final String installerPackageName; 10105 final String volumeUuid; 10106 final ManifestDigest manifestDigest; 10107 final UserHandle user; 10108 final String abiOverride; 10109 10110 // The list of instruction sets supported by this app. This is currently 10111 // only used during the rmdex() phase to clean up resources. We can get rid of this 10112 // if we move dex files under the common app path. 10113 /* nullable */ String[] instructionSets; 10114 10115 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10116 int installFlags, String installerPackageName, String volumeUuid, 10117 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10118 String abiOverride) { 10119 this.origin = origin; 10120 this.move = move; 10121 this.installFlags = installFlags; 10122 this.observer = observer; 10123 this.installerPackageName = installerPackageName; 10124 this.volumeUuid = volumeUuid; 10125 this.manifestDigest = manifestDigest; 10126 this.user = user; 10127 this.instructionSets = instructionSets; 10128 this.abiOverride = abiOverride; 10129 } 10130 10131 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10132 abstract int doPreInstall(int status); 10133 10134 /** 10135 * Rename package into final resting place. All paths on the given 10136 * scanned package should be updated to reflect the rename. 10137 */ 10138 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10139 abstract int doPostInstall(int status, int uid); 10140 10141 /** @see PackageSettingBase#codePathString */ 10142 abstract String getCodePath(); 10143 /** @see PackageSettingBase#resourcePathString */ 10144 abstract String getResourcePath(); 10145 10146 // Need installer lock especially for dex file removal. 10147 abstract void cleanUpResourcesLI(); 10148 abstract boolean doPostDeleteLI(boolean delete); 10149 10150 /** 10151 * Called before the source arguments are copied. This is used mostly 10152 * for MoveParams when it needs to read the source file to put it in the 10153 * destination. 10154 */ 10155 int doPreCopy() { 10156 return PackageManager.INSTALL_SUCCEEDED; 10157 } 10158 10159 /** 10160 * Called after the source arguments are copied. This is used mostly for 10161 * MoveParams when it needs to read the source file to put it in the 10162 * destination. 10163 * 10164 * @return 10165 */ 10166 int doPostCopy(int uid) { 10167 return PackageManager.INSTALL_SUCCEEDED; 10168 } 10169 10170 protected boolean isFwdLocked() { 10171 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10172 } 10173 10174 protected boolean isExternalAsec() { 10175 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10176 } 10177 10178 UserHandle getUser() { 10179 return user; 10180 } 10181 } 10182 10183 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10184 if (!allCodePaths.isEmpty()) { 10185 if (instructionSets == null) { 10186 throw new IllegalStateException("instructionSet == null"); 10187 } 10188 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10189 for (String codePath : allCodePaths) { 10190 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10191 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10192 if (retCode < 0) { 10193 Slog.w(TAG, "Couldn't remove dex file for package: " 10194 + " at location " + codePath + ", retcode=" + retCode); 10195 // we don't consider this to be a failure of the core package deletion 10196 } 10197 } 10198 } 10199 } 10200 } 10201 10202 /** 10203 * Logic to handle installation of non-ASEC applications, including copying 10204 * and renaming logic. 10205 */ 10206 class FileInstallArgs extends InstallArgs { 10207 private File codeFile; 10208 private File resourceFile; 10209 10210 // Example topology: 10211 // /data/app/com.example/base.apk 10212 // /data/app/com.example/split_foo.apk 10213 // /data/app/com.example/lib/arm/libfoo.so 10214 // /data/app/com.example/lib/arm64/libfoo.so 10215 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10216 10217 /** New install */ 10218 FileInstallArgs(InstallParams params) { 10219 super(params.origin, params.move, params.observer, params.installFlags, 10220 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10221 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10222 if (isFwdLocked()) { 10223 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10224 } 10225 } 10226 10227 /** Existing install */ 10228 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10229 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10230 null); 10231 this.codeFile = (codePath != null) ? new File(codePath) : null; 10232 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10233 } 10234 10235 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10236 if (origin.staged) { 10237 Slog.d(TAG, origin.file + " already staged; skipping copy"); 10238 codeFile = origin.file; 10239 resourceFile = origin.file; 10240 return PackageManager.INSTALL_SUCCEEDED; 10241 } 10242 10243 try { 10244 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10245 codeFile = tempDir; 10246 resourceFile = tempDir; 10247 } catch (IOException e) { 10248 Slog.w(TAG, "Failed to create copy file: " + e); 10249 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10250 } 10251 10252 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10253 @Override 10254 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10255 if (!FileUtils.isValidExtFilename(name)) { 10256 throw new IllegalArgumentException("Invalid filename: " + name); 10257 } 10258 try { 10259 final File file = new File(codeFile, name); 10260 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10261 O_RDWR | O_CREAT, 0644); 10262 Os.chmod(file.getAbsolutePath(), 0644); 10263 return new ParcelFileDescriptor(fd); 10264 } catch (ErrnoException e) { 10265 throw new RemoteException("Failed to open: " + e.getMessage()); 10266 } 10267 } 10268 }; 10269 10270 int ret = PackageManager.INSTALL_SUCCEEDED; 10271 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10272 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10273 Slog.e(TAG, "Failed to copy package"); 10274 return ret; 10275 } 10276 10277 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10278 NativeLibraryHelper.Handle handle = null; 10279 try { 10280 handle = NativeLibraryHelper.Handle.create(codeFile); 10281 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10282 abiOverride); 10283 } catch (IOException e) { 10284 Slog.e(TAG, "Copying native libraries failed", e); 10285 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10286 } finally { 10287 IoUtils.closeQuietly(handle); 10288 } 10289 10290 return ret; 10291 } 10292 10293 int doPreInstall(int status) { 10294 if (status != PackageManager.INSTALL_SUCCEEDED) { 10295 cleanUp(); 10296 } 10297 return status; 10298 } 10299 10300 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10301 if (status != PackageManager.INSTALL_SUCCEEDED) { 10302 cleanUp(); 10303 return false; 10304 } 10305 10306 final File targetDir = codeFile.getParentFile(); 10307 final File beforeCodeFile = codeFile; 10308 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10309 10310 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10311 try { 10312 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10313 } catch (ErrnoException e) { 10314 Slog.d(TAG, "Failed to rename", e); 10315 return false; 10316 } 10317 10318 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10319 Slog.d(TAG, "Failed to restorecon"); 10320 return false; 10321 } 10322 10323 // Reflect the rename internally 10324 codeFile = afterCodeFile; 10325 resourceFile = afterCodeFile; 10326 10327 // Reflect the rename in scanned details 10328 pkg.codePath = afterCodeFile.getAbsolutePath(); 10329 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10330 pkg.baseCodePath); 10331 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10332 pkg.splitCodePaths); 10333 10334 // Reflect the rename in app info 10335 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10336 pkg.applicationInfo.setCodePath(pkg.codePath); 10337 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10338 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10339 pkg.applicationInfo.setResourcePath(pkg.codePath); 10340 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10341 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10342 10343 return true; 10344 } 10345 10346 int doPostInstall(int status, int uid) { 10347 if (status != PackageManager.INSTALL_SUCCEEDED) { 10348 cleanUp(); 10349 } 10350 return status; 10351 } 10352 10353 @Override 10354 String getCodePath() { 10355 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10356 } 10357 10358 @Override 10359 String getResourcePath() { 10360 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10361 } 10362 10363 private boolean cleanUp() { 10364 if (codeFile == null || !codeFile.exists()) { 10365 return false; 10366 } 10367 10368 if (codeFile.isDirectory()) { 10369 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10370 } else { 10371 codeFile.delete(); 10372 } 10373 10374 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10375 resourceFile.delete(); 10376 } 10377 10378 return true; 10379 } 10380 10381 void cleanUpResourcesLI() { 10382 // Try enumerating all code paths before deleting 10383 List<String> allCodePaths = Collections.EMPTY_LIST; 10384 if (codeFile != null && codeFile.exists()) { 10385 try { 10386 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10387 allCodePaths = pkg.getAllCodePaths(); 10388 } catch (PackageParserException e) { 10389 // Ignored; we tried our best 10390 } 10391 } 10392 10393 cleanUp(); 10394 removeDexFiles(allCodePaths, instructionSets); 10395 } 10396 10397 boolean doPostDeleteLI(boolean delete) { 10398 // XXX err, shouldn't we respect the delete flag? 10399 cleanUpResourcesLI(); 10400 return true; 10401 } 10402 } 10403 10404 private boolean isAsecExternal(String cid) { 10405 final String asecPath = PackageHelper.getSdFilesystem(cid); 10406 return !asecPath.startsWith(mAsecInternalPath); 10407 } 10408 10409 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10410 PackageManagerException { 10411 if (copyRet < 0) { 10412 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10413 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10414 throw new PackageManagerException(copyRet, message); 10415 } 10416 } 10417 } 10418 10419 /** 10420 * Extract the MountService "container ID" from the full code path of an 10421 * .apk. 10422 */ 10423 static String cidFromCodePath(String fullCodePath) { 10424 int eidx = fullCodePath.lastIndexOf("/"); 10425 String subStr1 = fullCodePath.substring(0, eidx); 10426 int sidx = subStr1.lastIndexOf("/"); 10427 return subStr1.substring(sidx+1, eidx); 10428 } 10429 10430 /** 10431 * Logic to handle installation of ASEC applications, including copying and 10432 * renaming logic. 10433 */ 10434 class AsecInstallArgs extends InstallArgs { 10435 static final String RES_FILE_NAME = "pkg.apk"; 10436 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10437 10438 String cid; 10439 String packagePath; 10440 String resourcePath; 10441 10442 /** New install */ 10443 AsecInstallArgs(InstallParams params) { 10444 super(params.origin, params.move, params.observer, params.installFlags, 10445 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10446 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10447 } 10448 10449 /** Existing install */ 10450 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10451 boolean isExternal, boolean isForwardLocked) { 10452 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10453 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10454 instructionSets, null); 10455 // Hackily pretend we're still looking at a full code path 10456 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10457 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10458 } 10459 10460 // Extract cid from fullCodePath 10461 int eidx = fullCodePath.lastIndexOf("/"); 10462 String subStr1 = fullCodePath.substring(0, eidx); 10463 int sidx = subStr1.lastIndexOf("/"); 10464 cid = subStr1.substring(sidx+1, eidx); 10465 setMountPath(subStr1); 10466 } 10467 10468 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10469 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10470 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10471 instructionSets, null); 10472 this.cid = cid; 10473 setMountPath(PackageHelper.getSdDir(cid)); 10474 } 10475 10476 void createCopyFile() { 10477 cid = mInstallerService.allocateExternalStageCidLegacy(); 10478 } 10479 10480 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10481 if (origin.staged) { 10482 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10483 cid = origin.cid; 10484 setMountPath(PackageHelper.getSdDir(cid)); 10485 return PackageManager.INSTALL_SUCCEEDED; 10486 } 10487 10488 if (temp) { 10489 createCopyFile(); 10490 } else { 10491 /* 10492 * Pre-emptively destroy the container since it's destroyed if 10493 * copying fails due to it existing anyway. 10494 */ 10495 PackageHelper.destroySdDir(cid); 10496 } 10497 10498 final String newMountPath = imcs.copyPackageToContainer( 10499 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10500 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10501 10502 if (newMountPath != null) { 10503 setMountPath(newMountPath); 10504 return PackageManager.INSTALL_SUCCEEDED; 10505 } else { 10506 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10507 } 10508 } 10509 10510 @Override 10511 String getCodePath() { 10512 return packagePath; 10513 } 10514 10515 @Override 10516 String getResourcePath() { 10517 return resourcePath; 10518 } 10519 10520 int doPreInstall(int status) { 10521 if (status != PackageManager.INSTALL_SUCCEEDED) { 10522 // Destroy container 10523 PackageHelper.destroySdDir(cid); 10524 } else { 10525 boolean mounted = PackageHelper.isContainerMounted(cid); 10526 if (!mounted) { 10527 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10528 Process.SYSTEM_UID); 10529 if (newMountPath != null) { 10530 setMountPath(newMountPath); 10531 } else { 10532 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10533 } 10534 } 10535 } 10536 return status; 10537 } 10538 10539 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10540 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10541 String newMountPath = null; 10542 if (PackageHelper.isContainerMounted(cid)) { 10543 // Unmount the container 10544 if (!PackageHelper.unMountSdDir(cid)) { 10545 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10546 return false; 10547 } 10548 } 10549 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10550 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10551 " which might be stale. Will try to clean up."); 10552 // Clean up the stale container and proceed to recreate. 10553 if (!PackageHelper.destroySdDir(newCacheId)) { 10554 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10555 return false; 10556 } 10557 // Successfully cleaned up stale container. Try to rename again. 10558 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10559 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10560 + " inspite of cleaning it up."); 10561 return false; 10562 } 10563 } 10564 if (!PackageHelper.isContainerMounted(newCacheId)) { 10565 Slog.w(TAG, "Mounting container " + newCacheId); 10566 newMountPath = PackageHelper.mountSdDir(newCacheId, 10567 getEncryptKey(), Process.SYSTEM_UID); 10568 } else { 10569 newMountPath = PackageHelper.getSdDir(newCacheId); 10570 } 10571 if (newMountPath == null) { 10572 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10573 return false; 10574 } 10575 Log.i(TAG, "Succesfully renamed " + cid + 10576 " to " + newCacheId + 10577 " at new path: " + newMountPath); 10578 cid = newCacheId; 10579 10580 final File beforeCodeFile = new File(packagePath); 10581 setMountPath(newMountPath); 10582 final File afterCodeFile = new File(packagePath); 10583 10584 // Reflect the rename in scanned details 10585 pkg.codePath = afterCodeFile.getAbsolutePath(); 10586 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10587 pkg.baseCodePath); 10588 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10589 pkg.splitCodePaths); 10590 10591 // Reflect the rename in app info 10592 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10593 pkg.applicationInfo.setCodePath(pkg.codePath); 10594 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10595 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10596 pkg.applicationInfo.setResourcePath(pkg.codePath); 10597 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10598 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10599 10600 return true; 10601 } 10602 10603 private void setMountPath(String mountPath) { 10604 final File mountFile = new File(mountPath); 10605 10606 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10607 if (monolithicFile.exists()) { 10608 packagePath = monolithicFile.getAbsolutePath(); 10609 if (isFwdLocked()) { 10610 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10611 } else { 10612 resourcePath = packagePath; 10613 } 10614 } else { 10615 packagePath = mountFile.getAbsolutePath(); 10616 resourcePath = packagePath; 10617 } 10618 } 10619 10620 int doPostInstall(int status, int uid) { 10621 if (status != PackageManager.INSTALL_SUCCEEDED) { 10622 cleanUp(); 10623 } else { 10624 final int groupOwner; 10625 final String protectedFile; 10626 if (isFwdLocked()) { 10627 groupOwner = UserHandle.getSharedAppGid(uid); 10628 protectedFile = RES_FILE_NAME; 10629 } else { 10630 groupOwner = -1; 10631 protectedFile = null; 10632 } 10633 10634 if (uid < Process.FIRST_APPLICATION_UID 10635 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10636 Slog.e(TAG, "Failed to finalize " + cid); 10637 PackageHelper.destroySdDir(cid); 10638 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10639 } 10640 10641 boolean mounted = PackageHelper.isContainerMounted(cid); 10642 if (!mounted) { 10643 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10644 } 10645 } 10646 return status; 10647 } 10648 10649 private void cleanUp() { 10650 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10651 10652 // Destroy secure container 10653 PackageHelper.destroySdDir(cid); 10654 } 10655 10656 private List<String> getAllCodePaths() { 10657 final File codeFile = new File(getCodePath()); 10658 if (codeFile != null && codeFile.exists()) { 10659 try { 10660 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10661 return pkg.getAllCodePaths(); 10662 } catch (PackageParserException e) { 10663 // Ignored; we tried our best 10664 } 10665 } 10666 return Collections.EMPTY_LIST; 10667 } 10668 10669 void cleanUpResourcesLI() { 10670 // Enumerate all code paths before deleting 10671 cleanUpResourcesLI(getAllCodePaths()); 10672 } 10673 10674 private void cleanUpResourcesLI(List<String> allCodePaths) { 10675 cleanUp(); 10676 removeDexFiles(allCodePaths, instructionSets); 10677 } 10678 10679 String getPackageName() { 10680 return getAsecPackageName(cid); 10681 } 10682 10683 boolean doPostDeleteLI(boolean delete) { 10684 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10685 final List<String> allCodePaths = getAllCodePaths(); 10686 boolean mounted = PackageHelper.isContainerMounted(cid); 10687 if (mounted) { 10688 // Unmount first 10689 if (PackageHelper.unMountSdDir(cid)) { 10690 mounted = false; 10691 } 10692 } 10693 if (!mounted && delete) { 10694 cleanUpResourcesLI(allCodePaths); 10695 } 10696 return !mounted; 10697 } 10698 10699 @Override 10700 int doPreCopy() { 10701 if (isFwdLocked()) { 10702 if (!PackageHelper.fixSdPermissions(cid, 10703 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10704 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10705 } 10706 } 10707 10708 return PackageManager.INSTALL_SUCCEEDED; 10709 } 10710 10711 @Override 10712 int doPostCopy(int uid) { 10713 if (isFwdLocked()) { 10714 if (uid < Process.FIRST_APPLICATION_UID 10715 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10716 RES_FILE_NAME)) { 10717 Slog.e(TAG, "Failed to finalize " + cid); 10718 PackageHelper.destroySdDir(cid); 10719 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10720 } 10721 } 10722 10723 return PackageManager.INSTALL_SUCCEEDED; 10724 } 10725 } 10726 10727 /** 10728 * Logic to handle movement of existing installed applications. 10729 */ 10730 class MoveInstallArgs extends InstallArgs { 10731 private File codeFile; 10732 private File resourceFile; 10733 10734 /** New install */ 10735 MoveInstallArgs(InstallParams params) { 10736 super(params.origin, params.move, params.observer, params.installFlags, 10737 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10738 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10739 } 10740 10741 int copyApk(IMediaContainerService imcs, boolean temp) { 10742 Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to " 10743 + move.toUuid); 10744 synchronized (mInstaller) { 10745 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10746 move.dataAppName, move.appId, move.seinfo) != 0) { 10747 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10748 } 10749 } 10750 10751 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10752 resourceFile = codeFile; 10753 Slog.d(TAG, "codeFile after move is " + codeFile); 10754 10755 return PackageManager.INSTALL_SUCCEEDED; 10756 } 10757 10758 int doPreInstall(int status) { 10759 if (status != PackageManager.INSTALL_SUCCEEDED) { 10760 cleanUp(); 10761 } 10762 return status; 10763 } 10764 10765 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10766 if (status != PackageManager.INSTALL_SUCCEEDED) { 10767 cleanUp(); 10768 return false; 10769 } 10770 10771 // Reflect the move in app info 10772 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10773 pkg.applicationInfo.setCodePath(pkg.codePath); 10774 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10775 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10776 pkg.applicationInfo.setResourcePath(pkg.codePath); 10777 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10778 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10779 10780 return true; 10781 } 10782 10783 int doPostInstall(int status, int uid) { 10784 if (status != PackageManager.INSTALL_SUCCEEDED) { 10785 cleanUp(); 10786 } 10787 return status; 10788 } 10789 10790 @Override 10791 String getCodePath() { 10792 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10793 } 10794 10795 @Override 10796 String getResourcePath() { 10797 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10798 } 10799 10800 private boolean cleanUp() { 10801 if (codeFile == null || !codeFile.exists()) { 10802 return false; 10803 } 10804 10805 if (codeFile.isDirectory()) { 10806 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10807 } else { 10808 codeFile.delete(); 10809 } 10810 10811 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10812 resourceFile.delete(); 10813 } 10814 10815 return true; 10816 } 10817 10818 void cleanUpResourcesLI() { 10819 cleanUp(); 10820 } 10821 10822 boolean doPostDeleteLI(boolean delete) { 10823 // XXX err, shouldn't we respect the delete flag? 10824 cleanUpResourcesLI(); 10825 return true; 10826 } 10827 } 10828 10829 static String getAsecPackageName(String packageCid) { 10830 int idx = packageCid.lastIndexOf("-"); 10831 if (idx == -1) { 10832 return packageCid; 10833 } 10834 return packageCid.substring(0, idx); 10835 } 10836 10837 // Utility method used to create code paths based on package name and available index. 10838 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10839 String idxStr = ""; 10840 int idx = 1; 10841 // Fall back to default value of idx=1 if prefix is not 10842 // part of oldCodePath 10843 if (oldCodePath != null) { 10844 String subStr = oldCodePath; 10845 // Drop the suffix right away 10846 if (suffix != null && subStr.endsWith(suffix)) { 10847 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10848 } 10849 // If oldCodePath already contains prefix find out the 10850 // ending index to either increment or decrement. 10851 int sidx = subStr.lastIndexOf(prefix); 10852 if (sidx != -1) { 10853 subStr = subStr.substring(sidx + prefix.length()); 10854 if (subStr != null) { 10855 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10856 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10857 } 10858 try { 10859 idx = Integer.parseInt(subStr); 10860 if (idx <= 1) { 10861 idx++; 10862 } else { 10863 idx--; 10864 } 10865 } catch(NumberFormatException e) { 10866 } 10867 } 10868 } 10869 } 10870 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10871 return prefix + idxStr; 10872 } 10873 10874 private File getNextCodePath(File targetDir, String packageName) { 10875 int suffix = 1; 10876 File result; 10877 do { 10878 result = new File(targetDir, packageName + "-" + suffix); 10879 suffix++; 10880 } while (result.exists()); 10881 return result; 10882 } 10883 10884 // Utility method that returns the relative package path with respect 10885 // to the installation directory. Like say for /data/data/com.test-1.apk 10886 // string com.test-1 is returned. 10887 static String deriveCodePathName(String codePath) { 10888 if (codePath == null) { 10889 return null; 10890 } 10891 final File codeFile = new File(codePath); 10892 final String name = codeFile.getName(); 10893 if (codeFile.isDirectory()) { 10894 return name; 10895 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10896 final int lastDot = name.lastIndexOf('.'); 10897 return name.substring(0, lastDot); 10898 } else { 10899 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10900 return null; 10901 } 10902 } 10903 10904 class PackageInstalledInfo { 10905 String name; 10906 int uid; 10907 // The set of users that originally had this package installed. 10908 int[] origUsers; 10909 // The set of users that now have this package installed. 10910 int[] newUsers; 10911 PackageParser.Package pkg; 10912 int returnCode; 10913 String returnMsg; 10914 PackageRemovedInfo removedInfo; 10915 10916 public void setError(int code, String msg) { 10917 returnCode = code; 10918 returnMsg = msg; 10919 Slog.w(TAG, msg); 10920 } 10921 10922 public void setError(String msg, PackageParserException e) { 10923 returnCode = e.error; 10924 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10925 Slog.w(TAG, msg, e); 10926 } 10927 10928 public void setError(String msg, PackageManagerException e) { 10929 returnCode = e.error; 10930 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10931 Slog.w(TAG, msg, e); 10932 } 10933 10934 // In some error cases we want to convey more info back to the observer 10935 String origPackage; 10936 String origPermission; 10937 } 10938 10939 /* 10940 * Install a non-existing package. 10941 */ 10942 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 10943 UserHandle user, String installerPackageName, String volumeUuid, 10944 PackageInstalledInfo res) { 10945 // Remember this for later, in case we need to rollback this install 10946 String pkgName = pkg.packageName; 10947 10948 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10949 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 10950 UserHandle.USER_OWNER).exists(); 10951 synchronized(mPackages) { 10952 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10953 // A package with the same name is already installed, though 10954 // it has been renamed to an older name. The package we 10955 // are trying to install should be installed as an update to 10956 // the existing one, but that has not been requested, so bail. 10957 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10958 + " without first uninstalling package running as " 10959 + mSettings.mRenamedPackages.get(pkgName)); 10960 return; 10961 } 10962 if (mPackages.containsKey(pkgName)) { 10963 // Don't allow installation over an existing package with the same name. 10964 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10965 + " without first uninstalling."); 10966 return; 10967 } 10968 } 10969 10970 try { 10971 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10972 System.currentTimeMillis(), user); 10973 10974 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 10975 // delete the partially installed application. the data directory will have to be 10976 // restored if it was already existing 10977 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10978 // remove package from internal structures. Note that we want deletePackageX to 10979 // delete the package data and cache directories that it created in 10980 // scanPackageLocked, unless those directories existed before we even tried to 10981 // install. 10982 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10983 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10984 res.removedInfo, true); 10985 } 10986 10987 } catch (PackageManagerException e) { 10988 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10989 } 10990 } 10991 10992 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10993 // Upgrade keysets are being used. Determine if new package has a superset of the 10994 // required keys. 10995 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10996 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10997 for (int i = 0; i < upgradeKeySets.length; i++) { 10998 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10999 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11000 return true; 11001 } 11002 } 11003 return false; 11004 } 11005 11006 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11007 UserHandle user, String installerPackageName, String volumeUuid, 11008 PackageInstalledInfo res) { 11009 final PackageParser.Package oldPackage; 11010 final String pkgName = pkg.packageName; 11011 final int[] allUsers; 11012 final boolean[] perUserInstalled; 11013 final boolean weFroze; 11014 11015 // First find the old package info and check signatures 11016 synchronized(mPackages) { 11017 oldPackage = mPackages.get(pkgName); 11018 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11019 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11020 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11021 // default to original signature matching 11022 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11023 != PackageManager.SIGNATURE_MATCH) { 11024 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11025 "New package has a different signature: " + pkgName); 11026 return; 11027 } 11028 } else { 11029 if(!checkUpgradeKeySetLP(ps, pkg)) { 11030 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11031 "New package not signed by keys specified by upgrade-keysets: " 11032 + pkgName); 11033 return; 11034 } 11035 } 11036 11037 // In case of rollback, remember per-user/profile install state 11038 allUsers = sUserManager.getUserIds(); 11039 perUserInstalled = new boolean[allUsers.length]; 11040 for (int i = 0; i < allUsers.length; i++) { 11041 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11042 } 11043 11044 // Mark the app as frozen to prevent launching during the upgrade 11045 // process, and then kill all running instances 11046 if (!ps.frozen) { 11047 ps.frozen = true; 11048 weFroze = true; 11049 } else { 11050 weFroze = false; 11051 } 11052 } 11053 11054 // Now that we're guarded by frozen state, kill app during upgrade 11055 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11056 11057 try { 11058 boolean sysPkg = (isSystemApp(oldPackage)); 11059 if (sysPkg) { 11060 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11061 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11062 } else { 11063 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11064 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11065 } 11066 } finally { 11067 // Regardless of success or failure of upgrade steps above, always 11068 // unfreeze the package if we froze it 11069 if (weFroze) { 11070 unfreezePackage(pkgName); 11071 } 11072 } 11073 } 11074 11075 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11076 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11077 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11078 String volumeUuid, PackageInstalledInfo res) { 11079 String pkgName = deletedPackage.packageName; 11080 boolean deletedPkg = true; 11081 boolean updatedSettings = false; 11082 11083 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11084 + deletedPackage); 11085 long origUpdateTime; 11086 if (pkg.mExtras != null) { 11087 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11088 } else { 11089 origUpdateTime = 0; 11090 } 11091 11092 // First delete the existing package while retaining the data directory 11093 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11094 res.removedInfo, true)) { 11095 // If the existing package wasn't successfully deleted 11096 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11097 deletedPkg = false; 11098 } else { 11099 // Successfully deleted the old package; proceed with replace. 11100 11101 // If deleted package lived in a container, give users a chance to 11102 // relinquish resources before killing. 11103 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11104 if (DEBUG_INSTALL) { 11105 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11106 } 11107 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11108 final ArrayList<String> pkgList = new ArrayList<String>(1); 11109 pkgList.add(deletedPackage.applicationInfo.packageName); 11110 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11111 } 11112 11113 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11114 try { 11115 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11116 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11117 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11118 perUserInstalled, res, user); 11119 updatedSettings = true; 11120 } catch (PackageManagerException e) { 11121 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11122 } 11123 } 11124 11125 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11126 // remove package from internal structures. Note that we want deletePackageX to 11127 // delete the package data and cache directories that it created in 11128 // scanPackageLocked, unless those directories existed before we even tried to 11129 // install. 11130 if(updatedSettings) { 11131 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11132 deletePackageLI( 11133 pkgName, null, true, allUsers, perUserInstalled, 11134 PackageManager.DELETE_KEEP_DATA, 11135 res.removedInfo, true); 11136 } 11137 // Since we failed to install the new package we need to restore the old 11138 // package that we deleted. 11139 if (deletedPkg) { 11140 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11141 File restoreFile = new File(deletedPackage.codePath); 11142 // Parse old package 11143 boolean oldExternal = isExternal(deletedPackage); 11144 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11145 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11146 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11147 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11148 try { 11149 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11150 } catch (PackageManagerException e) { 11151 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11152 + e.getMessage()); 11153 return; 11154 } 11155 // Restore of old package succeeded. Update permissions. 11156 // writer 11157 synchronized (mPackages) { 11158 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11159 UPDATE_PERMISSIONS_ALL); 11160 // can downgrade to reader 11161 mSettings.writeLPr(); 11162 } 11163 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11164 } 11165 } 11166 } 11167 11168 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11169 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11170 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11171 String volumeUuid, PackageInstalledInfo res) { 11172 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11173 + ", old=" + deletedPackage); 11174 boolean disabledSystem = false; 11175 boolean updatedSettings = false; 11176 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11177 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11178 != 0) { 11179 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11180 } 11181 String packageName = deletedPackage.packageName; 11182 if (packageName == null) { 11183 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11184 "Attempt to delete null packageName."); 11185 return; 11186 } 11187 PackageParser.Package oldPkg; 11188 PackageSetting oldPkgSetting; 11189 // reader 11190 synchronized (mPackages) { 11191 oldPkg = mPackages.get(packageName); 11192 oldPkgSetting = mSettings.mPackages.get(packageName); 11193 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11194 (oldPkgSetting == null)) { 11195 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11196 "Couldn't find package:" + packageName + " information"); 11197 return; 11198 } 11199 } 11200 11201 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11202 res.removedInfo.removedPackage = packageName; 11203 // Remove existing system package 11204 removePackageLI(oldPkgSetting, true); 11205 // writer 11206 synchronized (mPackages) { 11207 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11208 if (!disabledSystem && deletedPackage != null) { 11209 // We didn't need to disable the .apk as a current system package, 11210 // which means we are replacing another update that is already 11211 // installed. We need to make sure to delete the older one's .apk. 11212 res.removedInfo.args = createInstallArgsForExisting(0, 11213 deletedPackage.applicationInfo.getCodePath(), 11214 deletedPackage.applicationInfo.getResourcePath(), 11215 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11216 } else { 11217 res.removedInfo.args = null; 11218 } 11219 } 11220 11221 // Successfully disabled the old package. Now proceed with re-installation 11222 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11223 11224 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11225 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11226 11227 PackageParser.Package newPackage = null; 11228 try { 11229 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11230 if (newPackage.mExtras != null) { 11231 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11232 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11233 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11234 11235 // is the update attempting to change shared user? that isn't going to work... 11236 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11237 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11238 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11239 + " to " + newPkgSetting.sharedUser); 11240 updatedSettings = true; 11241 } 11242 } 11243 11244 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11245 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11246 perUserInstalled, res, user); 11247 updatedSettings = true; 11248 } 11249 11250 } catch (PackageManagerException e) { 11251 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11252 } 11253 11254 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11255 // Re installation failed. Restore old information 11256 // Remove new pkg information 11257 if (newPackage != null) { 11258 removeInstalledPackageLI(newPackage, true); 11259 } 11260 // Add back the old system package 11261 try { 11262 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11263 } catch (PackageManagerException e) { 11264 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11265 } 11266 // Restore the old system information in Settings 11267 synchronized (mPackages) { 11268 if (disabledSystem) { 11269 mSettings.enableSystemPackageLPw(packageName); 11270 } 11271 if (updatedSettings) { 11272 mSettings.setInstallerPackageName(packageName, 11273 oldPkgSetting.installerPackageName); 11274 } 11275 mSettings.writeLPr(); 11276 } 11277 } 11278 } 11279 11280 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11281 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11282 UserHandle user) { 11283 String pkgName = newPackage.packageName; 11284 synchronized (mPackages) { 11285 //write settings. the installStatus will be incomplete at this stage. 11286 //note that the new package setting would have already been 11287 //added to mPackages. It hasn't been persisted yet. 11288 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11289 mSettings.writeLPr(); 11290 } 11291 11292 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11293 11294 synchronized (mPackages) { 11295 updatePermissionsLPw(newPackage.packageName, newPackage, 11296 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11297 ? UPDATE_PERMISSIONS_ALL : 0)); 11298 // For system-bundled packages, we assume that installing an upgraded version 11299 // of the package implies that the user actually wants to run that new code, 11300 // so we enable the package. 11301 PackageSetting ps = mSettings.mPackages.get(pkgName); 11302 if (ps != null) { 11303 if (isSystemApp(newPackage)) { 11304 // NB: implicit assumption that system package upgrades apply to all users 11305 if (DEBUG_INSTALL) { 11306 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11307 } 11308 if (res.origUsers != null) { 11309 for (int userHandle : res.origUsers) { 11310 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11311 userHandle, installerPackageName); 11312 } 11313 } 11314 // Also convey the prior install/uninstall state 11315 if (allUsers != null && perUserInstalled != null) { 11316 for (int i = 0; i < allUsers.length; i++) { 11317 if (DEBUG_INSTALL) { 11318 Slog.d(TAG, " user " + allUsers[i] 11319 + " => " + perUserInstalled[i]); 11320 } 11321 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11322 } 11323 // these install state changes will be persisted in the 11324 // upcoming call to mSettings.writeLPr(). 11325 } 11326 } 11327 // It's implied that when a user requests installation, they want the app to be 11328 // installed and enabled. 11329 int userId = user.getIdentifier(); 11330 if (userId != UserHandle.USER_ALL) { 11331 ps.setInstalled(true, userId); 11332 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11333 } 11334 } 11335 res.name = pkgName; 11336 res.uid = newPackage.applicationInfo.uid; 11337 res.pkg = newPackage; 11338 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11339 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11340 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11341 //to update install status 11342 mSettings.writeLPr(); 11343 } 11344 } 11345 11346 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11347 final int installFlags = args.installFlags; 11348 final String installerPackageName = args.installerPackageName; 11349 final String volumeUuid = args.volumeUuid; 11350 final File tmpPackageFile = new File(args.getCodePath()); 11351 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11352 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11353 || (args.volumeUuid != null)); 11354 boolean replace = false; 11355 int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 11356 // Result object to be returned 11357 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11358 11359 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11360 // Retrieve PackageSettings and parse package 11361 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11362 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11363 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11364 PackageParser pp = new PackageParser(); 11365 pp.setSeparateProcesses(mSeparateProcesses); 11366 pp.setDisplayMetrics(mMetrics); 11367 11368 final PackageParser.Package pkg; 11369 try { 11370 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11371 } catch (PackageParserException e) { 11372 res.setError("Failed parse during installPackageLI", e); 11373 return; 11374 } 11375 11376 // Mark that we have an install time CPU ABI override. 11377 pkg.cpuAbiOverride = args.abiOverride; 11378 11379 String pkgName = res.name = pkg.packageName; 11380 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11381 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11382 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11383 return; 11384 } 11385 } 11386 11387 try { 11388 pp.collectCertificates(pkg, parseFlags); 11389 pp.collectManifestDigest(pkg); 11390 } catch (PackageParserException e) { 11391 res.setError("Failed collect during installPackageLI", e); 11392 return; 11393 } 11394 11395 /* If the installer passed in a manifest digest, compare it now. */ 11396 if (args.manifestDigest != null) { 11397 if (DEBUG_INSTALL) { 11398 final String parsedManifest = pkg.manifestDigest == null ? "null" 11399 : pkg.manifestDigest.toString(); 11400 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11401 + parsedManifest); 11402 } 11403 11404 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11405 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11406 return; 11407 } 11408 } else if (DEBUG_INSTALL) { 11409 final String parsedManifest = pkg.manifestDigest == null 11410 ? "null" : pkg.manifestDigest.toString(); 11411 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11412 } 11413 11414 // Get rid of all references to package scan path via parser. 11415 pp = null; 11416 String oldCodePath = null; 11417 boolean systemApp = false; 11418 synchronized (mPackages) { 11419 // Check if installing already existing package 11420 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11421 String oldName = mSettings.mRenamedPackages.get(pkgName); 11422 if (pkg.mOriginalPackages != null 11423 && pkg.mOriginalPackages.contains(oldName) 11424 && mPackages.containsKey(oldName)) { 11425 // This package is derived from an original package, 11426 // and this device has been updating from that original 11427 // name. We must continue using the original name, so 11428 // rename the new package here. 11429 pkg.setPackageName(oldName); 11430 pkgName = pkg.packageName; 11431 replace = true; 11432 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11433 + oldName + " pkgName=" + pkgName); 11434 } else if (mPackages.containsKey(pkgName)) { 11435 // This package, under its official name, already exists 11436 // on the device; we should replace it. 11437 replace = true; 11438 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11439 } 11440 } 11441 11442 PackageSetting ps = mSettings.mPackages.get(pkgName); 11443 if (ps != null) { 11444 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11445 11446 // Quick sanity check that we're signed correctly if updating; 11447 // we'll check this again later when scanning, but we want to 11448 // bail early here before tripping over redefined permissions. 11449 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11450 try { 11451 verifySignaturesLP(ps, pkg); 11452 } catch (PackageManagerException e) { 11453 res.setError(e.error, e.getMessage()); 11454 return; 11455 } 11456 } else { 11457 if (!checkUpgradeKeySetLP(ps, pkg)) { 11458 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11459 + pkg.packageName + " upgrade keys do not match the " 11460 + "previously installed version"); 11461 return; 11462 } 11463 } 11464 11465 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11466 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11467 systemApp = (ps.pkg.applicationInfo.flags & 11468 ApplicationInfo.FLAG_SYSTEM) != 0; 11469 } 11470 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11471 } 11472 11473 // Check whether the newly-scanned package wants to define an already-defined perm 11474 int N = pkg.permissions.size(); 11475 for (int i = N-1; i >= 0; i--) { 11476 PackageParser.Permission perm = pkg.permissions.get(i); 11477 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11478 if (bp != null) { 11479 // If the defining package is signed with our cert, it's okay. This 11480 // also includes the "updating the same package" case, of course. 11481 // "updating same package" could also involve key-rotation. 11482 final boolean sigsOk; 11483 if (!bp.sourcePackage.equals(pkg.packageName) 11484 || !(bp.packageSetting instanceof PackageSetting) 11485 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11486 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11487 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11488 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11489 } else { 11490 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11491 } 11492 if (!sigsOk) { 11493 // If the owning package is the system itself, we log but allow 11494 // install to proceed; we fail the install on all other permission 11495 // redefinitions. 11496 if (!bp.sourcePackage.equals("android")) { 11497 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11498 + pkg.packageName + " attempting to redeclare permission " 11499 + perm.info.name + " already owned by " + bp.sourcePackage); 11500 res.origPermission = perm.info.name; 11501 res.origPackage = bp.sourcePackage; 11502 return; 11503 } else { 11504 Slog.w(TAG, "Package " + pkg.packageName 11505 + " attempting to redeclare system permission " 11506 + perm.info.name + "; ignoring new declaration"); 11507 pkg.permissions.remove(i); 11508 } 11509 } 11510 } 11511 } 11512 11513 } 11514 11515 if (systemApp && onExternal) { 11516 // Disable updates to system apps on sdcard 11517 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11518 "Cannot install updates to system apps on sdcard"); 11519 return; 11520 } 11521 11522 if (args.move != null) { 11523 // We did an in-place move, so dex is ready to roll 11524 scanFlags |= SCAN_NO_DEX; 11525 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11526 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11527 scanFlags |= SCAN_NO_DEX; 11528 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11529 int result = mPackageDexOptimizer 11530 .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */, 11531 false /* defer */, false /* inclDependencies */); 11532 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11533 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11534 return; 11535 } 11536 } 11537 11538 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11539 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11540 return; 11541 } 11542 11543 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11544 11545 if (replace) { 11546 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11547 installerPackageName, volumeUuid, res); 11548 } else { 11549 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11550 args.user, installerPackageName, volumeUuid, res); 11551 } 11552 synchronized (mPackages) { 11553 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11554 if (ps != null) { 11555 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11556 } 11557 } 11558 } 11559 11560 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11561 if (mIntentFilterVerifierComponent == null) { 11562 Slog.d(TAG, "No IntentFilter verification will not be done as " 11563 + "there is no IntentFilterVerifier available!"); 11564 return; 11565 } 11566 11567 final int verifierUid = getPackageUid( 11568 mIntentFilterVerifierComponent.getPackageName(), 11569 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11570 11571 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11572 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11573 msg.obj = pkg; 11574 msg.arg1 = userId; 11575 msg.arg2 = verifierUid; 11576 11577 mHandler.sendMessage(msg); 11578 } 11579 11580 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11581 PackageParser.Package pkg) { 11582 int size = pkg.activities.size(); 11583 if (size == 0) { 11584 Slog.d(TAG, "No activity, so no need to verify any IntentFilter!"); 11585 return; 11586 } 11587 11588 final boolean hasDomainURLs = hasDomainURLs(pkg); 11589 if (!hasDomainURLs) { 11590 Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!"); 11591 return; 11592 } 11593 11594 Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size 11595 + " Activities needs verification ..."); 11596 11597 final int verificationId = mIntentFilterVerificationToken++; 11598 int count = 0; 11599 final String packageName = pkg.packageName; 11600 ArrayList<String> allHosts = new ArrayList<>(); 11601 11602 synchronized (mPackages) { 11603 for (PackageParser.Activity a : pkg.activities) { 11604 for (ActivityIntentInfo filter : a.intents) { 11605 boolean needsFilterVerification = filter.needsVerification(); 11606 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11607 Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString()); 11608 mIntentFilterVerifier.addOneIntentFilterVerification( 11609 verifierUid, userId, verificationId, filter, packageName); 11610 count++; 11611 } else if (!needsFilterVerification) { 11612 Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString()); 11613 if (hasValidDomains(filter)) { 11614 ArrayList<String> hosts = filter.getHostsList(); 11615 if (hosts.size() > 0) { 11616 allHosts.addAll(hosts); 11617 } else { 11618 if (allHosts.isEmpty()) { 11619 allHosts.add("*"); 11620 } 11621 } 11622 } 11623 } else { 11624 Slog.d(TAG, "Verification already done for IntentFilter:" 11625 + filter.toString()); 11626 } 11627 } 11628 } 11629 } 11630 11631 if (count > 0) { 11632 mIntentFilterVerifier.startVerifications(userId); 11633 Slog.d(TAG, "Started " + count + " IntentFilter verification" 11634 + (count > 1 ? "s" : "") + " for userId:" + userId + "!"); 11635 } else { 11636 Slog.d(TAG, "No need to start any IntentFilter verification!"); 11637 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11638 packageName, allHosts) != null) { 11639 scheduleWriteSettingsLocked(); 11640 } 11641 } 11642 } 11643 11644 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11645 final ComponentName cn = filter.activity.getComponentName(); 11646 final String packageName = cn.getPackageName(); 11647 11648 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11649 packageName); 11650 if (ivi == null) { 11651 return true; 11652 } 11653 int status = ivi.getStatus(); 11654 switch (status) { 11655 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11656 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11657 return true; 11658 11659 default: 11660 // Nothing to do 11661 return false; 11662 } 11663 } 11664 11665 private static boolean isMultiArch(PackageSetting ps) { 11666 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11667 } 11668 11669 private static boolean isMultiArch(ApplicationInfo info) { 11670 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11671 } 11672 11673 private static boolean isExternal(PackageParser.Package pkg) { 11674 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11675 } 11676 11677 private static boolean isExternal(PackageSetting ps) { 11678 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11679 } 11680 11681 private static boolean isExternal(ApplicationInfo info) { 11682 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11683 } 11684 11685 private static boolean isSystemApp(PackageParser.Package pkg) { 11686 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11687 } 11688 11689 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11690 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11691 } 11692 11693 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11694 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11695 } 11696 11697 private static boolean isSystemApp(PackageSetting ps) { 11698 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11699 } 11700 11701 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11702 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11703 } 11704 11705 private int packageFlagsToInstallFlags(PackageSetting ps) { 11706 int installFlags = 0; 11707 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11708 // This existing package was an external ASEC install when we have 11709 // the external flag without a UUID 11710 installFlags |= PackageManager.INSTALL_EXTERNAL; 11711 } 11712 if (ps.isForwardLocked()) { 11713 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11714 } 11715 return installFlags; 11716 } 11717 11718 private void deleteTempPackageFiles() { 11719 final FilenameFilter filter = new FilenameFilter() { 11720 public boolean accept(File dir, String name) { 11721 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11722 } 11723 }; 11724 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11725 file.delete(); 11726 } 11727 } 11728 11729 @Override 11730 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11731 int flags) { 11732 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11733 flags); 11734 } 11735 11736 @Override 11737 public void deletePackage(final String packageName, 11738 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11739 mContext.enforceCallingOrSelfPermission( 11740 android.Manifest.permission.DELETE_PACKAGES, null); 11741 final int uid = Binder.getCallingUid(); 11742 if (UserHandle.getUserId(uid) != userId) { 11743 mContext.enforceCallingPermission( 11744 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11745 "deletePackage for user " + userId); 11746 } 11747 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11748 try { 11749 observer.onPackageDeleted(packageName, 11750 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11751 } catch (RemoteException re) { 11752 } 11753 return; 11754 } 11755 11756 boolean uninstallBlocked = false; 11757 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11758 int[] users = sUserManager.getUserIds(); 11759 for (int i = 0; i < users.length; ++i) { 11760 if (getBlockUninstallForUser(packageName, users[i])) { 11761 uninstallBlocked = true; 11762 break; 11763 } 11764 } 11765 } else { 11766 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11767 } 11768 if (uninstallBlocked) { 11769 try { 11770 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11771 null); 11772 } catch (RemoteException re) { 11773 } 11774 return; 11775 } 11776 11777 if (DEBUG_REMOVE) { 11778 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11779 } 11780 // Queue up an async operation since the package deletion may take a little while. 11781 mHandler.post(new Runnable() { 11782 public void run() { 11783 mHandler.removeCallbacks(this); 11784 final int returnCode = deletePackageX(packageName, userId, flags); 11785 if (observer != null) { 11786 try { 11787 observer.onPackageDeleted(packageName, returnCode, null); 11788 } catch (RemoteException e) { 11789 Log.i(TAG, "Observer no longer exists."); 11790 } //end catch 11791 } //end if 11792 } //end run 11793 }); 11794 } 11795 11796 private boolean isPackageDeviceAdmin(String packageName, int userId) { 11797 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 11798 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 11799 try { 11800 if (dpm != null) { 11801 if (dpm.isDeviceOwner(packageName)) { 11802 return true; 11803 } 11804 int[] users; 11805 if (userId == UserHandle.USER_ALL) { 11806 users = sUserManager.getUserIds(); 11807 } else { 11808 users = new int[]{userId}; 11809 } 11810 for (int i = 0; i < users.length; ++i) { 11811 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 11812 return true; 11813 } 11814 } 11815 } 11816 } catch (RemoteException e) { 11817 } 11818 return false; 11819 } 11820 11821 /** 11822 * This method is an internal method that could be get invoked either 11823 * to delete an installed package or to clean up a failed installation. 11824 * After deleting an installed package, a broadcast is sent to notify any 11825 * listeners that the package has been installed. For cleaning up a failed 11826 * installation, the broadcast is not necessary since the package's 11827 * installation wouldn't have sent the initial broadcast either 11828 * The key steps in deleting a package are 11829 * deleting the package information in internal structures like mPackages, 11830 * deleting the packages base directories through installd 11831 * updating mSettings to reflect current status 11832 * persisting settings for later use 11833 * sending a broadcast if necessary 11834 */ 11835 private int deletePackageX(String packageName, int userId, int flags) { 11836 final PackageRemovedInfo info = new PackageRemovedInfo(); 11837 final boolean res; 11838 11839 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 11840 ? UserHandle.ALL : new UserHandle(userId); 11841 11842 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 11843 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 11844 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 11845 } 11846 11847 boolean removedForAllUsers = false; 11848 boolean systemUpdate = false; 11849 11850 // for the uninstall-updates case and restricted profiles, remember the per- 11851 // userhandle installed state 11852 int[] allUsers; 11853 boolean[] perUserInstalled; 11854 synchronized (mPackages) { 11855 PackageSetting ps = mSettings.mPackages.get(packageName); 11856 allUsers = sUserManager.getUserIds(); 11857 perUserInstalled = new boolean[allUsers.length]; 11858 for (int i = 0; i < allUsers.length; i++) { 11859 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11860 } 11861 } 11862 11863 synchronized (mInstallLock) { 11864 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 11865 res = deletePackageLI(packageName, removeForUser, 11866 true, allUsers, perUserInstalled, 11867 flags | REMOVE_CHATTY, info, true); 11868 systemUpdate = info.isRemovedPackageSystemUpdate; 11869 if (res && !systemUpdate && mPackages.get(packageName) == null) { 11870 removedForAllUsers = true; 11871 } 11872 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 11873 + " removedForAllUsers=" + removedForAllUsers); 11874 } 11875 11876 if (res) { 11877 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 11878 11879 // If the removed package was a system update, the old system package 11880 // was re-enabled; we need to broadcast this information 11881 if (systemUpdate) { 11882 Bundle extras = new Bundle(1); 11883 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 11884 ? info.removedAppId : info.uid); 11885 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11886 11887 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 11888 extras, null, null, null); 11889 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 11890 extras, null, null, null); 11891 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 11892 null, packageName, null, null); 11893 } 11894 } 11895 // Force a gc here. 11896 Runtime.getRuntime().gc(); 11897 // Delete the resources here after sending the broadcast to let 11898 // other processes clean up before deleting resources. 11899 if (info.args != null) { 11900 synchronized (mInstallLock) { 11901 info.args.doPostDeleteLI(true); 11902 } 11903 } 11904 11905 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 11906 } 11907 11908 class PackageRemovedInfo { 11909 String removedPackage; 11910 int uid = -1; 11911 int removedAppId = -1; 11912 int[] removedUsers = null; 11913 boolean isRemovedPackageSystemUpdate = false; 11914 // Clean up resources deleted packages. 11915 InstallArgs args = null; 11916 11917 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11918 Bundle extras = new Bundle(1); 11919 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11920 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11921 if (replacing) { 11922 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11923 } 11924 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11925 if (removedPackage != null) { 11926 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11927 extras, null, null, removedUsers); 11928 if (fullRemove && !replacing) { 11929 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11930 extras, null, null, removedUsers); 11931 } 11932 } 11933 if (removedAppId >= 0) { 11934 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11935 removedUsers); 11936 } 11937 } 11938 } 11939 11940 /* 11941 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11942 * flag is not set, the data directory is removed as well. 11943 * make sure this flag is set for partially installed apps. If not its meaningless to 11944 * delete a partially installed application. 11945 */ 11946 private void removePackageDataLI(PackageSetting ps, 11947 int[] allUserHandles, boolean[] perUserInstalled, 11948 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11949 String packageName = ps.name; 11950 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11951 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11952 // Retrieve object to delete permissions for shared user later on 11953 final PackageSetting deletedPs; 11954 // reader 11955 synchronized (mPackages) { 11956 deletedPs = mSettings.mPackages.get(packageName); 11957 if (outInfo != null) { 11958 outInfo.removedPackage = packageName; 11959 outInfo.removedUsers = deletedPs != null 11960 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11961 : null; 11962 } 11963 } 11964 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11965 removeDataDirsLI(ps.volumeUuid, packageName); 11966 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11967 } 11968 // writer 11969 synchronized (mPackages) { 11970 if (deletedPs != null) { 11971 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11972 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 11973 if (outInfo != null) { 11974 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11975 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11976 } 11977 updatePermissionsLPw(deletedPs.name, null, 0); 11978 if (deletedPs.sharedUser != null) { 11979 // Remove permissions associated with package. Since runtime 11980 // permissions are per user we have to kill the removed package 11981 // or packages running under the shared user of the removed 11982 // package if revoking the permissions requested only by the removed 11983 // package is successful and this causes a change in gids. 11984 for (int userId : UserManagerService.getInstance().getUserIds()) { 11985 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 11986 userId); 11987 if (userIdToKill == UserHandle.USER_ALL 11988 || userIdToKill >= UserHandle.USER_OWNER) { 11989 // If gids changed for this user, kill all affected packages. 11990 mHandler.post(new Runnable() { 11991 @Override 11992 public void run() { 11993 // This has to happen with no lock held. 11994 killSettingPackagesForUser(deletedPs, userIdToKill, 11995 KILL_APP_REASON_GIDS_CHANGED); 11996 } 11997 }); 11998 break; 11999 } 12000 } 12001 } 12002 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12003 } 12004 // make sure to preserve per-user disabled state if this removal was just 12005 // a downgrade of a system app to the factory package 12006 if (allUserHandles != null && perUserInstalled != null) { 12007 if (DEBUG_REMOVE) { 12008 Slog.d(TAG, "Propagating install state across downgrade"); 12009 } 12010 for (int i = 0; i < allUserHandles.length; i++) { 12011 if (DEBUG_REMOVE) { 12012 Slog.d(TAG, " user " + allUserHandles[i] 12013 + " => " + perUserInstalled[i]); 12014 } 12015 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12016 } 12017 } 12018 } 12019 // can downgrade to reader 12020 if (writeSettings) { 12021 // Save settings now 12022 mSettings.writeLPr(); 12023 } 12024 } 12025 if (outInfo != null) { 12026 // A user ID was deleted here. Go through all users and remove it 12027 // from KeyStore. 12028 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12029 } 12030 } 12031 12032 static boolean locationIsPrivileged(File path) { 12033 try { 12034 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12035 .getCanonicalPath(); 12036 return path.getCanonicalPath().startsWith(privilegedAppDir); 12037 } catch (IOException e) { 12038 Slog.e(TAG, "Unable to access code path " + path); 12039 } 12040 return false; 12041 } 12042 12043 /* 12044 * Tries to delete system package. 12045 */ 12046 private boolean deleteSystemPackageLI(PackageSetting newPs, 12047 int[] allUserHandles, boolean[] perUserInstalled, 12048 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12049 final boolean applyUserRestrictions 12050 = (allUserHandles != null) && (perUserInstalled != null); 12051 PackageSetting disabledPs = null; 12052 // Confirm if the system package has been updated 12053 // An updated system app can be deleted. This will also have to restore 12054 // the system pkg from system partition 12055 // reader 12056 synchronized (mPackages) { 12057 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12058 } 12059 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12060 + " disabledPs=" + disabledPs); 12061 if (disabledPs == null) { 12062 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12063 return false; 12064 } else if (DEBUG_REMOVE) { 12065 Slog.d(TAG, "Deleting system pkg from data partition"); 12066 } 12067 if (DEBUG_REMOVE) { 12068 if (applyUserRestrictions) { 12069 Slog.d(TAG, "Remembering install states:"); 12070 for (int i = 0; i < allUserHandles.length; i++) { 12071 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12072 } 12073 } 12074 } 12075 // Delete the updated package 12076 outInfo.isRemovedPackageSystemUpdate = true; 12077 if (disabledPs.versionCode < newPs.versionCode) { 12078 // Delete data for downgrades 12079 flags &= ~PackageManager.DELETE_KEEP_DATA; 12080 } else { 12081 // Preserve data by setting flag 12082 flags |= PackageManager.DELETE_KEEP_DATA; 12083 } 12084 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12085 allUserHandles, perUserInstalled, outInfo, writeSettings); 12086 if (!ret) { 12087 return false; 12088 } 12089 // writer 12090 synchronized (mPackages) { 12091 // Reinstate the old system package 12092 mSettings.enableSystemPackageLPw(newPs.name); 12093 // Remove any native libraries from the upgraded package. 12094 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12095 } 12096 // Install the system package 12097 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12098 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12099 if (locationIsPrivileged(disabledPs.codePath)) { 12100 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12101 } 12102 12103 final PackageParser.Package newPkg; 12104 try { 12105 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12106 } catch (PackageManagerException e) { 12107 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12108 return false; 12109 } 12110 12111 // writer 12112 synchronized (mPackages) { 12113 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12114 updatePermissionsLPw(newPkg.packageName, newPkg, 12115 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12116 if (applyUserRestrictions) { 12117 if (DEBUG_REMOVE) { 12118 Slog.d(TAG, "Propagating install state across reinstall"); 12119 } 12120 for (int i = 0; i < allUserHandles.length; i++) { 12121 if (DEBUG_REMOVE) { 12122 Slog.d(TAG, " user " + allUserHandles[i] 12123 + " => " + perUserInstalled[i]); 12124 } 12125 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12126 } 12127 // Regardless of writeSettings we need to ensure that this restriction 12128 // state propagation is persisted 12129 mSettings.writeAllUsersPackageRestrictionsLPr(); 12130 } 12131 // can downgrade to reader here 12132 if (writeSettings) { 12133 mSettings.writeLPr(); 12134 } 12135 } 12136 return true; 12137 } 12138 12139 private boolean deleteInstalledPackageLI(PackageSetting ps, 12140 boolean deleteCodeAndResources, int flags, 12141 int[] allUserHandles, boolean[] perUserInstalled, 12142 PackageRemovedInfo outInfo, boolean writeSettings) { 12143 if (outInfo != null) { 12144 outInfo.uid = ps.appId; 12145 } 12146 12147 // Delete package data from internal structures and also remove data if flag is set 12148 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12149 12150 // Delete application code and resources 12151 if (deleteCodeAndResources && (outInfo != null)) { 12152 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12153 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12154 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12155 } 12156 return true; 12157 } 12158 12159 @Override 12160 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12161 int userId) { 12162 mContext.enforceCallingOrSelfPermission( 12163 android.Manifest.permission.DELETE_PACKAGES, null); 12164 synchronized (mPackages) { 12165 PackageSetting ps = mSettings.mPackages.get(packageName); 12166 if (ps == null) { 12167 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12168 return false; 12169 } 12170 if (!ps.getInstalled(userId)) { 12171 // Can't block uninstall for an app that is not installed or enabled. 12172 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12173 return false; 12174 } 12175 ps.setBlockUninstall(blockUninstall, userId); 12176 mSettings.writePackageRestrictionsLPr(userId); 12177 } 12178 return true; 12179 } 12180 12181 @Override 12182 public boolean getBlockUninstallForUser(String packageName, int userId) { 12183 synchronized (mPackages) { 12184 PackageSetting ps = mSettings.mPackages.get(packageName); 12185 if (ps == null) { 12186 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12187 return false; 12188 } 12189 return ps.getBlockUninstall(userId); 12190 } 12191 } 12192 12193 /* 12194 * This method handles package deletion in general 12195 */ 12196 private boolean deletePackageLI(String packageName, UserHandle user, 12197 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12198 int flags, PackageRemovedInfo outInfo, 12199 boolean writeSettings) { 12200 if (packageName == null) { 12201 Slog.w(TAG, "Attempt to delete null packageName."); 12202 return false; 12203 } 12204 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12205 PackageSetting ps; 12206 boolean dataOnly = false; 12207 int removeUser = -1; 12208 int appId = -1; 12209 synchronized (mPackages) { 12210 ps = mSettings.mPackages.get(packageName); 12211 if (ps == null) { 12212 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12213 return false; 12214 } 12215 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12216 && user.getIdentifier() != UserHandle.USER_ALL) { 12217 // The caller is asking that the package only be deleted for a single 12218 // user. To do this, we just mark its uninstalled state and delete 12219 // its data. If this is a system app, we only allow this to happen if 12220 // they have set the special DELETE_SYSTEM_APP which requests different 12221 // semantics than normal for uninstalling system apps. 12222 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12223 ps.setUserState(user.getIdentifier(), 12224 COMPONENT_ENABLED_STATE_DEFAULT, 12225 false, //installed 12226 true, //stopped 12227 true, //notLaunched 12228 false, //hidden 12229 null, null, null, 12230 false, // blockUninstall 12231 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12232 if (!isSystemApp(ps)) { 12233 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12234 // Other user still have this package installed, so all 12235 // we need to do is clear this user's data and save that 12236 // it is uninstalled. 12237 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12238 removeUser = user.getIdentifier(); 12239 appId = ps.appId; 12240 scheduleWritePackageRestrictionsLocked(removeUser); 12241 } else { 12242 // We need to set it back to 'installed' so the uninstall 12243 // broadcasts will be sent correctly. 12244 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12245 ps.setInstalled(true, user.getIdentifier()); 12246 } 12247 } else { 12248 // This is a system app, so we assume that the 12249 // other users still have this package installed, so all 12250 // we need to do is clear this user's data and save that 12251 // it is uninstalled. 12252 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12253 removeUser = user.getIdentifier(); 12254 appId = ps.appId; 12255 scheduleWritePackageRestrictionsLocked(removeUser); 12256 } 12257 } 12258 } 12259 12260 if (removeUser >= 0) { 12261 // From above, we determined that we are deleting this only 12262 // for a single user. Continue the work here. 12263 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12264 if (outInfo != null) { 12265 outInfo.removedPackage = packageName; 12266 outInfo.removedAppId = appId; 12267 outInfo.removedUsers = new int[] {removeUser}; 12268 } 12269 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12270 removeKeystoreDataIfNeeded(removeUser, appId); 12271 schedulePackageCleaning(packageName, removeUser, false); 12272 synchronized (mPackages) { 12273 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12274 scheduleWritePackageRestrictionsLocked(removeUser); 12275 } 12276 } 12277 return true; 12278 } 12279 12280 if (dataOnly) { 12281 // Delete application data first 12282 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12283 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12284 return true; 12285 } 12286 12287 boolean ret = false; 12288 if (isSystemApp(ps)) { 12289 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12290 // When an updated system application is deleted we delete the existing resources as well and 12291 // fall back to existing code in system partition 12292 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12293 flags, outInfo, writeSettings); 12294 } else { 12295 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12296 // Kill application pre-emptively especially for apps on sd. 12297 killApplication(packageName, ps.appId, "uninstall pkg"); 12298 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12299 allUserHandles, perUserInstalled, 12300 outInfo, writeSettings); 12301 } 12302 12303 return ret; 12304 } 12305 12306 private final class ClearStorageConnection implements ServiceConnection { 12307 IMediaContainerService mContainerService; 12308 12309 @Override 12310 public void onServiceConnected(ComponentName name, IBinder service) { 12311 synchronized (this) { 12312 mContainerService = IMediaContainerService.Stub.asInterface(service); 12313 notifyAll(); 12314 } 12315 } 12316 12317 @Override 12318 public void onServiceDisconnected(ComponentName name) { 12319 } 12320 } 12321 12322 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12323 final boolean mounted; 12324 if (Environment.isExternalStorageEmulated()) { 12325 mounted = true; 12326 } else { 12327 final String status = Environment.getExternalStorageState(); 12328 12329 mounted = status.equals(Environment.MEDIA_MOUNTED) 12330 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12331 } 12332 12333 if (!mounted) { 12334 return; 12335 } 12336 12337 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12338 int[] users; 12339 if (userId == UserHandle.USER_ALL) { 12340 users = sUserManager.getUserIds(); 12341 } else { 12342 users = new int[] { userId }; 12343 } 12344 final ClearStorageConnection conn = new ClearStorageConnection(); 12345 if (mContext.bindServiceAsUser( 12346 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12347 try { 12348 for (int curUser : users) { 12349 long timeout = SystemClock.uptimeMillis() + 5000; 12350 synchronized (conn) { 12351 long now = SystemClock.uptimeMillis(); 12352 while (conn.mContainerService == null && now < timeout) { 12353 try { 12354 conn.wait(timeout - now); 12355 } catch (InterruptedException e) { 12356 } 12357 } 12358 } 12359 if (conn.mContainerService == null) { 12360 return; 12361 } 12362 12363 final UserEnvironment userEnv = new UserEnvironment(curUser); 12364 clearDirectory(conn.mContainerService, 12365 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12366 if (allData) { 12367 clearDirectory(conn.mContainerService, 12368 userEnv.buildExternalStorageAppDataDirs(packageName)); 12369 clearDirectory(conn.mContainerService, 12370 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12371 } 12372 } 12373 } finally { 12374 mContext.unbindService(conn); 12375 } 12376 } 12377 } 12378 12379 @Override 12380 public void clearApplicationUserData(final String packageName, 12381 final IPackageDataObserver observer, final int userId) { 12382 mContext.enforceCallingOrSelfPermission( 12383 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12384 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12385 // Queue up an async operation since the package deletion may take a little while. 12386 mHandler.post(new Runnable() { 12387 public void run() { 12388 mHandler.removeCallbacks(this); 12389 final boolean succeeded; 12390 synchronized (mInstallLock) { 12391 succeeded = clearApplicationUserDataLI(packageName, userId); 12392 } 12393 clearExternalStorageDataSync(packageName, userId, true); 12394 if (succeeded) { 12395 // invoke DeviceStorageMonitor's update method to clear any notifications 12396 DeviceStorageMonitorInternal 12397 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12398 if (dsm != null) { 12399 dsm.checkMemory(); 12400 } 12401 } 12402 if(observer != null) { 12403 try { 12404 observer.onRemoveCompleted(packageName, succeeded); 12405 } catch (RemoteException e) { 12406 Log.i(TAG, "Observer no longer exists."); 12407 } 12408 } //end if observer 12409 } //end run 12410 }); 12411 } 12412 12413 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12414 if (packageName == null) { 12415 Slog.w(TAG, "Attempt to delete null packageName."); 12416 return false; 12417 } 12418 12419 // Try finding details about the requested package 12420 PackageParser.Package pkg; 12421 synchronized (mPackages) { 12422 pkg = mPackages.get(packageName); 12423 if (pkg == null) { 12424 final PackageSetting ps = mSettings.mPackages.get(packageName); 12425 if (ps != null) { 12426 pkg = ps.pkg; 12427 } 12428 } 12429 } 12430 12431 if (pkg == null) { 12432 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12433 } 12434 12435 // Always delete data directories for package, even if we found no other 12436 // record of app. This helps users recover from UID mismatches without 12437 // resorting to a full data wipe. 12438 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12439 if (retCode < 0) { 12440 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12441 return false; 12442 } 12443 12444 if (pkg == null) { 12445 return false; 12446 } 12447 12448 if (pkg != null && pkg.applicationInfo != null) { 12449 final int appId = pkg.applicationInfo.uid; 12450 removeKeystoreDataIfNeeded(userId, appId); 12451 } 12452 12453 // Create a native library symlink only if we have native libraries 12454 // and if the native libraries are 32 bit libraries. We do not provide 12455 // this symlink for 64 bit libraries. 12456 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12457 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12458 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12459 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12460 nativeLibPath, userId) < 0) { 12461 Slog.w(TAG, "Failed linking native library dir"); 12462 return false; 12463 } 12464 } 12465 12466 return true; 12467 } 12468 12469 /** 12470 * Remove entries from the keystore daemon. Will only remove it if the 12471 * {@code appId} is valid. 12472 */ 12473 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12474 if (appId < 0) { 12475 return; 12476 } 12477 12478 final KeyStore keyStore = KeyStore.getInstance(); 12479 if (keyStore != null) { 12480 if (userId == UserHandle.USER_ALL) { 12481 for (final int individual : sUserManager.getUserIds()) { 12482 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12483 } 12484 } else { 12485 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12486 } 12487 } else { 12488 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12489 } 12490 } 12491 12492 @Override 12493 public void deleteApplicationCacheFiles(final String packageName, 12494 final IPackageDataObserver observer) { 12495 mContext.enforceCallingOrSelfPermission( 12496 android.Manifest.permission.DELETE_CACHE_FILES, null); 12497 // Queue up an async operation since the package deletion may take a little while. 12498 final int userId = UserHandle.getCallingUserId(); 12499 mHandler.post(new Runnable() { 12500 public void run() { 12501 mHandler.removeCallbacks(this); 12502 final boolean succeded; 12503 synchronized (mInstallLock) { 12504 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12505 } 12506 clearExternalStorageDataSync(packageName, userId, false); 12507 if(observer != null) { 12508 try { 12509 observer.onRemoveCompleted(packageName, succeded); 12510 } catch (RemoteException e) { 12511 Log.i(TAG, "Observer no longer exists."); 12512 } 12513 } //end if observer 12514 } //end run 12515 }); 12516 } 12517 12518 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12519 if (packageName == null) { 12520 Slog.w(TAG, "Attempt to delete null packageName."); 12521 return false; 12522 } 12523 PackageParser.Package p; 12524 synchronized (mPackages) { 12525 p = mPackages.get(packageName); 12526 } 12527 if (p == null) { 12528 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12529 return false; 12530 } 12531 final ApplicationInfo applicationInfo = p.applicationInfo; 12532 if (applicationInfo == null) { 12533 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12534 return false; 12535 } 12536 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12537 if (retCode < 0) { 12538 Slog.w(TAG, "Couldn't remove cache files for package: " 12539 + packageName + " u" + userId); 12540 return false; 12541 } 12542 return true; 12543 } 12544 12545 @Override 12546 public void getPackageSizeInfo(final String packageName, int userHandle, 12547 final IPackageStatsObserver observer) { 12548 mContext.enforceCallingOrSelfPermission( 12549 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12550 if (packageName == null) { 12551 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12552 } 12553 12554 PackageStats stats = new PackageStats(packageName, userHandle); 12555 12556 /* 12557 * Queue up an async operation since the package measurement may take a 12558 * little while. 12559 */ 12560 Message msg = mHandler.obtainMessage(INIT_COPY); 12561 msg.obj = new MeasureParams(stats, observer); 12562 mHandler.sendMessage(msg); 12563 } 12564 12565 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12566 PackageStats pStats) { 12567 if (packageName == null) { 12568 Slog.w(TAG, "Attempt to get size of null packageName."); 12569 return false; 12570 } 12571 PackageParser.Package p; 12572 boolean dataOnly = false; 12573 String libDirRoot = null; 12574 String asecPath = null; 12575 PackageSetting ps = null; 12576 synchronized (mPackages) { 12577 p = mPackages.get(packageName); 12578 ps = mSettings.mPackages.get(packageName); 12579 if(p == null) { 12580 dataOnly = true; 12581 if((ps == null) || (ps.pkg == null)) { 12582 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12583 return false; 12584 } 12585 p = ps.pkg; 12586 } 12587 if (ps != null) { 12588 libDirRoot = ps.legacyNativeLibraryPathString; 12589 } 12590 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12591 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12592 if (secureContainerId != null) { 12593 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12594 } 12595 } 12596 } 12597 String publicSrcDir = null; 12598 if(!dataOnly) { 12599 final ApplicationInfo applicationInfo = p.applicationInfo; 12600 if (applicationInfo == null) { 12601 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12602 return false; 12603 } 12604 if (p.isForwardLocked()) { 12605 publicSrcDir = applicationInfo.getBaseResourcePath(); 12606 } 12607 } 12608 // TODO: extend to measure size of split APKs 12609 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12610 // not just the first level. 12611 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12612 // just the primary. 12613 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12614 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12615 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12616 if (res < 0) { 12617 return false; 12618 } 12619 12620 // Fix-up for forward-locked applications in ASEC containers. 12621 if (!isExternal(p)) { 12622 pStats.codeSize += pStats.externalCodeSize; 12623 pStats.externalCodeSize = 0L; 12624 } 12625 12626 return true; 12627 } 12628 12629 12630 @Override 12631 public void addPackageToPreferred(String packageName) { 12632 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12633 } 12634 12635 @Override 12636 public void removePackageFromPreferred(String packageName) { 12637 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12638 } 12639 12640 @Override 12641 public List<PackageInfo> getPreferredPackages(int flags) { 12642 return new ArrayList<PackageInfo>(); 12643 } 12644 12645 private int getUidTargetSdkVersionLockedLPr(int uid) { 12646 Object obj = mSettings.getUserIdLPr(uid); 12647 if (obj instanceof SharedUserSetting) { 12648 final SharedUserSetting sus = (SharedUserSetting) obj; 12649 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12650 final Iterator<PackageSetting> it = sus.packages.iterator(); 12651 while (it.hasNext()) { 12652 final PackageSetting ps = it.next(); 12653 if (ps.pkg != null) { 12654 int v = ps.pkg.applicationInfo.targetSdkVersion; 12655 if (v < vers) vers = v; 12656 } 12657 } 12658 return vers; 12659 } else if (obj instanceof PackageSetting) { 12660 final PackageSetting ps = (PackageSetting) obj; 12661 if (ps.pkg != null) { 12662 return ps.pkg.applicationInfo.targetSdkVersion; 12663 } 12664 } 12665 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12666 } 12667 12668 @Override 12669 public void addPreferredActivity(IntentFilter filter, int match, 12670 ComponentName[] set, ComponentName activity, int userId) { 12671 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12672 "Adding preferred"); 12673 } 12674 12675 private void addPreferredActivityInternal(IntentFilter filter, int match, 12676 ComponentName[] set, ComponentName activity, boolean always, int userId, 12677 String opname) { 12678 // writer 12679 int callingUid = Binder.getCallingUid(); 12680 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12681 if (filter.countActions() == 0) { 12682 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12683 return; 12684 } 12685 synchronized (mPackages) { 12686 if (mContext.checkCallingOrSelfPermission( 12687 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12688 != PackageManager.PERMISSION_GRANTED) { 12689 if (getUidTargetSdkVersionLockedLPr(callingUid) 12690 < Build.VERSION_CODES.FROYO) { 12691 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12692 + callingUid); 12693 return; 12694 } 12695 mContext.enforceCallingOrSelfPermission( 12696 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12697 } 12698 12699 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12700 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12701 + userId + ":"); 12702 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12703 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12704 scheduleWritePackageRestrictionsLocked(userId); 12705 } 12706 } 12707 12708 @Override 12709 public void replacePreferredActivity(IntentFilter filter, int match, 12710 ComponentName[] set, ComponentName activity, int userId) { 12711 if (filter.countActions() != 1) { 12712 throw new IllegalArgumentException( 12713 "replacePreferredActivity expects filter to have only 1 action."); 12714 } 12715 if (filter.countDataAuthorities() != 0 12716 || filter.countDataPaths() != 0 12717 || filter.countDataSchemes() > 1 12718 || filter.countDataTypes() != 0) { 12719 throw new IllegalArgumentException( 12720 "replacePreferredActivity expects filter to have no data authorities, " + 12721 "paths, or types; and at most one scheme."); 12722 } 12723 12724 final int callingUid = Binder.getCallingUid(); 12725 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12726 synchronized (mPackages) { 12727 if (mContext.checkCallingOrSelfPermission( 12728 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12729 != PackageManager.PERMISSION_GRANTED) { 12730 if (getUidTargetSdkVersionLockedLPr(callingUid) 12731 < Build.VERSION_CODES.FROYO) { 12732 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12733 + Binder.getCallingUid()); 12734 return; 12735 } 12736 mContext.enforceCallingOrSelfPermission( 12737 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12738 } 12739 12740 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12741 if (pir != null) { 12742 // Get all of the existing entries that exactly match this filter. 12743 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12744 if (existing != null && existing.size() == 1) { 12745 PreferredActivity cur = existing.get(0); 12746 if (DEBUG_PREFERRED) { 12747 Slog.i(TAG, "Checking replace of preferred:"); 12748 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12749 if (!cur.mPref.mAlways) { 12750 Slog.i(TAG, " -- CUR; not mAlways!"); 12751 } else { 12752 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12753 Slog.i(TAG, " -- CUR: mSet=" 12754 + Arrays.toString(cur.mPref.mSetComponents)); 12755 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12756 Slog.i(TAG, " -- NEW: mMatch=" 12757 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12758 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12759 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12760 } 12761 } 12762 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12763 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12764 && cur.mPref.sameSet(set)) { 12765 // Setting the preferred activity to what it happens to be already 12766 if (DEBUG_PREFERRED) { 12767 Slog.i(TAG, "Replacing with same preferred activity " 12768 + cur.mPref.mShortComponent + " for user " 12769 + userId + ":"); 12770 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12771 } 12772 return; 12773 } 12774 } 12775 12776 if (existing != null) { 12777 if (DEBUG_PREFERRED) { 12778 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12779 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12780 } 12781 for (int i = 0; i < existing.size(); i++) { 12782 PreferredActivity pa = existing.get(i); 12783 if (DEBUG_PREFERRED) { 12784 Slog.i(TAG, "Removing existing preferred activity " 12785 + pa.mPref.mComponent + ":"); 12786 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 12787 } 12788 pir.removeFilter(pa); 12789 } 12790 } 12791 } 12792 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12793 "Replacing preferred"); 12794 } 12795 } 12796 12797 @Override 12798 public void clearPackagePreferredActivities(String packageName) { 12799 final int uid = Binder.getCallingUid(); 12800 // writer 12801 synchronized (mPackages) { 12802 PackageParser.Package pkg = mPackages.get(packageName); 12803 if (pkg == null || pkg.applicationInfo.uid != uid) { 12804 if (mContext.checkCallingOrSelfPermission( 12805 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12806 != PackageManager.PERMISSION_GRANTED) { 12807 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 12808 < Build.VERSION_CODES.FROYO) { 12809 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 12810 + Binder.getCallingUid()); 12811 return; 12812 } 12813 mContext.enforceCallingOrSelfPermission( 12814 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12815 } 12816 } 12817 12818 int user = UserHandle.getCallingUserId(); 12819 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 12820 scheduleWritePackageRestrictionsLocked(user); 12821 } 12822 } 12823 } 12824 12825 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12826 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 12827 ArrayList<PreferredActivity> removed = null; 12828 boolean changed = false; 12829 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12830 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 12831 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12832 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 12833 continue; 12834 } 12835 Iterator<PreferredActivity> it = pir.filterIterator(); 12836 while (it.hasNext()) { 12837 PreferredActivity pa = it.next(); 12838 // Mark entry for removal only if it matches the package name 12839 // and the entry is of type "always". 12840 if (packageName == null || 12841 (pa.mPref.mComponent.getPackageName().equals(packageName) 12842 && pa.mPref.mAlways)) { 12843 if (removed == null) { 12844 removed = new ArrayList<PreferredActivity>(); 12845 } 12846 removed.add(pa); 12847 } 12848 } 12849 if (removed != null) { 12850 for (int j=0; j<removed.size(); j++) { 12851 PreferredActivity pa = removed.get(j); 12852 pir.removeFilter(pa); 12853 } 12854 changed = true; 12855 } 12856 } 12857 return changed; 12858 } 12859 12860 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 12861 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 12862 if (userId == UserHandle.USER_ALL) { 12863 if (mSettings.removeIntentFilterVerificationLPw(packageName, 12864 sUserManager.getUserIds())) { 12865 for (int oneUserId : sUserManager.getUserIds()) { 12866 scheduleWritePackageRestrictionsLocked(oneUserId); 12867 } 12868 } 12869 } else { 12870 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 12871 scheduleWritePackageRestrictionsLocked(userId); 12872 } 12873 } 12874 } 12875 12876 @Override 12877 public void resetPreferredActivities(int userId) { 12878 /* TODO: Actually use userId. Why is it being passed in? */ 12879 mContext.enforceCallingOrSelfPermission( 12880 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12881 // writer 12882 synchronized (mPackages) { 12883 int user = UserHandle.getCallingUserId(); 12884 clearPackagePreferredActivitiesLPw(null, user); 12885 mSettings.readDefaultPreferredAppsLPw(this, user); 12886 scheduleWritePackageRestrictionsLocked(user); 12887 } 12888 } 12889 12890 @Override 12891 public int getPreferredActivities(List<IntentFilter> outFilters, 12892 List<ComponentName> outActivities, String packageName) { 12893 12894 int num = 0; 12895 final int userId = UserHandle.getCallingUserId(); 12896 // reader 12897 synchronized (mPackages) { 12898 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12899 if (pir != null) { 12900 final Iterator<PreferredActivity> it = pir.filterIterator(); 12901 while (it.hasNext()) { 12902 final PreferredActivity pa = it.next(); 12903 if (packageName == null 12904 || (pa.mPref.mComponent.getPackageName().equals(packageName) 12905 && pa.mPref.mAlways)) { 12906 if (outFilters != null) { 12907 outFilters.add(new IntentFilter(pa)); 12908 } 12909 if (outActivities != null) { 12910 outActivities.add(pa.mPref.mComponent); 12911 } 12912 } 12913 } 12914 } 12915 } 12916 12917 return num; 12918 } 12919 12920 @Override 12921 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 12922 int userId) { 12923 int callingUid = Binder.getCallingUid(); 12924 if (callingUid != Process.SYSTEM_UID) { 12925 throw new SecurityException( 12926 "addPersistentPreferredActivity can only be run by the system"); 12927 } 12928 if (filter.countActions() == 0) { 12929 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12930 return; 12931 } 12932 synchronized (mPackages) { 12933 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 12934 " :"); 12935 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12936 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 12937 new PersistentPreferredActivity(filter, activity)); 12938 scheduleWritePackageRestrictionsLocked(userId); 12939 } 12940 } 12941 12942 @Override 12943 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 12944 int callingUid = Binder.getCallingUid(); 12945 if (callingUid != Process.SYSTEM_UID) { 12946 throw new SecurityException( 12947 "clearPackagePersistentPreferredActivities can only be run by the system"); 12948 } 12949 ArrayList<PersistentPreferredActivity> removed = null; 12950 boolean changed = false; 12951 synchronized (mPackages) { 12952 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12953 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12954 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12955 .valueAt(i); 12956 if (userId != thisUserId) { 12957 continue; 12958 } 12959 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12960 while (it.hasNext()) { 12961 PersistentPreferredActivity ppa = it.next(); 12962 // Mark entry for removal only if it matches the package name. 12963 if (ppa.mComponent.getPackageName().equals(packageName)) { 12964 if (removed == null) { 12965 removed = new ArrayList<PersistentPreferredActivity>(); 12966 } 12967 removed.add(ppa); 12968 } 12969 } 12970 if (removed != null) { 12971 for (int j=0; j<removed.size(); j++) { 12972 PersistentPreferredActivity ppa = removed.get(j); 12973 ppir.removeFilter(ppa); 12974 } 12975 changed = true; 12976 } 12977 } 12978 12979 if (changed) { 12980 scheduleWritePackageRestrictionsLocked(userId); 12981 } 12982 } 12983 } 12984 12985 /** 12986 * Non-Binder method, support for the backup/restore mechanism: write the 12987 * full set of preferred activities in its canonical XML format. Returns true 12988 * on success; false otherwise. 12989 */ 12990 @Override 12991 public byte[] getPreferredActivityBackup(int userId) { 12992 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 12993 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 12994 } 12995 12996 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 12997 try { 12998 final XmlSerializer serializer = new FastXmlSerializer(); 12999 serializer.setOutput(dataStream, "utf-8"); 13000 serializer.startDocument(null, true); 13001 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13002 13003 synchronized (mPackages) { 13004 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13005 } 13006 13007 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13008 serializer.endDocument(); 13009 serializer.flush(); 13010 } catch (Exception e) { 13011 if (DEBUG_BACKUP) { 13012 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13013 } 13014 return null; 13015 } 13016 13017 return dataStream.toByteArray(); 13018 } 13019 13020 @Override 13021 public void restorePreferredActivities(byte[] backup, int userId) { 13022 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13023 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13024 } 13025 13026 try { 13027 final XmlPullParser parser = Xml.newPullParser(); 13028 parser.setInput(new ByteArrayInputStream(backup), null); 13029 13030 int type; 13031 while ((type = parser.next()) != XmlPullParser.START_TAG 13032 && type != XmlPullParser.END_DOCUMENT) { 13033 } 13034 if (type != XmlPullParser.START_TAG) { 13035 // oops didn't find a start tag?! 13036 if (DEBUG_BACKUP) { 13037 Slog.e(TAG, "Didn't find start tag during restore"); 13038 } 13039 return; 13040 } 13041 13042 // this is supposed to be TAG_PREFERRED_BACKUP 13043 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13044 if (DEBUG_BACKUP) { 13045 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13046 } 13047 return; 13048 } 13049 13050 // skip interfering stuff, then we're aligned with the backing implementation 13051 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13052 synchronized (mPackages) { 13053 mSettings.readPreferredActivitiesLPw(parser, userId); 13054 } 13055 } catch (Exception e) { 13056 if (DEBUG_BACKUP) { 13057 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13058 } 13059 } 13060 } 13061 13062 @Override 13063 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13064 int sourceUserId, int targetUserId, int flags) { 13065 mContext.enforceCallingOrSelfPermission( 13066 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13067 int callingUid = Binder.getCallingUid(); 13068 enforceOwnerRights(ownerPackage, callingUid); 13069 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13070 if (intentFilter.countActions() == 0) { 13071 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13072 return; 13073 } 13074 synchronized (mPackages) { 13075 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13076 ownerPackage, targetUserId, flags); 13077 CrossProfileIntentResolver resolver = 13078 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13079 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13080 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13081 if (existing != null) { 13082 int size = existing.size(); 13083 for (int i = 0; i < size; i++) { 13084 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13085 return; 13086 } 13087 } 13088 } 13089 resolver.addFilter(newFilter); 13090 scheduleWritePackageRestrictionsLocked(sourceUserId); 13091 } 13092 } 13093 13094 @Override 13095 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13096 mContext.enforceCallingOrSelfPermission( 13097 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13098 int callingUid = Binder.getCallingUid(); 13099 enforceOwnerRights(ownerPackage, callingUid); 13100 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13101 synchronized (mPackages) { 13102 CrossProfileIntentResolver resolver = 13103 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13104 ArraySet<CrossProfileIntentFilter> set = 13105 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13106 for (CrossProfileIntentFilter filter : set) { 13107 if (filter.getOwnerPackage().equals(ownerPackage)) { 13108 resolver.removeFilter(filter); 13109 } 13110 } 13111 scheduleWritePackageRestrictionsLocked(sourceUserId); 13112 } 13113 } 13114 13115 // Enforcing that callingUid is owning pkg on userId 13116 private void enforceOwnerRights(String pkg, int callingUid) { 13117 // The system owns everything. 13118 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13119 return; 13120 } 13121 int callingUserId = UserHandle.getUserId(callingUid); 13122 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13123 if (pi == null) { 13124 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13125 + callingUserId); 13126 } 13127 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13128 throw new SecurityException("Calling uid " + callingUid 13129 + " does not own package " + pkg); 13130 } 13131 } 13132 13133 @Override 13134 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13135 Intent intent = new Intent(Intent.ACTION_MAIN); 13136 intent.addCategory(Intent.CATEGORY_HOME); 13137 13138 final int callingUserId = UserHandle.getCallingUserId(); 13139 List<ResolveInfo> list = queryIntentActivities(intent, null, 13140 PackageManager.GET_META_DATA, callingUserId); 13141 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13142 true, false, false, callingUserId); 13143 13144 allHomeCandidates.clear(); 13145 if (list != null) { 13146 for (ResolveInfo ri : list) { 13147 allHomeCandidates.add(ri); 13148 } 13149 } 13150 return (preferred == null || preferred.activityInfo == null) 13151 ? null 13152 : new ComponentName(preferred.activityInfo.packageName, 13153 preferred.activityInfo.name); 13154 } 13155 13156 @Override 13157 public void setApplicationEnabledSetting(String appPackageName, 13158 int newState, int flags, int userId, String callingPackage) { 13159 if (!sUserManager.exists(userId)) return; 13160 if (callingPackage == null) { 13161 callingPackage = Integer.toString(Binder.getCallingUid()); 13162 } 13163 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13164 } 13165 13166 @Override 13167 public void setComponentEnabledSetting(ComponentName componentName, 13168 int newState, int flags, int userId) { 13169 if (!sUserManager.exists(userId)) return; 13170 setEnabledSetting(componentName.getPackageName(), 13171 componentName.getClassName(), newState, flags, userId, null); 13172 } 13173 13174 private void setEnabledSetting(final String packageName, String className, int newState, 13175 final int flags, int userId, String callingPackage) { 13176 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13177 || newState == COMPONENT_ENABLED_STATE_ENABLED 13178 || newState == COMPONENT_ENABLED_STATE_DISABLED 13179 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13180 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13181 throw new IllegalArgumentException("Invalid new component state: " 13182 + newState); 13183 } 13184 PackageSetting pkgSetting; 13185 final int uid = Binder.getCallingUid(); 13186 final int permission = mContext.checkCallingOrSelfPermission( 13187 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13188 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13189 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13190 boolean sendNow = false; 13191 boolean isApp = (className == null); 13192 String componentName = isApp ? packageName : className; 13193 int packageUid = -1; 13194 ArrayList<String> components; 13195 13196 // writer 13197 synchronized (mPackages) { 13198 pkgSetting = mSettings.mPackages.get(packageName); 13199 if (pkgSetting == null) { 13200 if (className == null) { 13201 throw new IllegalArgumentException( 13202 "Unknown package: " + packageName); 13203 } 13204 throw new IllegalArgumentException( 13205 "Unknown component: " + packageName 13206 + "/" + className); 13207 } 13208 // Allow root and verify that userId is not being specified by a different user 13209 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13210 throw new SecurityException( 13211 "Permission Denial: attempt to change component state from pid=" 13212 + Binder.getCallingPid() 13213 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13214 } 13215 if (className == null) { 13216 // We're dealing with an application/package level state change 13217 if (pkgSetting.getEnabled(userId) == newState) { 13218 // Nothing to do 13219 return; 13220 } 13221 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13222 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13223 // Don't care about who enables an app. 13224 callingPackage = null; 13225 } 13226 pkgSetting.setEnabled(newState, userId, callingPackage); 13227 // pkgSetting.pkg.mSetEnabled = newState; 13228 } else { 13229 // We're dealing with a component level state change 13230 // First, verify that this is a valid class name. 13231 PackageParser.Package pkg = pkgSetting.pkg; 13232 if (pkg == null || !pkg.hasComponentClassName(className)) { 13233 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13234 throw new IllegalArgumentException("Component class " + className 13235 + " does not exist in " + packageName); 13236 } else { 13237 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13238 + className + " does not exist in " + packageName); 13239 } 13240 } 13241 switch (newState) { 13242 case COMPONENT_ENABLED_STATE_ENABLED: 13243 if (!pkgSetting.enableComponentLPw(className, userId)) { 13244 return; 13245 } 13246 break; 13247 case COMPONENT_ENABLED_STATE_DISABLED: 13248 if (!pkgSetting.disableComponentLPw(className, userId)) { 13249 return; 13250 } 13251 break; 13252 case COMPONENT_ENABLED_STATE_DEFAULT: 13253 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13254 return; 13255 } 13256 break; 13257 default: 13258 Slog.e(TAG, "Invalid new component state: " + newState); 13259 return; 13260 } 13261 } 13262 scheduleWritePackageRestrictionsLocked(userId); 13263 components = mPendingBroadcasts.get(userId, packageName); 13264 final boolean newPackage = components == null; 13265 if (newPackage) { 13266 components = new ArrayList<String>(); 13267 } 13268 if (!components.contains(componentName)) { 13269 components.add(componentName); 13270 } 13271 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13272 sendNow = true; 13273 // Purge entry from pending broadcast list if another one exists already 13274 // since we are sending one right away. 13275 mPendingBroadcasts.remove(userId, packageName); 13276 } else { 13277 if (newPackage) { 13278 mPendingBroadcasts.put(userId, packageName, components); 13279 } 13280 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13281 // Schedule a message 13282 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13283 } 13284 } 13285 } 13286 13287 long callingId = Binder.clearCallingIdentity(); 13288 try { 13289 if (sendNow) { 13290 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13291 sendPackageChangedBroadcast(packageName, 13292 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13293 } 13294 } finally { 13295 Binder.restoreCallingIdentity(callingId); 13296 } 13297 } 13298 13299 private void sendPackageChangedBroadcast(String packageName, 13300 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13301 if (DEBUG_INSTALL) 13302 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13303 + componentNames); 13304 Bundle extras = new Bundle(4); 13305 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13306 String nameList[] = new String[componentNames.size()]; 13307 componentNames.toArray(nameList); 13308 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13309 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13310 extras.putInt(Intent.EXTRA_UID, packageUid); 13311 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13312 new int[] {UserHandle.getUserId(packageUid)}); 13313 } 13314 13315 @Override 13316 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13317 if (!sUserManager.exists(userId)) return; 13318 final int uid = Binder.getCallingUid(); 13319 final int permission = mContext.checkCallingOrSelfPermission( 13320 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13321 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13322 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13323 // writer 13324 synchronized (mPackages) { 13325 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13326 allowedByPermission, uid, userId)) { 13327 scheduleWritePackageRestrictionsLocked(userId); 13328 } 13329 } 13330 } 13331 13332 @Override 13333 public String getInstallerPackageName(String packageName) { 13334 // reader 13335 synchronized (mPackages) { 13336 return mSettings.getInstallerPackageNameLPr(packageName); 13337 } 13338 } 13339 13340 @Override 13341 public int getApplicationEnabledSetting(String packageName, int userId) { 13342 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13343 int uid = Binder.getCallingUid(); 13344 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13345 // reader 13346 synchronized (mPackages) { 13347 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13348 } 13349 } 13350 13351 @Override 13352 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13353 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13354 int uid = Binder.getCallingUid(); 13355 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13356 // reader 13357 synchronized (mPackages) { 13358 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13359 } 13360 } 13361 13362 @Override 13363 public void enterSafeMode() { 13364 enforceSystemOrRoot("Only the system can request entering safe mode"); 13365 13366 if (!mSystemReady) { 13367 mSafeMode = true; 13368 } 13369 } 13370 13371 @Override 13372 public void systemReady() { 13373 mSystemReady = true; 13374 13375 // Read the compatibilty setting when the system is ready. 13376 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13377 mContext.getContentResolver(), 13378 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13379 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13380 if (DEBUG_SETTINGS) { 13381 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13382 } 13383 13384 synchronized (mPackages) { 13385 // Verify that all of the preferred activity components actually 13386 // exist. It is possible for applications to be updated and at 13387 // that point remove a previously declared activity component that 13388 // had been set as a preferred activity. We try to clean this up 13389 // the next time we encounter that preferred activity, but it is 13390 // possible for the user flow to never be able to return to that 13391 // situation so here we do a sanity check to make sure we haven't 13392 // left any junk around. 13393 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13394 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13395 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13396 removed.clear(); 13397 for (PreferredActivity pa : pir.filterSet()) { 13398 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13399 removed.add(pa); 13400 } 13401 } 13402 if (removed.size() > 0) { 13403 for (int r=0; r<removed.size(); r++) { 13404 PreferredActivity pa = removed.get(r); 13405 Slog.w(TAG, "Removing dangling preferred activity: " 13406 + pa.mPref.mComponent); 13407 pir.removeFilter(pa); 13408 } 13409 mSettings.writePackageRestrictionsLPr( 13410 mSettings.mPreferredActivities.keyAt(i)); 13411 } 13412 } 13413 } 13414 sUserManager.systemReady(); 13415 13416 // Kick off any messages waiting for system ready 13417 if (mPostSystemReadyMessages != null) { 13418 for (Message msg : mPostSystemReadyMessages) { 13419 msg.sendToTarget(); 13420 } 13421 mPostSystemReadyMessages = null; 13422 } 13423 13424 // Watch for external volumes that come and go over time 13425 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13426 storage.registerListener(mStorageListener); 13427 13428 mInstallerService.systemReady(); 13429 } 13430 13431 @Override 13432 public boolean isSafeMode() { 13433 return mSafeMode; 13434 } 13435 13436 @Override 13437 public boolean hasSystemUidErrors() { 13438 return mHasSystemUidErrors; 13439 } 13440 13441 static String arrayToString(int[] array) { 13442 StringBuffer buf = new StringBuffer(128); 13443 buf.append('['); 13444 if (array != null) { 13445 for (int i=0; i<array.length; i++) { 13446 if (i > 0) buf.append(", "); 13447 buf.append(array[i]); 13448 } 13449 } 13450 buf.append(']'); 13451 return buf.toString(); 13452 } 13453 13454 static class DumpState { 13455 public static final int DUMP_LIBS = 1 << 0; 13456 public static final int DUMP_FEATURES = 1 << 1; 13457 public static final int DUMP_RESOLVERS = 1 << 2; 13458 public static final int DUMP_PERMISSIONS = 1 << 3; 13459 public static final int DUMP_PACKAGES = 1 << 4; 13460 public static final int DUMP_SHARED_USERS = 1 << 5; 13461 public static final int DUMP_MESSAGES = 1 << 6; 13462 public static final int DUMP_PROVIDERS = 1 << 7; 13463 public static final int DUMP_VERIFIERS = 1 << 8; 13464 public static final int DUMP_PREFERRED = 1 << 9; 13465 public static final int DUMP_PREFERRED_XML = 1 << 10; 13466 public static final int DUMP_KEYSETS = 1 << 11; 13467 public static final int DUMP_VERSION = 1 << 12; 13468 public static final int DUMP_INSTALLS = 1 << 13; 13469 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13470 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13471 13472 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13473 13474 private int mTypes; 13475 13476 private int mOptions; 13477 13478 private boolean mTitlePrinted; 13479 13480 private SharedUserSetting mSharedUser; 13481 13482 public boolean isDumping(int type) { 13483 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13484 return true; 13485 } 13486 13487 return (mTypes & type) != 0; 13488 } 13489 13490 public void setDump(int type) { 13491 mTypes |= type; 13492 } 13493 13494 public boolean isOptionEnabled(int option) { 13495 return (mOptions & option) != 0; 13496 } 13497 13498 public void setOptionEnabled(int option) { 13499 mOptions |= option; 13500 } 13501 13502 public boolean onTitlePrinted() { 13503 final boolean printed = mTitlePrinted; 13504 mTitlePrinted = true; 13505 return printed; 13506 } 13507 13508 public boolean getTitlePrinted() { 13509 return mTitlePrinted; 13510 } 13511 13512 public void setTitlePrinted(boolean enabled) { 13513 mTitlePrinted = enabled; 13514 } 13515 13516 public SharedUserSetting getSharedUser() { 13517 return mSharedUser; 13518 } 13519 13520 public void setSharedUser(SharedUserSetting user) { 13521 mSharedUser = user; 13522 } 13523 } 13524 13525 @Override 13526 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13527 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13528 != PackageManager.PERMISSION_GRANTED) { 13529 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13530 + Binder.getCallingPid() 13531 + ", uid=" + Binder.getCallingUid() 13532 + " without permission " 13533 + android.Manifest.permission.DUMP); 13534 return; 13535 } 13536 13537 DumpState dumpState = new DumpState(); 13538 boolean fullPreferred = false; 13539 boolean checkin = false; 13540 13541 String packageName = null; 13542 13543 int opti = 0; 13544 while (opti < args.length) { 13545 String opt = args[opti]; 13546 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13547 break; 13548 } 13549 opti++; 13550 13551 if ("-a".equals(opt)) { 13552 // Right now we only know how to print all. 13553 } else if ("-h".equals(opt)) { 13554 pw.println("Package manager dump options:"); 13555 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13556 pw.println(" --checkin: dump for a checkin"); 13557 pw.println(" -f: print details of intent filters"); 13558 pw.println(" -h: print this help"); 13559 pw.println(" cmd may be one of:"); 13560 pw.println(" l[ibraries]: list known shared libraries"); 13561 pw.println(" f[ibraries]: list device features"); 13562 pw.println(" k[eysets]: print known keysets"); 13563 pw.println(" r[esolvers]: dump intent resolvers"); 13564 pw.println(" perm[issions]: dump permissions"); 13565 pw.println(" pref[erred]: print preferred package settings"); 13566 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13567 pw.println(" prov[iders]: dump content providers"); 13568 pw.println(" p[ackages]: dump installed packages"); 13569 pw.println(" s[hared-users]: dump shared user IDs"); 13570 pw.println(" m[essages]: print collected runtime messages"); 13571 pw.println(" v[erifiers]: print package verifier info"); 13572 pw.println(" version: print database version info"); 13573 pw.println(" write: write current settings now"); 13574 pw.println(" <package.name>: info about given package"); 13575 pw.println(" installs: details about install sessions"); 13576 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13577 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13578 return; 13579 } else if ("--checkin".equals(opt)) { 13580 checkin = true; 13581 } else if ("-f".equals(opt)) { 13582 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13583 } else { 13584 pw.println("Unknown argument: " + opt + "; use -h for help"); 13585 } 13586 } 13587 13588 // Is the caller requesting to dump a particular piece of data? 13589 if (opti < args.length) { 13590 String cmd = args[opti]; 13591 opti++; 13592 // Is this a package name? 13593 if ("android".equals(cmd) || cmd.contains(".")) { 13594 packageName = cmd; 13595 // When dumping a single package, we always dump all of its 13596 // filter information since the amount of data will be reasonable. 13597 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13598 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13599 dumpState.setDump(DumpState.DUMP_LIBS); 13600 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13601 dumpState.setDump(DumpState.DUMP_FEATURES); 13602 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13603 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13604 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13605 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13606 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13607 dumpState.setDump(DumpState.DUMP_PREFERRED); 13608 } else if ("preferred-xml".equals(cmd)) { 13609 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13610 if (opti < args.length && "--full".equals(args[opti])) { 13611 fullPreferred = true; 13612 opti++; 13613 } 13614 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13615 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13616 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13617 dumpState.setDump(DumpState.DUMP_PACKAGES); 13618 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13619 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13620 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13621 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13622 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13623 dumpState.setDump(DumpState.DUMP_MESSAGES); 13624 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13625 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13626 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13627 || "intent-filter-verifiers".equals(cmd)) { 13628 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13629 } else if ("version".equals(cmd)) { 13630 dumpState.setDump(DumpState.DUMP_VERSION); 13631 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13632 dumpState.setDump(DumpState.DUMP_KEYSETS); 13633 } else if ("installs".equals(cmd)) { 13634 dumpState.setDump(DumpState.DUMP_INSTALLS); 13635 } else if ("write".equals(cmd)) { 13636 synchronized (mPackages) { 13637 mSettings.writeLPr(); 13638 pw.println("Settings written."); 13639 return; 13640 } 13641 } 13642 } 13643 13644 if (checkin) { 13645 pw.println("vers,1"); 13646 } 13647 13648 // reader 13649 synchronized (mPackages) { 13650 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13651 if (!checkin) { 13652 if (dumpState.onTitlePrinted()) 13653 pw.println(); 13654 pw.println("Database versions:"); 13655 pw.print(" SDK Version:"); 13656 pw.print(" internal="); 13657 pw.print(mSettings.mInternalSdkPlatform); 13658 pw.print(" external="); 13659 pw.println(mSettings.mExternalSdkPlatform); 13660 pw.print(" DB Version:"); 13661 pw.print(" internal="); 13662 pw.print(mSettings.mInternalDatabaseVersion); 13663 pw.print(" external="); 13664 pw.println(mSettings.mExternalDatabaseVersion); 13665 } 13666 } 13667 13668 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13669 if (!checkin) { 13670 if (dumpState.onTitlePrinted()) 13671 pw.println(); 13672 pw.println("Verifiers:"); 13673 pw.print(" Required: "); 13674 pw.print(mRequiredVerifierPackage); 13675 pw.print(" (uid="); 13676 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13677 pw.println(")"); 13678 } else if (mRequiredVerifierPackage != null) { 13679 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13680 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13681 } 13682 } 13683 13684 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13685 packageName == null) { 13686 if (mIntentFilterVerifierComponent != null) { 13687 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13688 if (!checkin) { 13689 if (dumpState.onTitlePrinted()) 13690 pw.println(); 13691 pw.println("Intent Filter Verifier:"); 13692 pw.print(" Using: "); 13693 pw.print(verifierPackageName); 13694 pw.print(" (uid="); 13695 pw.print(getPackageUid(verifierPackageName, 0)); 13696 pw.println(")"); 13697 } else if (verifierPackageName != null) { 13698 pw.print("ifv,"); pw.print(verifierPackageName); 13699 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13700 } 13701 } else { 13702 pw.println(); 13703 pw.println("No Intent Filter Verifier available!"); 13704 } 13705 } 13706 13707 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13708 boolean printedHeader = false; 13709 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13710 while (it.hasNext()) { 13711 String name = it.next(); 13712 SharedLibraryEntry ent = mSharedLibraries.get(name); 13713 if (!checkin) { 13714 if (!printedHeader) { 13715 if (dumpState.onTitlePrinted()) 13716 pw.println(); 13717 pw.println("Libraries:"); 13718 printedHeader = true; 13719 } 13720 pw.print(" "); 13721 } else { 13722 pw.print("lib,"); 13723 } 13724 pw.print(name); 13725 if (!checkin) { 13726 pw.print(" -> "); 13727 } 13728 if (ent.path != null) { 13729 if (!checkin) { 13730 pw.print("(jar) "); 13731 pw.print(ent.path); 13732 } else { 13733 pw.print(",jar,"); 13734 pw.print(ent.path); 13735 } 13736 } else { 13737 if (!checkin) { 13738 pw.print("(apk) "); 13739 pw.print(ent.apk); 13740 } else { 13741 pw.print(",apk,"); 13742 pw.print(ent.apk); 13743 } 13744 } 13745 pw.println(); 13746 } 13747 } 13748 13749 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13750 if (dumpState.onTitlePrinted()) 13751 pw.println(); 13752 if (!checkin) { 13753 pw.println("Features:"); 13754 } 13755 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13756 while (it.hasNext()) { 13757 String name = it.next(); 13758 if (!checkin) { 13759 pw.print(" "); 13760 } else { 13761 pw.print("feat,"); 13762 } 13763 pw.println(name); 13764 } 13765 } 13766 13767 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13768 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13769 : "Activity Resolver Table:", " ", packageName, 13770 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13771 dumpState.setTitlePrinted(true); 13772 } 13773 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13774 : "Receiver Resolver Table:", " ", packageName, 13775 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13776 dumpState.setTitlePrinted(true); 13777 } 13778 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 13779 : "Service Resolver Table:", " ", packageName, 13780 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13781 dumpState.setTitlePrinted(true); 13782 } 13783 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 13784 : "Provider Resolver Table:", " ", packageName, 13785 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13786 dumpState.setTitlePrinted(true); 13787 } 13788 } 13789 13790 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 13791 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13792 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13793 int user = mSettings.mPreferredActivities.keyAt(i); 13794 if (pir.dump(pw, 13795 dumpState.getTitlePrinted() 13796 ? "\nPreferred Activities User " + user + ":" 13797 : "Preferred Activities User " + user + ":", " ", 13798 packageName, true, false)) { 13799 dumpState.setTitlePrinted(true); 13800 } 13801 } 13802 } 13803 13804 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 13805 pw.flush(); 13806 FileOutputStream fout = new FileOutputStream(fd); 13807 BufferedOutputStream str = new BufferedOutputStream(fout); 13808 XmlSerializer serializer = new FastXmlSerializer(); 13809 try { 13810 serializer.setOutput(str, "utf-8"); 13811 serializer.startDocument(null, true); 13812 serializer.setFeature( 13813 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 13814 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 13815 serializer.endDocument(); 13816 serializer.flush(); 13817 } catch (IllegalArgumentException e) { 13818 pw.println("Failed writing: " + e); 13819 } catch (IllegalStateException e) { 13820 pw.println("Failed writing: " + e); 13821 } catch (IOException e) { 13822 pw.println("Failed writing: " + e); 13823 } 13824 } 13825 13826 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 13827 pw.println(); 13828 int count = mSettings.mPackages.size(); 13829 if (count == 0) { 13830 pw.println("No domain preferred apps!"); 13831 pw.println(); 13832 } else { 13833 final String prefix = " "; 13834 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 13835 if (allPackageSettings.size() == 0) { 13836 pw.println("No domain preferred apps!"); 13837 pw.println(); 13838 } else { 13839 pw.println("Domain preferred apps status:"); 13840 pw.println(); 13841 count = 0; 13842 for (PackageSetting ps : allPackageSettings) { 13843 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13844 if (ivi == null || ivi.getPackageName() == null) continue; 13845 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13846 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13847 pw.println(prefix + "Status: " + ivi.getStatusString()); 13848 pw.println(); 13849 count++; 13850 } 13851 if (count == 0) { 13852 pw.println(prefix + "No domain preferred app status!"); 13853 pw.println(); 13854 } 13855 for (int userId : sUserManager.getUserIds()) { 13856 pw.println("Domain preferred apps for User " + userId + ":"); 13857 pw.println(); 13858 count = 0; 13859 for (PackageSetting ps : allPackageSettings) { 13860 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 13861 if (ivi == null || ivi.getPackageName() == null) { 13862 continue; 13863 } 13864 final int status = ps.getDomainVerificationStatusForUser(userId); 13865 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 13866 continue; 13867 } 13868 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 13869 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 13870 String statusStr = IntentFilterVerificationInfo. 13871 getStatusStringFromValue(status); 13872 pw.println(prefix + "Status: " + statusStr); 13873 pw.println(); 13874 count++; 13875 } 13876 if (count == 0) { 13877 pw.println(prefix + "No domain preferred apps!"); 13878 pw.println(); 13879 } 13880 } 13881 } 13882 } 13883 } 13884 13885 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 13886 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 13887 if (packageName == null) { 13888 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 13889 if (iperm == 0) { 13890 if (dumpState.onTitlePrinted()) 13891 pw.println(); 13892 pw.println("AppOp Permissions:"); 13893 } 13894 pw.print(" AppOp Permission "); 13895 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 13896 pw.println(":"); 13897 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 13898 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 13899 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 13900 } 13901 } 13902 } 13903 } 13904 13905 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 13906 boolean printedSomething = false; 13907 for (PackageParser.Provider p : mProviders.mProviders.values()) { 13908 if (packageName != null && !packageName.equals(p.info.packageName)) { 13909 continue; 13910 } 13911 if (!printedSomething) { 13912 if (dumpState.onTitlePrinted()) 13913 pw.println(); 13914 pw.println("Registered ContentProviders:"); 13915 printedSomething = true; 13916 } 13917 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 13918 pw.print(" "); pw.println(p.toString()); 13919 } 13920 printedSomething = false; 13921 for (Map.Entry<String, PackageParser.Provider> entry : 13922 mProvidersByAuthority.entrySet()) { 13923 PackageParser.Provider p = entry.getValue(); 13924 if (packageName != null && !packageName.equals(p.info.packageName)) { 13925 continue; 13926 } 13927 if (!printedSomething) { 13928 if (dumpState.onTitlePrinted()) 13929 pw.println(); 13930 pw.println("ContentProvider Authorities:"); 13931 printedSomething = true; 13932 } 13933 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 13934 pw.print(" "); pw.println(p.toString()); 13935 if (p.info != null && p.info.applicationInfo != null) { 13936 final String appInfo = p.info.applicationInfo.toString(); 13937 pw.print(" applicationInfo="); pw.println(appInfo); 13938 } 13939 } 13940 } 13941 13942 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 13943 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 13944 } 13945 13946 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 13947 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 13948 } 13949 13950 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 13951 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 13952 } 13953 13954 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 13955 // XXX should handle packageName != null by dumping only install data that 13956 // the given package is involved with. 13957 if (dumpState.onTitlePrinted()) pw.println(); 13958 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 13959 } 13960 13961 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 13962 if (dumpState.onTitlePrinted()) pw.println(); 13963 mSettings.dumpReadMessagesLPr(pw, dumpState); 13964 13965 pw.println(); 13966 pw.println("Package warning messages:"); 13967 BufferedReader in = null; 13968 String line = null; 13969 try { 13970 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13971 while ((line = in.readLine()) != null) { 13972 if (line.contains("ignored: updated version")) continue; 13973 pw.println(line); 13974 } 13975 } catch (IOException ignored) { 13976 } finally { 13977 IoUtils.closeQuietly(in); 13978 } 13979 } 13980 13981 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 13982 BufferedReader in = null; 13983 String line = null; 13984 try { 13985 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 13986 while ((line = in.readLine()) != null) { 13987 if (line.contains("ignored: updated version")) continue; 13988 pw.print("msg,"); 13989 pw.println(line); 13990 } 13991 } catch (IOException ignored) { 13992 } finally { 13993 IoUtils.closeQuietly(in); 13994 } 13995 } 13996 } 13997 } 13998 13999 // ------- apps on sdcard specific code ------- 14000 static final boolean DEBUG_SD_INSTALL = false; 14001 14002 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14003 14004 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14005 14006 private boolean mMediaMounted = false; 14007 14008 static String getEncryptKey() { 14009 try { 14010 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14011 SD_ENCRYPTION_KEYSTORE_NAME); 14012 if (sdEncKey == null) { 14013 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14014 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14015 if (sdEncKey == null) { 14016 Slog.e(TAG, "Failed to create encryption keys"); 14017 return null; 14018 } 14019 } 14020 return sdEncKey; 14021 } catch (NoSuchAlgorithmException nsae) { 14022 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14023 return null; 14024 } catch (IOException ioe) { 14025 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14026 return null; 14027 } 14028 } 14029 14030 /* 14031 * Update media status on PackageManager. 14032 */ 14033 @Override 14034 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14035 int callingUid = Binder.getCallingUid(); 14036 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14037 throw new SecurityException("Media status can only be updated by the system"); 14038 } 14039 // reader; this apparently protects mMediaMounted, but should probably 14040 // be a different lock in that case. 14041 synchronized (mPackages) { 14042 Log.i(TAG, "Updating external media status from " 14043 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14044 + (mediaStatus ? "mounted" : "unmounted")); 14045 if (DEBUG_SD_INSTALL) 14046 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14047 + ", mMediaMounted=" + mMediaMounted); 14048 if (mediaStatus == mMediaMounted) { 14049 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14050 : 0, -1); 14051 mHandler.sendMessage(msg); 14052 return; 14053 } 14054 mMediaMounted = mediaStatus; 14055 } 14056 // Queue up an async operation since the package installation may take a 14057 // little while. 14058 mHandler.post(new Runnable() { 14059 public void run() { 14060 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14061 } 14062 }); 14063 } 14064 14065 /** 14066 * Called by MountService when the initial ASECs to scan are available. 14067 * Should block until all the ASEC containers are finished being scanned. 14068 */ 14069 public void scanAvailableAsecs() { 14070 updateExternalMediaStatusInner(true, false, false); 14071 if (mShouldRestoreconData) { 14072 SELinuxMMAC.setRestoreconDone(); 14073 mShouldRestoreconData = false; 14074 } 14075 } 14076 14077 /* 14078 * Collect information of applications on external media, map them against 14079 * existing containers and update information based on current mount status. 14080 * Please note that we always have to report status if reportStatus has been 14081 * set to true especially when unloading packages. 14082 */ 14083 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14084 boolean externalStorage) { 14085 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14086 int[] uidArr = EmptyArray.INT; 14087 14088 final String[] list = PackageHelper.getSecureContainerList(); 14089 if (ArrayUtils.isEmpty(list)) { 14090 Log.i(TAG, "No secure containers found"); 14091 } else { 14092 // Process list of secure containers and categorize them 14093 // as active or stale based on their package internal state. 14094 14095 // reader 14096 synchronized (mPackages) { 14097 for (String cid : list) { 14098 // Leave stages untouched for now; installer service owns them 14099 if (PackageInstallerService.isStageName(cid)) continue; 14100 14101 if (DEBUG_SD_INSTALL) 14102 Log.i(TAG, "Processing container " + cid); 14103 String pkgName = getAsecPackageName(cid); 14104 if (pkgName == null) { 14105 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14106 continue; 14107 } 14108 if (DEBUG_SD_INSTALL) 14109 Log.i(TAG, "Looking for pkg : " + pkgName); 14110 14111 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14112 if (ps == null) { 14113 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14114 continue; 14115 } 14116 14117 /* 14118 * Skip packages that are not external if we're unmounting 14119 * external storage. 14120 */ 14121 if (externalStorage && !isMounted && !isExternal(ps)) { 14122 continue; 14123 } 14124 14125 final AsecInstallArgs args = new AsecInstallArgs(cid, 14126 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14127 // The package status is changed only if the code path 14128 // matches between settings and the container id. 14129 if (ps.codePathString != null 14130 && ps.codePathString.startsWith(args.getCodePath())) { 14131 if (DEBUG_SD_INSTALL) { 14132 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14133 + " at code path: " + ps.codePathString); 14134 } 14135 14136 // We do have a valid package installed on sdcard 14137 processCids.put(args, ps.codePathString); 14138 final int uid = ps.appId; 14139 if (uid != -1) { 14140 uidArr = ArrayUtils.appendInt(uidArr, uid); 14141 } 14142 } else { 14143 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14144 + ps.codePathString); 14145 } 14146 } 14147 } 14148 14149 Arrays.sort(uidArr); 14150 } 14151 14152 // Process packages with valid entries. 14153 if (isMounted) { 14154 if (DEBUG_SD_INSTALL) 14155 Log.i(TAG, "Loading packages"); 14156 loadMediaPackages(processCids, uidArr); 14157 startCleaningPackages(); 14158 mInstallerService.onSecureContainersAvailable(); 14159 } else { 14160 if (DEBUG_SD_INSTALL) 14161 Log.i(TAG, "Unloading packages"); 14162 unloadMediaPackages(processCids, uidArr, reportStatus); 14163 } 14164 } 14165 14166 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14167 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14168 final int size = infos.size(); 14169 final String[] packageNames = new String[size]; 14170 final int[] packageUids = new int[size]; 14171 for (int i = 0; i < size; i++) { 14172 final ApplicationInfo info = infos.get(i); 14173 packageNames[i] = info.packageName; 14174 packageUids[i] = info.uid; 14175 } 14176 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14177 finishedReceiver); 14178 } 14179 14180 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14181 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14182 sendResourcesChangedBroadcast(mediaStatus, replacing, 14183 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14184 } 14185 14186 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14187 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14188 int size = pkgList.length; 14189 if (size > 0) { 14190 // Send broadcasts here 14191 Bundle extras = new Bundle(); 14192 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14193 if (uidArr != null) { 14194 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14195 } 14196 if (replacing) { 14197 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14198 } 14199 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14200 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14201 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14202 } 14203 } 14204 14205 /* 14206 * Look at potentially valid container ids from processCids If package 14207 * information doesn't match the one on record or package scanning fails, 14208 * the cid is added to list of removeCids. We currently don't delete stale 14209 * containers. 14210 */ 14211 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14212 ArrayList<String> pkgList = new ArrayList<String>(); 14213 Set<AsecInstallArgs> keys = processCids.keySet(); 14214 14215 for (AsecInstallArgs args : keys) { 14216 String codePath = processCids.get(args); 14217 if (DEBUG_SD_INSTALL) 14218 Log.i(TAG, "Loading container : " + args.cid); 14219 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14220 try { 14221 // Make sure there are no container errors first. 14222 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14223 Slog.e(TAG, "Failed to mount cid : " + args.cid 14224 + " when installing from sdcard"); 14225 continue; 14226 } 14227 // Check code path here. 14228 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14229 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14230 + " does not match one in settings " + codePath); 14231 continue; 14232 } 14233 // Parse package 14234 int parseFlags = mDefParseFlags; 14235 if (args.isExternalAsec()) { 14236 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14237 } 14238 if (args.isFwdLocked()) { 14239 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14240 } 14241 14242 synchronized (mInstallLock) { 14243 PackageParser.Package pkg = null; 14244 try { 14245 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14246 } catch (PackageManagerException e) { 14247 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14248 } 14249 // Scan the package 14250 if (pkg != null) { 14251 /* 14252 * TODO why is the lock being held? doPostInstall is 14253 * called in other places without the lock. This needs 14254 * to be straightened out. 14255 */ 14256 // writer 14257 synchronized (mPackages) { 14258 retCode = PackageManager.INSTALL_SUCCEEDED; 14259 pkgList.add(pkg.packageName); 14260 // Post process args 14261 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14262 pkg.applicationInfo.uid); 14263 } 14264 } else { 14265 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14266 } 14267 } 14268 14269 } finally { 14270 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14271 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14272 } 14273 } 14274 } 14275 // writer 14276 synchronized (mPackages) { 14277 // If the platform SDK has changed since the last time we booted, 14278 // we need to re-grant app permission to catch any new ones that 14279 // appear. This is really a hack, and means that apps can in some 14280 // cases get permissions that the user didn't initially explicitly 14281 // allow... it would be nice to have some better way to handle 14282 // this situation. 14283 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14284 if (regrantPermissions) 14285 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14286 + mSdkVersion + "; regranting permissions for external storage"); 14287 mSettings.mExternalSdkPlatform = mSdkVersion; 14288 14289 // Make sure group IDs have been assigned, and any permission 14290 // changes in other apps are accounted for 14291 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14292 | (regrantPermissions 14293 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14294 : 0)); 14295 14296 mSettings.updateExternalDatabaseVersion(); 14297 14298 // can downgrade to reader 14299 // Persist settings 14300 mSettings.writeLPr(); 14301 } 14302 // Send a broadcast to let everyone know we are done processing 14303 if (pkgList.size() > 0) { 14304 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14305 } 14306 } 14307 14308 /* 14309 * Utility method to unload a list of specified containers 14310 */ 14311 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14312 // Just unmount all valid containers. 14313 for (AsecInstallArgs arg : cidArgs) { 14314 synchronized (mInstallLock) { 14315 arg.doPostDeleteLI(false); 14316 } 14317 } 14318 } 14319 14320 /* 14321 * Unload packages mounted on external media. This involves deleting package 14322 * data from internal structures, sending broadcasts about diabled packages, 14323 * gc'ing to free up references, unmounting all secure containers 14324 * corresponding to packages on external media, and posting a 14325 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14326 * that we always have to post this message if status has been requested no 14327 * matter what. 14328 */ 14329 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14330 final boolean reportStatus) { 14331 if (DEBUG_SD_INSTALL) 14332 Log.i(TAG, "unloading media packages"); 14333 ArrayList<String> pkgList = new ArrayList<String>(); 14334 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14335 final Set<AsecInstallArgs> keys = processCids.keySet(); 14336 for (AsecInstallArgs args : keys) { 14337 String pkgName = args.getPackageName(); 14338 if (DEBUG_SD_INSTALL) 14339 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14340 // Delete package internally 14341 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14342 synchronized (mInstallLock) { 14343 boolean res = deletePackageLI(pkgName, null, false, null, null, 14344 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14345 if (res) { 14346 pkgList.add(pkgName); 14347 } else { 14348 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14349 failedList.add(args); 14350 } 14351 } 14352 } 14353 14354 // reader 14355 synchronized (mPackages) { 14356 // We didn't update the settings after removing each package; 14357 // write them now for all packages. 14358 mSettings.writeLPr(); 14359 } 14360 14361 // We have to absolutely send UPDATED_MEDIA_STATUS only 14362 // after confirming that all the receivers processed the ordered 14363 // broadcast when packages get disabled, force a gc to clean things up. 14364 // and unload all the containers. 14365 if (pkgList.size() > 0) { 14366 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14367 new IIntentReceiver.Stub() { 14368 public void performReceive(Intent intent, int resultCode, String data, 14369 Bundle extras, boolean ordered, boolean sticky, 14370 int sendingUser) throws RemoteException { 14371 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14372 reportStatus ? 1 : 0, 1, keys); 14373 mHandler.sendMessage(msg); 14374 } 14375 }); 14376 } else { 14377 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14378 keys); 14379 mHandler.sendMessage(msg); 14380 } 14381 } 14382 14383 private void loadPrivatePackages(VolumeInfo vol) { 14384 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14385 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14386 synchronized (mInstallLock) { 14387 synchronized (mPackages) { 14388 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14389 for (PackageSetting ps : packages) { 14390 final PackageParser.Package pkg; 14391 try { 14392 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14393 loaded.add(pkg.applicationInfo); 14394 } catch (PackageManagerException e) { 14395 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14396 } 14397 } 14398 14399 // TODO: regrant any permissions that changed based since original install 14400 14401 mSettings.writeLPr(); 14402 } 14403 } 14404 14405 Slog.d(TAG, "Loaded packages " + loaded); 14406 sendResourcesChangedBroadcast(true, false, loaded, null); 14407 } 14408 14409 private void unloadPrivatePackages(VolumeInfo vol) { 14410 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14411 synchronized (mInstallLock) { 14412 synchronized (mPackages) { 14413 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14414 for (PackageSetting ps : packages) { 14415 if (ps.pkg == null) continue; 14416 14417 final ApplicationInfo info = ps.pkg.applicationInfo; 14418 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14419 if (deletePackageLI(ps.name, null, false, null, null, 14420 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14421 unloaded.add(info); 14422 } else { 14423 Slog.w(TAG, "Failed to unload " + ps.codePath); 14424 } 14425 } 14426 14427 mSettings.writeLPr(); 14428 } 14429 } 14430 14431 Slog.d(TAG, "Unloaded packages " + unloaded); 14432 sendResourcesChangedBroadcast(false, false, unloaded, null); 14433 } 14434 14435 private void unfreezePackage(String packageName) { 14436 synchronized (mPackages) { 14437 final PackageSetting ps = mSettings.mPackages.get(packageName); 14438 if (ps != null) { 14439 ps.frozen = false; 14440 } 14441 } 14442 } 14443 14444 @Override 14445 public int movePackage(final String packageName, final String volumeUuid) { 14446 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14447 14448 final int moveId = mNextMoveId.getAndIncrement(); 14449 try { 14450 movePackageInternal(packageName, volumeUuid, moveId); 14451 } catch (PackageManagerException e) { 14452 Slog.d(TAG, "Failed to move " + packageName, e); 14453 mMoveCallbacks.notifyStatusChanged(moveId, 14454 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14455 } 14456 return moveId; 14457 } 14458 14459 private void movePackageInternal(final String packageName, final String volumeUuid, 14460 final int moveId) throws PackageManagerException { 14461 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14462 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14463 final PackageManager pm = mContext.getPackageManager(); 14464 14465 final boolean currentAsec; 14466 final String currentVolumeUuid; 14467 final File codeFile; 14468 final String installerPackageName; 14469 final String packageAbiOverride; 14470 final int appId; 14471 final String seinfo; 14472 final String label; 14473 14474 // reader 14475 synchronized (mPackages) { 14476 final PackageParser.Package pkg = mPackages.get(packageName); 14477 final PackageSetting ps = mSettings.mPackages.get(packageName); 14478 if (pkg == null || ps == null) { 14479 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14480 } 14481 14482 if (pkg.applicationInfo.isSystemApp()) { 14483 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14484 "Cannot move system application"); 14485 } 14486 14487 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14488 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14489 "Package already moved to " + volumeUuid); 14490 } 14491 14492 final File probe = new File(pkg.codePath); 14493 final File probeOat = new File(probe, "oat"); 14494 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14495 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14496 "Move only supported for modern cluster style installs"); 14497 } 14498 14499 if (ps.frozen) { 14500 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14501 "Failed to move already frozen package"); 14502 } 14503 ps.frozen = true; 14504 14505 currentAsec = pkg.applicationInfo.isForwardLocked() 14506 || pkg.applicationInfo.isExternalAsec(); 14507 currentVolumeUuid = ps.volumeUuid; 14508 codeFile = new File(pkg.codePath); 14509 installerPackageName = ps.installerPackageName; 14510 packageAbiOverride = ps.cpuAbiOverrideString; 14511 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14512 seinfo = pkg.applicationInfo.seinfo; 14513 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14514 } 14515 14516 // Now that we're guarded by frozen state, kill app during move 14517 killApplication(packageName, appId, "move pkg"); 14518 14519 final Bundle extras = new Bundle(); 14520 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14521 extras.putString(Intent.EXTRA_TITLE, label); 14522 mMoveCallbacks.notifyCreated(moveId, extras); 14523 14524 int installFlags; 14525 final boolean moveCompleteApp; 14526 final File measurePath; 14527 14528 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14529 installFlags = INSTALL_INTERNAL; 14530 moveCompleteApp = !currentAsec; 14531 measurePath = Environment.getDataAppDirectory(volumeUuid); 14532 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14533 installFlags = INSTALL_EXTERNAL; 14534 moveCompleteApp = false; 14535 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14536 } else { 14537 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14538 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14539 || !volume.isMountedWritable()) { 14540 unfreezePackage(packageName); 14541 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14542 "Move location not mounted private volume"); 14543 } 14544 14545 Preconditions.checkState(!currentAsec); 14546 14547 installFlags = INSTALL_INTERNAL; 14548 moveCompleteApp = true; 14549 measurePath = Environment.getDataAppDirectory(volumeUuid); 14550 } 14551 14552 final PackageStats stats = new PackageStats(null, -1); 14553 synchronized (mInstaller) { 14554 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14555 unfreezePackage(packageName); 14556 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14557 "Failed to measure package size"); 14558 } 14559 } 14560 14561 Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize); 14562 14563 final long startFreeBytes = measurePath.getFreeSpace(); 14564 final long sizeBytes; 14565 if (moveCompleteApp) { 14566 sizeBytes = stats.codeSize + stats.dataSize; 14567 } else { 14568 sizeBytes = stats.codeSize; 14569 } 14570 14571 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14572 unfreezePackage(packageName); 14573 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14574 "Not enough free space to move"); 14575 } 14576 14577 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14578 14579 final CountDownLatch installedLatch = new CountDownLatch(1); 14580 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14581 @Override 14582 public void onUserActionRequired(Intent intent) throws RemoteException { 14583 throw new IllegalStateException(); 14584 } 14585 14586 @Override 14587 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14588 Bundle extras) throws RemoteException { 14589 Slog.d(TAG, "Install result for move: " 14590 + PackageManager.installStatusToString(returnCode, msg)); 14591 14592 installedLatch.countDown(); 14593 14594 // Regardless of success or failure of the move operation, 14595 // always unfreeze the package 14596 unfreezePackage(packageName); 14597 14598 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14599 switch (status) { 14600 case PackageInstaller.STATUS_SUCCESS: 14601 mMoveCallbacks.notifyStatusChanged(moveId, 14602 PackageManager.MOVE_SUCCEEDED); 14603 break; 14604 case PackageInstaller.STATUS_FAILURE_STORAGE: 14605 mMoveCallbacks.notifyStatusChanged(moveId, 14606 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14607 break; 14608 default: 14609 mMoveCallbacks.notifyStatusChanged(moveId, 14610 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14611 break; 14612 } 14613 } 14614 }; 14615 14616 final MoveInfo move; 14617 if (moveCompleteApp) { 14618 // Kick off a thread to report progress estimates 14619 new Thread() { 14620 @Override 14621 public void run() { 14622 while (true) { 14623 try { 14624 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14625 break; 14626 } 14627 } catch (InterruptedException ignored) { 14628 } 14629 14630 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14631 final int progress = 10 + (int) MathUtils.constrain( 14632 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14633 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14634 } 14635 } 14636 }.start(); 14637 14638 final String dataAppName = codeFile.getName(); 14639 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14640 dataAppName, appId, seinfo); 14641 } else { 14642 move = null; 14643 } 14644 14645 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14646 14647 final Message msg = mHandler.obtainMessage(INIT_COPY); 14648 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14649 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14650 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14651 mHandler.sendMessage(msg); 14652 } 14653 14654 @Override 14655 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14656 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14657 14658 final int realMoveId = mNextMoveId.getAndIncrement(); 14659 final Bundle extras = new Bundle(); 14660 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14661 mMoveCallbacks.notifyCreated(realMoveId, extras); 14662 14663 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14664 @Override 14665 public void onCreated(int moveId, Bundle extras) { 14666 // Ignored 14667 } 14668 14669 @Override 14670 public void onStatusChanged(int moveId, int status, long estMillis) { 14671 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14672 } 14673 }; 14674 14675 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14676 storage.setPrimaryStorageUuid(volumeUuid, callback); 14677 return realMoveId; 14678 } 14679 14680 @Override 14681 public int getMoveStatus(int moveId) { 14682 mContext.enforceCallingOrSelfPermission( 14683 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14684 return mMoveCallbacks.mLastStatus.get(moveId); 14685 } 14686 14687 @Override 14688 public void registerMoveCallback(IPackageMoveObserver callback) { 14689 mContext.enforceCallingOrSelfPermission( 14690 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14691 mMoveCallbacks.register(callback); 14692 } 14693 14694 @Override 14695 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14696 mContext.enforceCallingOrSelfPermission( 14697 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14698 mMoveCallbacks.unregister(callback); 14699 } 14700 14701 @Override 14702 public boolean setInstallLocation(int loc) { 14703 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14704 null); 14705 if (getInstallLocation() == loc) { 14706 return true; 14707 } 14708 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14709 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14710 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14711 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14712 return true; 14713 } 14714 return false; 14715 } 14716 14717 @Override 14718 public int getInstallLocation() { 14719 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14720 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14721 PackageHelper.APP_INSTALL_AUTO); 14722 } 14723 14724 /** Called by UserManagerService */ 14725 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14726 mDirtyUsers.remove(userHandle); 14727 mSettings.removeUserLPw(userHandle); 14728 mPendingBroadcasts.remove(userHandle); 14729 if (mInstaller != null) { 14730 // Technically, we shouldn't be doing this with the package lock 14731 // held. However, this is very rare, and there is already so much 14732 // other disk I/O going on, that we'll let it slide for now. 14733 final StorageManager storage = StorageManager.from(mContext); 14734 final List<VolumeInfo> vols = storage.getVolumes(); 14735 for (VolumeInfo vol : vols) { 14736 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14737 final String volumeUuid = vol.getFsUuid(); 14738 Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14739 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14740 } 14741 } 14742 } 14743 mUserNeedsBadging.delete(userHandle); 14744 removeUnusedPackagesLILPw(userManager, userHandle); 14745 } 14746 14747 /** 14748 * We're removing userHandle and would like to remove any downloaded packages 14749 * that are no longer in use by any other user. 14750 * @param userHandle the user being removed 14751 */ 14752 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14753 final boolean DEBUG_CLEAN_APKS = false; 14754 int [] users = userManager.getUserIdsLPr(); 14755 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14756 while (psit.hasNext()) { 14757 PackageSetting ps = psit.next(); 14758 if (ps.pkg == null) { 14759 continue; 14760 } 14761 final String packageName = ps.pkg.packageName; 14762 // Skip over if system app 14763 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14764 continue; 14765 } 14766 if (DEBUG_CLEAN_APKS) { 14767 Slog.i(TAG, "Checking package " + packageName); 14768 } 14769 boolean keep = false; 14770 for (int i = 0; i < users.length; i++) { 14771 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14772 keep = true; 14773 if (DEBUG_CLEAN_APKS) { 14774 Slog.i(TAG, " Keeping package " + packageName + " for user " 14775 + users[i]); 14776 } 14777 break; 14778 } 14779 } 14780 if (!keep) { 14781 if (DEBUG_CLEAN_APKS) { 14782 Slog.i(TAG, " Removing package " + packageName); 14783 } 14784 mHandler.post(new Runnable() { 14785 public void run() { 14786 deletePackageX(packageName, userHandle, 0); 14787 } //end run 14788 }); 14789 } 14790 } 14791 } 14792 14793 /** Called by UserManagerService */ 14794 void createNewUserLILPw(int userHandle, File path) { 14795 if (mInstaller != null) { 14796 mInstaller.createUserConfig(userHandle); 14797 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 14798 } 14799 } 14800 14801 void newUserCreatedLILPw(int userHandle) { 14802 // Adding a user requires updating runtime permissions for system apps. 14803 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 14804 } 14805 14806 @Override 14807 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 14808 mContext.enforceCallingOrSelfPermission( 14809 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14810 "Only package verification agents can read the verifier device identity"); 14811 14812 synchronized (mPackages) { 14813 return mSettings.getVerifierDeviceIdentityLPw(); 14814 } 14815 } 14816 14817 @Override 14818 public void setPermissionEnforced(String permission, boolean enforced) { 14819 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 14820 if (READ_EXTERNAL_STORAGE.equals(permission)) { 14821 synchronized (mPackages) { 14822 if (mSettings.mReadExternalStorageEnforced == null 14823 || mSettings.mReadExternalStorageEnforced != enforced) { 14824 mSettings.mReadExternalStorageEnforced = enforced; 14825 mSettings.writeLPr(); 14826 } 14827 } 14828 // kill any non-foreground processes so we restart them and 14829 // grant/revoke the GID. 14830 final IActivityManager am = ActivityManagerNative.getDefault(); 14831 if (am != null) { 14832 final long token = Binder.clearCallingIdentity(); 14833 try { 14834 am.killProcessesBelowForeground("setPermissionEnforcement"); 14835 } catch (RemoteException e) { 14836 } finally { 14837 Binder.restoreCallingIdentity(token); 14838 } 14839 } 14840 } else { 14841 throw new IllegalArgumentException("No selective enforcement for " + permission); 14842 } 14843 } 14844 14845 @Override 14846 @Deprecated 14847 public boolean isPermissionEnforced(String permission) { 14848 return true; 14849 } 14850 14851 @Override 14852 public boolean isStorageLow() { 14853 final long token = Binder.clearCallingIdentity(); 14854 try { 14855 final DeviceStorageMonitorInternal 14856 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 14857 if (dsm != null) { 14858 return dsm.isMemoryLow(); 14859 } else { 14860 return false; 14861 } 14862 } finally { 14863 Binder.restoreCallingIdentity(token); 14864 } 14865 } 14866 14867 @Override 14868 public IPackageInstaller getPackageInstaller() { 14869 return mInstallerService; 14870 } 14871 14872 private boolean userNeedsBadging(int userId) { 14873 int index = mUserNeedsBadging.indexOfKey(userId); 14874 if (index < 0) { 14875 final UserInfo userInfo; 14876 final long token = Binder.clearCallingIdentity(); 14877 try { 14878 userInfo = sUserManager.getUserInfo(userId); 14879 } finally { 14880 Binder.restoreCallingIdentity(token); 14881 } 14882 final boolean b; 14883 if (userInfo != null && userInfo.isManagedProfile()) { 14884 b = true; 14885 } else { 14886 b = false; 14887 } 14888 mUserNeedsBadging.put(userId, b); 14889 return b; 14890 } 14891 return mUserNeedsBadging.valueAt(index); 14892 } 14893 14894 @Override 14895 public KeySet getKeySetByAlias(String packageName, String alias) { 14896 if (packageName == null || alias == null) { 14897 return null; 14898 } 14899 synchronized(mPackages) { 14900 final PackageParser.Package pkg = mPackages.get(packageName); 14901 if (pkg == null) { 14902 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14903 throw new IllegalArgumentException("Unknown package: " + packageName); 14904 } 14905 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14906 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 14907 } 14908 } 14909 14910 @Override 14911 public KeySet getSigningKeySet(String packageName) { 14912 if (packageName == null) { 14913 return null; 14914 } 14915 synchronized(mPackages) { 14916 final PackageParser.Package pkg = mPackages.get(packageName); 14917 if (pkg == null) { 14918 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14919 throw new IllegalArgumentException("Unknown package: " + packageName); 14920 } 14921 if (pkg.applicationInfo.uid != Binder.getCallingUid() 14922 && Process.SYSTEM_UID != Binder.getCallingUid()) { 14923 throw new SecurityException("May not access signing KeySet of other apps."); 14924 } 14925 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14926 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 14927 } 14928 } 14929 14930 @Override 14931 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 14932 if (packageName == null || ks == null) { 14933 return false; 14934 } 14935 synchronized(mPackages) { 14936 final PackageParser.Package pkg = mPackages.get(packageName); 14937 if (pkg == null) { 14938 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14939 throw new IllegalArgumentException("Unknown package: " + packageName); 14940 } 14941 IBinder ksh = ks.getToken(); 14942 if (ksh instanceof KeySetHandle) { 14943 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14944 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 14945 } 14946 return false; 14947 } 14948 } 14949 14950 @Override 14951 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 14952 if (packageName == null || ks == null) { 14953 return false; 14954 } 14955 synchronized(mPackages) { 14956 final PackageParser.Package pkg = mPackages.get(packageName); 14957 if (pkg == null) { 14958 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 14959 throw new IllegalArgumentException("Unknown package: " + packageName); 14960 } 14961 IBinder ksh = ks.getToken(); 14962 if (ksh instanceof KeySetHandle) { 14963 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14964 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 14965 } 14966 return false; 14967 } 14968 } 14969 14970 public void getUsageStatsIfNoPackageUsageInfo() { 14971 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 14972 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 14973 if (usm == null) { 14974 throw new IllegalStateException("UsageStatsManager must be initialized"); 14975 } 14976 long now = System.currentTimeMillis(); 14977 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 14978 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 14979 String packageName = entry.getKey(); 14980 PackageParser.Package pkg = mPackages.get(packageName); 14981 if (pkg == null) { 14982 continue; 14983 } 14984 UsageStats usage = entry.getValue(); 14985 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 14986 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 14987 } 14988 } 14989 } 14990 14991 /** 14992 * Check and throw if the given before/after packages would be considered a 14993 * downgrade. 14994 */ 14995 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 14996 throws PackageManagerException { 14997 if (after.versionCode < before.mVersionCode) { 14998 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 14999 "Update version code " + after.versionCode + " is older than current " 15000 + before.mVersionCode); 15001 } else if (after.versionCode == before.mVersionCode) { 15002 if (after.baseRevisionCode < before.baseRevisionCode) { 15003 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15004 "Update base revision code " + after.baseRevisionCode 15005 + " is older than current " + before.baseRevisionCode); 15006 } 15007 15008 if (!ArrayUtils.isEmpty(after.splitNames)) { 15009 for (int i = 0; i < after.splitNames.length; i++) { 15010 final String splitName = after.splitNames[i]; 15011 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15012 if (j != -1) { 15013 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15014 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15015 "Update split " + splitName + " revision code " 15016 + after.splitRevisionCodes[i] + " is older than current " 15017 + before.splitRevisionCodes[j]); 15018 } 15019 } 15020 } 15021 } 15022 } 15023 } 15024 15025 private static class MoveCallbacks extends Handler { 15026 private static final int MSG_CREATED = 1; 15027 private static final int MSG_STATUS_CHANGED = 2; 15028 15029 private final RemoteCallbackList<IPackageMoveObserver> 15030 mCallbacks = new RemoteCallbackList<>(); 15031 15032 private final SparseIntArray mLastStatus = new SparseIntArray(); 15033 15034 public MoveCallbacks(Looper looper) { 15035 super(looper); 15036 } 15037 15038 public void register(IPackageMoveObserver callback) { 15039 mCallbacks.register(callback); 15040 } 15041 15042 public void unregister(IPackageMoveObserver callback) { 15043 mCallbacks.unregister(callback); 15044 } 15045 15046 @Override 15047 public void handleMessage(Message msg) { 15048 final SomeArgs args = (SomeArgs) msg.obj; 15049 final int n = mCallbacks.beginBroadcast(); 15050 for (int i = 0; i < n; i++) { 15051 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15052 try { 15053 invokeCallback(callback, msg.what, args); 15054 } catch (RemoteException ignored) { 15055 } 15056 } 15057 mCallbacks.finishBroadcast(); 15058 args.recycle(); 15059 } 15060 15061 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15062 throws RemoteException { 15063 switch (what) { 15064 case MSG_CREATED: { 15065 callback.onCreated(args.argi1, (Bundle) args.arg2); 15066 break; 15067 } 15068 case MSG_STATUS_CHANGED: { 15069 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15070 break; 15071 } 15072 } 15073 } 15074 15075 private void notifyCreated(int moveId, Bundle extras) { 15076 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15077 15078 final SomeArgs args = SomeArgs.obtain(); 15079 args.argi1 = moveId; 15080 args.arg2 = extras; 15081 obtainMessage(MSG_CREATED, args).sendToTarget(); 15082 } 15083 15084 private void notifyStatusChanged(int moveId, int status) { 15085 notifyStatusChanged(moveId, status, -1); 15086 } 15087 15088 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15089 Slog.v(TAG, "Move " + moveId + " status " + status); 15090 15091 final SomeArgs args = SomeArgs.obtain(); 15092 args.argi1 = moveId; 15093 args.argi2 = status; 15094 args.arg3 = estMillis; 15095 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15096 15097 synchronized (mLastStatus) { 15098 mLastStatus.put(moveId, status); 15099 } 15100 } 15101 } 15102} 15103