PackageManagerService.java revision a5c852e03abb9372a6928271a930d7d79e4ec45e
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.FIRST_APPLICATION_UID; 59import static android.os.Process.PACKAGE_INFO_GID; 60import static android.os.Process.SYSTEM_UID; 61import static android.system.OsConstants.O_CREAT; 62import static android.system.OsConstants.O_RDWR; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 67import static com.android.internal.util.ArrayUtils.appendInt; 68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 73 74import android.Manifest; 75import android.app.ActivityManager; 76import android.app.ActivityManagerNative; 77import android.app.AppGlobals; 78import android.app.IActivityManager; 79import android.app.admin.IDevicePolicyManager; 80import android.app.backup.IBackupManager; 81import android.app.usage.UsageStats; 82import android.app.usage.UsageStatsManager; 83import android.content.BroadcastReceiver; 84import android.content.ComponentName; 85import android.content.Context; 86import android.content.IIntentReceiver; 87import android.content.Intent; 88import android.content.IntentFilter; 89import android.content.IntentSender; 90import android.content.IntentSender.SendIntentException; 91import android.content.ServiceConnection; 92import android.content.pm.ActivityInfo; 93import android.content.pm.ApplicationInfo; 94import android.content.pm.FeatureInfo; 95import android.content.pm.IOnPermissionsChangeListener; 96import android.content.pm.IPackageDataObserver; 97import android.content.pm.IPackageDeleteObserver; 98import android.content.pm.IPackageDeleteObserver2; 99import android.content.pm.IPackageInstallObserver2; 100import android.content.pm.IPackageInstaller; 101import android.content.pm.IPackageManager; 102import android.content.pm.IPackageMoveObserver; 103import android.content.pm.IPackageStatsObserver; 104import android.content.pm.InstrumentationInfo; 105import android.content.pm.IntentFilterVerificationInfo; 106import android.content.pm.KeySet; 107import android.content.pm.ManifestDigest; 108import android.content.pm.PackageCleanItem; 109import android.content.pm.PackageInfo; 110import android.content.pm.PackageInfoLite; 111import android.content.pm.PackageInstaller; 112import android.content.pm.PackageManager; 113import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 114import android.content.pm.PackageParser; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageStats; 119import android.content.pm.PackageUserState; 120import android.content.pm.ParceledListSlice; 121import android.content.pm.PermissionGroupInfo; 122import android.content.pm.PermissionInfo; 123import android.content.pm.ProviderInfo; 124import android.content.pm.ResolveInfo; 125import android.content.pm.ServiceInfo; 126import android.content.pm.Signature; 127import android.content.pm.UserInfo; 128import android.content.pm.VerificationParams; 129import android.content.pm.VerifierDeviceIdentity; 130import android.content.pm.VerifierInfo; 131import android.content.res.Resources; 132import android.hardware.display.DisplayManager; 133import android.net.Uri; 134import android.os.Binder; 135import android.os.Build; 136import android.os.Bundle; 137import android.os.Debug; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.FileUtils; 141import android.os.Handler; 142import android.os.IBinder; 143import android.os.Looper; 144import android.os.Message; 145import android.os.Parcel; 146import android.os.ParcelFileDescriptor; 147import android.os.Process; 148import android.os.RemoteCallbackList; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.os.storage.IMountService; 157import android.os.storage.StorageEventListener; 158import android.os.storage.StorageManager; 159import android.os.storage.VolumeInfo; 160import android.os.storage.VolumeRecord; 161import android.security.KeyStore; 162import android.security.SystemKeyStore; 163import android.system.ErrnoException; 164import android.system.Os; 165import android.system.StructStat; 166import android.text.TextUtils; 167import android.text.format.DateUtils; 168import android.util.ArrayMap; 169import android.util.ArraySet; 170import android.util.AtomicFile; 171import android.util.DisplayMetrics; 172import android.util.EventLog; 173import android.util.ExceptionUtils; 174import android.util.Log; 175import android.util.LogPrinter; 176import android.util.MathUtils; 177import android.util.PrintStreamPrinter; 178import android.util.Slog; 179import android.util.SparseArray; 180import android.util.SparseBooleanArray; 181import android.util.SparseIntArray; 182import android.util.Xml; 183import android.view.Display; 184 185import dalvik.system.DexFile; 186import dalvik.system.VMRuntime; 187 188import libcore.io.IoUtils; 189import libcore.util.EmptyArray; 190 191import com.android.internal.R; 192import com.android.internal.app.IMediaContainerService; 193import com.android.internal.app.ResolverActivity; 194import com.android.internal.content.NativeLibraryHelper; 195import com.android.internal.content.PackageHelper; 196import com.android.internal.os.IParcelFileDescriptorFactory; 197import com.android.internal.os.SomeArgs; 198import com.android.internal.util.ArrayUtils; 199import com.android.internal.util.FastPrintWriter; 200import com.android.internal.util.FastXmlSerializer; 201import com.android.internal.util.IndentingPrintWriter; 202import com.android.internal.util.Preconditions; 203import com.android.server.EventLogTags; 204import com.android.server.FgThread; 205import com.android.server.IntentResolver; 206import com.android.server.LocalServices; 207import com.android.server.ServiceThread; 208import com.android.server.SystemConfig; 209import com.android.server.Watchdog; 210import com.android.server.pm.Settings.DatabaseVersion; 211import com.android.server.pm.PermissionsState.PermissionState; 212import com.android.server.storage.DeviceStorageMonitorInternal; 213 214import org.xmlpull.v1.XmlPullParser; 215import org.xmlpull.v1.XmlSerializer; 216 217import java.io.BufferedInputStream; 218import java.io.BufferedOutputStream; 219import java.io.BufferedReader; 220import java.io.ByteArrayInputStream; 221import java.io.ByteArrayOutputStream; 222import java.io.File; 223import java.io.FileDescriptor; 224import java.io.FileNotFoundException; 225import java.io.FileOutputStream; 226import java.io.FileReader; 227import java.io.FilenameFilter; 228import java.io.IOException; 229import java.io.InputStream; 230import java.io.PrintWriter; 231import java.nio.charset.StandardCharsets; 232import java.security.NoSuchAlgorithmException; 233import java.security.PublicKey; 234import java.security.cert.CertificateEncodingException; 235import java.security.cert.CertificateException; 236import java.text.SimpleDateFormat; 237import java.util.ArrayList; 238import java.util.Arrays; 239import java.util.Collection; 240import java.util.Collections; 241import java.util.Comparator; 242import java.util.Date; 243import java.util.Iterator; 244import java.util.List; 245import java.util.Map; 246import java.util.Objects; 247import java.util.Set; 248import java.util.concurrent.CountDownLatch; 249import java.util.concurrent.TimeUnit; 250import java.util.concurrent.atomic.AtomicBoolean; 251import java.util.concurrent.atomic.AtomicInteger; 252import java.util.concurrent.atomic.AtomicLong; 253 254/** 255 * Keep track of all those .apks everywhere. 256 * 257 * This is very central to the platform's security; please run the unit 258 * tests whenever making modifications here: 259 * 260mmm frameworks/base/tests/AndroidTests 261adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 262adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 263 * 264 * {@hide} 265 */ 266public class PackageManagerService extends IPackageManager.Stub { 267 static final String TAG = "PackageManager"; 268 static final boolean DEBUG_SETTINGS = false; 269 static final boolean DEBUG_PREFERRED = false; 270 static final boolean DEBUG_UPGRADE = false; 271 private static final boolean DEBUG_BACKUP = true; 272 private static final boolean DEBUG_INSTALL = false; 273 private static final boolean DEBUG_REMOVE = false; 274 private static final boolean DEBUG_BROADCASTS = false; 275 private static final boolean DEBUG_SHOW_INFO = false; 276 private static final boolean DEBUG_PACKAGE_INFO = false; 277 private static final boolean DEBUG_INTENT_MATCHING = false; 278 private static final boolean DEBUG_PACKAGE_SCANNING = false; 279 private static final boolean DEBUG_VERIFY = false; 280 private static final boolean DEBUG_DEXOPT = false; 281 private static final boolean DEBUG_ABI_SELECTION = false; 282 private static final boolean DEBUG_DOMAIN_VERIFICATION = false; 283 284 private static final int RADIO_UID = Process.PHONE_UID; 285 private static final int LOG_UID = Process.LOG_UID; 286 private static final int NFC_UID = Process.NFC_UID; 287 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 288 private static final int SHELL_UID = Process.SHELL_UID; 289 290 // Cap the size of permission trees that 3rd party apps can define 291 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 292 293 // Suffix used during package installation when copying/moving 294 // package apks to install directory. 295 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 296 297 static final int SCAN_NO_DEX = 1<<1; 298 static final int SCAN_FORCE_DEX = 1<<2; 299 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 300 static final int SCAN_NEW_INSTALL = 1<<4; 301 static final int SCAN_NO_PATHS = 1<<5; 302 static final int SCAN_UPDATE_TIME = 1<<6; 303 static final int SCAN_DEFER_DEX = 1<<7; 304 static final int SCAN_BOOTING = 1<<8; 305 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 306 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 307 static final int SCAN_REQUIRE_KNOWN = 1<<12; 308 static final int SCAN_MOVE = 1<<13; 309 310 static final int REMOVE_CHATTY = 1<<16; 311 312 private static final int[] EMPTY_INT_ARRAY = new int[0]; 313 314 /** 315 * Timeout (in milliseconds) after which the watchdog should declare that 316 * our handler thread is wedged. The usual default for such things is one 317 * minute but we sometimes do very lengthy I/O operations on this thread, 318 * such as installing multi-gigabyte applications, so ours needs to be longer. 319 */ 320 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 321 322 /** 323 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 324 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 325 * settings entry if available, otherwise we use the hardcoded default. If it's been 326 * more than this long since the last fstrim, we force one during the boot sequence. 327 * 328 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 329 * one gets run at the next available charging+idle time. This final mandatory 330 * no-fstrim check kicks in only of the other scheduling criteria is never met. 331 */ 332 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 333 334 /** 335 * Whether verification is enabled by default. 336 */ 337 private static final boolean DEFAULT_VERIFY_ENABLE = true; 338 339 /** 340 * The default maximum time to wait for the verification agent to return in 341 * milliseconds. 342 */ 343 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 344 345 /** 346 * The default response for package verification timeout. 347 * 348 * This can be either PackageManager.VERIFICATION_ALLOW or 349 * PackageManager.VERIFICATION_REJECT. 350 */ 351 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 352 353 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 354 355 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 356 DEFAULT_CONTAINER_PACKAGE, 357 "com.android.defcontainer.DefaultContainerService"); 358 359 private static final String KILL_APP_REASON_GIDS_CHANGED = 360 "permission grant or revoke changed gids"; 361 362 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 363 "permissions revoked"; 364 365 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 366 367 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 368 369 /** Permission grant: not grant the permission. */ 370 private static final int GRANT_DENIED = 1; 371 372 /** Permission grant: grant the permission as an install permission. */ 373 private static final int GRANT_INSTALL = 2; 374 375 /** Permission grant: grant the permission as an install permission for a legacy app. */ 376 private static final int GRANT_INSTALL_LEGACY = 3; 377 378 /** Permission grant: grant the permission as a runtime one. */ 379 private static final int GRANT_RUNTIME = 4; 380 381 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 382 private static final int GRANT_UPGRADE = 5; 383 384 final ServiceThread mHandlerThread; 385 386 final PackageHandler mHandler; 387 388 /** 389 * Messages for {@link #mHandler} that need to wait for system ready before 390 * being dispatched. 391 */ 392 private ArrayList<Message> mPostSystemReadyMessages; 393 394 final int mSdkVersion = Build.VERSION.SDK_INT; 395 396 final Context mContext; 397 final boolean mFactoryTest; 398 final boolean mOnlyCore; 399 final boolean mLazyDexOpt; 400 final long mDexOptLRUThresholdInMills; 401 final DisplayMetrics mMetrics; 402 final int mDefParseFlags; 403 final String[] mSeparateProcesses; 404 final boolean mIsUpgrade; 405 406 // This is where all application persistent data goes. 407 final File mAppDataDir; 408 409 // This is where all application persistent data goes for secondary users. 410 final File mUserAppDataDir; 411 412 /** The location for ASEC container files on internal storage. */ 413 final String mAsecInternalPath; 414 415 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 416 // LOCK HELD. Can be called with mInstallLock held. 417 final Installer mInstaller; 418 419 /** Directory where installed third-party apps stored */ 420 final File mAppInstallDir; 421 422 /** 423 * Directory to which applications installed internally have their 424 * 32 bit native libraries copied. 425 */ 426 private File mAppLib32InstallDir; 427 428 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 429 // apps. 430 final File mDrmAppPrivateInstallDir; 431 432 // ---------------------------------------------------------------- 433 434 // Lock for state used when installing and doing other long running 435 // operations. Methods that must be called with this lock held have 436 // the suffix "LI". 437 final Object mInstallLock = new Object(); 438 439 // ---------------------------------------------------------------- 440 441 // Keys are String (package name), values are Package. This also serves 442 // as the lock for the global state. Methods that must be called with 443 // this lock held have the prefix "LP". 444 final ArrayMap<String, PackageParser.Package> mPackages = 445 new ArrayMap<String, PackageParser.Package>(); 446 447 // Tracks available target package names -> overlay package paths. 448 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 449 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 450 451 final Settings mSettings; 452 boolean mRestoredSettings; 453 454 // System configuration read by SystemConfig. 455 final int[] mGlobalGids; 456 final SparseArray<ArraySet<String>> mSystemPermissions; 457 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 458 459 // If mac_permissions.xml was found for seinfo labeling. 460 boolean mFoundPolicyFile; 461 462 // If a recursive restorecon of /data/data/<pkg> is needed. 463 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 464 465 public static final class SharedLibraryEntry { 466 public final String path; 467 public final String apk; 468 469 SharedLibraryEntry(String _path, String _apk) { 470 path = _path; 471 apk = _apk; 472 } 473 } 474 475 // Currently known shared libraries. 476 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 477 new ArrayMap<String, SharedLibraryEntry>(); 478 479 // All available activities, for your resolving pleasure. 480 final ActivityIntentResolver mActivities = 481 new ActivityIntentResolver(); 482 483 // All available receivers, for your resolving pleasure. 484 final ActivityIntentResolver mReceivers = 485 new ActivityIntentResolver(); 486 487 // All available services, for your resolving pleasure. 488 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 489 490 // All available providers, for your resolving pleasure. 491 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 492 493 // Mapping from provider base names (first directory in content URI codePath) 494 // to the provider information. 495 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 496 new ArrayMap<String, PackageParser.Provider>(); 497 498 // Mapping from instrumentation class names to info about them. 499 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 500 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 501 502 // Mapping from permission names to info about them. 503 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 504 new ArrayMap<String, PackageParser.PermissionGroup>(); 505 506 // Packages whose data we have transfered into another package, thus 507 // should no longer exist. 508 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 509 510 // Broadcast actions that are only available to the system. 511 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 512 513 /** List of packages waiting for verification. */ 514 final SparseArray<PackageVerificationState> mPendingVerification 515 = new SparseArray<PackageVerificationState>(); 516 517 /** Set of packages associated with each app op permission. */ 518 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 519 520 final PackageInstallerService mInstallerService; 521 522 private final PackageDexOptimizer mPackageDexOptimizer; 523 524 private AtomicInteger mNextMoveId = new AtomicInteger(); 525 private final MoveCallbacks mMoveCallbacks; 526 527 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 528 529 // Cache of users who need badging. 530 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 531 532 /** Token for keys in mPendingVerification. */ 533 private int mPendingVerificationToken = 0; 534 535 volatile boolean mSystemReady; 536 volatile boolean mSafeMode; 537 volatile boolean mHasSystemUidErrors; 538 539 ApplicationInfo mAndroidApplication; 540 final ActivityInfo mResolveActivity = new ActivityInfo(); 541 final ResolveInfo mResolveInfo = new ResolveInfo(); 542 ComponentName mResolveComponentName; 543 PackageParser.Package mPlatformPackage; 544 ComponentName mCustomResolverComponentName; 545 546 boolean mResolverReplaced = false; 547 548 private final ComponentName mIntentFilterVerifierComponent; 549 private int mIntentFilterVerificationToken = 0; 550 551 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 552 = new SparseArray<IntentFilterVerificationState>(); 553 554 private interface IntentFilterVerifier<T extends IntentFilter> { 555 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 556 T filter, String packageName); 557 void startVerifications(int userId); 558 void receiveVerificationResponse(int verificationId); 559 } 560 561 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 562 private Context mContext; 563 private ComponentName mIntentFilterVerifierComponent; 564 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 565 566 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 567 mContext = context; 568 mIntentFilterVerifierComponent = verifierComponent; 569 } 570 571 private String getDefaultScheme() { 572 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 573 return IntentFilter.SCHEME_HTTP; 574 } 575 576 @Override 577 public void startVerifications(int userId) { 578 // Launch verifications requests 579 int count = mCurrentIntentFilterVerifications.size(); 580 for (int n=0; n<count; n++) { 581 int verificationId = mCurrentIntentFilterVerifications.get(n); 582 final IntentFilterVerificationState ivs = 583 mIntentFilterVerificationStates.get(verificationId); 584 585 String packageName = ivs.getPackageName(); 586 587 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 588 final int filterCount = filters.size(); 589 ArraySet<String> domainsSet = new ArraySet<>(); 590 for (int m=0; m<filterCount; m++) { 591 PackageParser.ActivityIntentInfo filter = filters.get(m); 592 domainsSet.addAll(filter.getHostsList()); 593 } 594 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 595 synchronized (mPackages) { 596 if (mSettings.createIntentFilterVerificationIfNeededLPw( 597 packageName, domainsList) != null) { 598 scheduleWriteSettingsLocked(); 599 } 600 } 601 sendVerificationRequest(userId, verificationId, ivs); 602 } 603 mCurrentIntentFilterVerifications.clear(); 604 } 605 606 private void sendVerificationRequest(int userId, int verificationId, 607 IntentFilterVerificationState ivs) { 608 609 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 610 verificationIntent.putExtra( 611 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 612 verificationId); 613 verificationIntent.putExtra( 614 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 615 getDefaultScheme()); 616 verificationIntent.putExtra( 617 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 618 ivs.getHostsString()); 619 verificationIntent.putExtra( 620 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 621 ivs.getPackageName()); 622 verificationIntent.setComponent(mIntentFilterVerifierComponent); 623 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 624 625 UserHandle user = new UserHandle(userId); 626 mContext.sendBroadcastAsUser(verificationIntent, user); 627 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 628 "Sending IntenFilter verification broadcast"); 629 } 630 631 public void receiveVerificationResponse(int verificationId) { 632 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 633 634 final boolean verified = ivs.isVerified(); 635 636 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 637 final int count = filters.size(); 638 for (int n=0; n<count; n++) { 639 PackageParser.ActivityIntentInfo filter = filters.get(n); 640 filter.setVerified(verified); 641 642 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 643 + " verified with result:" + verified + " and hosts:" 644 + ivs.getHostsString()); 645 } 646 647 mIntentFilterVerificationStates.remove(verificationId); 648 649 final String packageName = ivs.getPackageName(); 650 IntentFilterVerificationInfo ivi = null; 651 652 synchronized (mPackages) { 653 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 654 } 655 if (ivi == null) { 656 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 657 + verificationId + " packageName:" + packageName); 658 return; 659 } 660 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 661 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 662 663 synchronized (mPackages) { 664 if (verified) { 665 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 666 } else { 667 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 668 } 669 scheduleWriteSettingsLocked(); 670 671 final int userId = ivs.getUserId(); 672 if (userId != UserHandle.USER_ALL) { 673 final int userStatus = 674 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 675 676 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 677 boolean needUpdate = false; 678 679 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 680 // already been set by the User thru the Disambiguation dialog 681 switch (userStatus) { 682 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 683 if (verified) { 684 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 685 } else { 686 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 687 } 688 needUpdate = true; 689 break; 690 691 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 692 if (verified) { 693 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 694 needUpdate = true; 695 } 696 break; 697 698 default: 699 // Nothing to do 700 } 701 702 if (needUpdate) { 703 mSettings.updateIntentFilterVerificationStatusLPw( 704 packageName, updatedStatus, userId); 705 scheduleWritePackageRestrictionsLocked(userId); 706 } 707 } 708 } 709 } 710 711 @Override 712 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 713 ActivityIntentInfo filter, String packageName) { 714 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 715 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 716 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 717 "IntentFilter does not contain HTTP nor HTTPS data scheme"); 718 return false; 719 } 720 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 721 if (ivs == null) { 722 ivs = createDomainVerificationState(verifierId, userId, verificationId, 723 packageName); 724 } 725 if (!hasValidDomains(filter)) { 726 return false; 727 } 728 ivs.addFilter(filter); 729 return true; 730 } 731 732 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 733 int userId, int verificationId, String packageName) { 734 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 735 verifierId, userId, packageName); 736 ivs.setPendingState(); 737 synchronized (mPackages) { 738 mIntentFilterVerificationStates.append(verificationId, ivs); 739 mCurrentIntentFilterVerifications.add(verificationId); 740 } 741 return ivs; 742 } 743 } 744 745 private static boolean hasValidDomains(ActivityIntentInfo filter) { 746 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 747 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 748 if (!hasHTTPorHTTPS) { 749 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 750 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 751 return false; 752 } 753 return true; 754 } 755 756 private IntentFilterVerifier mIntentFilterVerifier; 757 758 // Set of pending broadcasts for aggregating enable/disable of components. 759 static class PendingPackageBroadcasts { 760 // for each user id, a map of <package name -> components within that package> 761 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 762 763 public PendingPackageBroadcasts() { 764 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 765 } 766 767 public ArrayList<String> get(int userId, String packageName) { 768 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 769 return packages.get(packageName); 770 } 771 772 public void put(int userId, String packageName, ArrayList<String> components) { 773 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 774 packages.put(packageName, components); 775 } 776 777 public void remove(int userId, String packageName) { 778 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 779 if (packages != null) { 780 packages.remove(packageName); 781 } 782 } 783 784 public void remove(int userId) { 785 mUidMap.remove(userId); 786 } 787 788 public int userIdCount() { 789 return mUidMap.size(); 790 } 791 792 public int userIdAt(int n) { 793 return mUidMap.keyAt(n); 794 } 795 796 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 797 return mUidMap.get(userId); 798 } 799 800 public int size() { 801 // total number of pending broadcast entries across all userIds 802 int num = 0; 803 for (int i = 0; i< mUidMap.size(); i++) { 804 num += mUidMap.valueAt(i).size(); 805 } 806 return num; 807 } 808 809 public void clear() { 810 mUidMap.clear(); 811 } 812 813 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 814 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 815 if (map == null) { 816 map = new ArrayMap<String, ArrayList<String>>(); 817 mUidMap.put(userId, map); 818 } 819 return map; 820 } 821 } 822 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 823 824 // Service Connection to remote media container service to copy 825 // package uri's from external media onto secure containers 826 // or internal storage. 827 private IMediaContainerService mContainerService = null; 828 829 static final int SEND_PENDING_BROADCAST = 1; 830 static final int MCS_BOUND = 3; 831 static final int END_COPY = 4; 832 static final int INIT_COPY = 5; 833 static final int MCS_UNBIND = 6; 834 static final int START_CLEANING_PACKAGE = 7; 835 static final int FIND_INSTALL_LOC = 8; 836 static final int POST_INSTALL = 9; 837 static final int MCS_RECONNECT = 10; 838 static final int MCS_GIVE_UP = 11; 839 static final int UPDATED_MEDIA_STATUS = 12; 840 static final int WRITE_SETTINGS = 13; 841 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 842 static final int PACKAGE_VERIFIED = 15; 843 static final int CHECK_PENDING_VERIFICATION = 16; 844 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 845 static final int INTENT_FILTER_VERIFIED = 18; 846 847 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 848 849 // Delay time in millisecs 850 static final int BROADCAST_DELAY = 10 * 1000; 851 852 static UserManagerService sUserManager; 853 854 // Stores a list of users whose package restrictions file needs to be updated 855 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 856 857 final private DefaultContainerConnection mDefContainerConn = 858 new DefaultContainerConnection(); 859 class DefaultContainerConnection implements ServiceConnection { 860 public void onServiceConnected(ComponentName name, IBinder service) { 861 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 862 IMediaContainerService imcs = 863 IMediaContainerService.Stub.asInterface(service); 864 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 865 } 866 867 public void onServiceDisconnected(ComponentName name) { 868 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 869 } 870 }; 871 872 // Recordkeeping of restore-after-install operations that are currently in flight 873 // between the Package Manager and the Backup Manager 874 class PostInstallData { 875 public InstallArgs args; 876 public PackageInstalledInfo res; 877 878 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 879 args = _a; 880 res = _r; 881 } 882 }; 883 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 884 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 885 886 // backup/restore of preferred activity state 887 private static final String TAG_PREFERRED_BACKUP = "pa"; 888 889 private final String mRequiredVerifierPackage; 890 891 private final PackageUsage mPackageUsage = new PackageUsage(); 892 893 private class PackageUsage { 894 private static final int WRITE_INTERVAL 895 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 896 897 private final Object mFileLock = new Object(); 898 private final AtomicLong mLastWritten = new AtomicLong(0); 899 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 900 901 private boolean mIsHistoricalPackageUsageAvailable = true; 902 903 boolean isHistoricalPackageUsageAvailable() { 904 return mIsHistoricalPackageUsageAvailable; 905 } 906 907 void write(boolean force) { 908 if (force) { 909 writeInternal(); 910 return; 911 } 912 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 913 && !DEBUG_DEXOPT) { 914 return; 915 } 916 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 917 new Thread("PackageUsage_DiskWriter") { 918 @Override 919 public void run() { 920 try { 921 writeInternal(); 922 } finally { 923 mBackgroundWriteRunning.set(false); 924 } 925 } 926 }.start(); 927 } 928 } 929 930 private void writeInternal() { 931 synchronized (mPackages) { 932 synchronized (mFileLock) { 933 AtomicFile file = getFile(); 934 FileOutputStream f = null; 935 try { 936 f = file.startWrite(); 937 BufferedOutputStream out = new BufferedOutputStream(f); 938 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 939 StringBuilder sb = new StringBuilder(); 940 for (PackageParser.Package pkg : mPackages.values()) { 941 if (pkg.mLastPackageUsageTimeInMills == 0) { 942 continue; 943 } 944 sb.setLength(0); 945 sb.append(pkg.packageName); 946 sb.append(' '); 947 sb.append((long)pkg.mLastPackageUsageTimeInMills); 948 sb.append('\n'); 949 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 950 } 951 out.flush(); 952 file.finishWrite(f); 953 } catch (IOException e) { 954 if (f != null) { 955 file.failWrite(f); 956 } 957 Log.e(TAG, "Failed to write package usage times", e); 958 } 959 } 960 } 961 mLastWritten.set(SystemClock.elapsedRealtime()); 962 } 963 964 void readLP() { 965 synchronized (mFileLock) { 966 AtomicFile file = getFile(); 967 BufferedInputStream in = null; 968 try { 969 in = new BufferedInputStream(file.openRead()); 970 StringBuffer sb = new StringBuffer(); 971 while (true) { 972 String packageName = readToken(in, sb, ' '); 973 if (packageName == null) { 974 break; 975 } 976 String timeInMillisString = readToken(in, sb, '\n'); 977 if (timeInMillisString == null) { 978 throw new IOException("Failed to find last usage time for package " 979 + packageName); 980 } 981 PackageParser.Package pkg = mPackages.get(packageName); 982 if (pkg == null) { 983 continue; 984 } 985 long timeInMillis; 986 try { 987 timeInMillis = Long.parseLong(timeInMillisString.toString()); 988 } catch (NumberFormatException e) { 989 throw new IOException("Failed to parse " + timeInMillisString 990 + " as a long.", e); 991 } 992 pkg.mLastPackageUsageTimeInMills = timeInMillis; 993 } 994 } catch (FileNotFoundException expected) { 995 mIsHistoricalPackageUsageAvailable = false; 996 } catch (IOException e) { 997 Log.w(TAG, "Failed to read package usage times", e); 998 } finally { 999 IoUtils.closeQuietly(in); 1000 } 1001 } 1002 mLastWritten.set(SystemClock.elapsedRealtime()); 1003 } 1004 1005 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1006 throws IOException { 1007 sb.setLength(0); 1008 while (true) { 1009 int ch = in.read(); 1010 if (ch == -1) { 1011 if (sb.length() == 0) { 1012 return null; 1013 } 1014 throw new IOException("Unexpected EOF"); 1015 } 1016 if (ch == endOfToken) { 1017 return sb.toString(); 1018 } 1019 sb.append((char)ch); 1020 } 1021 } 1022 1023 private AtomicFile getFile() { 1024 File dataDir = Environment.getDataDirectory(); 1025 File systemDir = new File(dataDir, "system"); 1026 File fname = new File(systemDir, "package-usage.list"); 1027 return new AtomicFile(fname); 1028 } 1029 } 1030 1031 class PackageHandler extends Handler { 1032 private boolean mBound = false; 1033 final ArrayList<HandlerParams> mPendingInstalls = 1034 new ArrayList<HandlerParams>(); 1035 1036 private boolean connectToService() { 1037 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1038 " DefaultContainerService"); 1039 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1040 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1041 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1042 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1043 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1044 mBound = true; 1045 return true; 1046 } 1047 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1048 return false; 1049 } 1050 1051 private void disconnectService() { 1052 mContainerService = null; 1053 mBound = false; 1054 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1055 mContext.unbindService(mDefContainerConn); 1056 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1057 } 1058 1059 PackageHandler(Looper looper) { 1060 super(looper); 1061 } 1062 1063 public void handleMessage(Message msg) { 1064 try { 1065 doHandleMessage(msg); 1066 } finally { 1067 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1068 } 1069 } 1070 1071 void doHandleMessage(Message msg) { 1072 switch (msg.what) { 1073 case INIT_COPY: { 1074 HandlerParams params = (HandlerParams) msg.obj; 1075 int idx = mPendingInstalls.size(); 1076 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1077 // If a bind was already initiated we dont really 1078 // need to do anything. The pending install 1079 // will be processed later on. 1080 if (!mBound) { 1081 // If this is the only one pending we might 1082 // have to bind to the service again. 1083 if (!connectToService()) { 1084 Slog.e(TAG, "Failed to bind to media container service"); 1085 params.serviceError(); 1086 return; 1087 } else { 1088 // Once we bind to the service, the first 1089 // pending request will be processed. 1090 mPendingInstalls.add(idx, params); 1091 } 1092 } else { 1093 mPendingInstalls.add(idx, params); 1094 // Already bound to the service. Just make 1095 // sure we trigger off processing the first request. 1096 if (idx == 0) { 1097 mHandler.sendEmptyMessage(MCS_BOUND); 1098 } 1099 } 1100 break; 1101 } 1102 case MCS_BOUND: { 1103 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1104 if (msg.obj != null) { 1105 mContainerService = (IMediaContainerService) msg.obj; 1106 } 1107 if (mContainerService == null) { 1108 // Something seriously wrong. Bail out 1109 Slog.e(TAG, "Cannot bind to media container service"); 1110 for (HandlerParams params : mPendingInstalls) { 1111 // Indicate service bind error 1112 params.serviceError(); 1113 } 1114 mPendingInstalls.clear(); 1115 } else if (mPendingInstalls.size() > 0) { 1116 HandlerParams params = mPendingInstalls.get(0); 1117 if (params != null) { 1118 if (params.startCopy()) { 1119 // We are done... look for more work or to 1120 // go idle. 1121 if (DEBUG_SD_INSTALL) Log.i(TAG, 1122 "Checking for more work or unbind..."); 1123 // Delete pending install 1124 if (mPendingInstalls.size() > 0) { 1125 mPendingInstalls.remove(0); 1126 } 1127 if (mPendingInstalls.size() == 0) { 1128 if (mBound) { 1129 if (DEBUG_SD_INSTALL) Log.i(TAG, 1130 "Posting delayed MCS_UNBIND"); 1131 removeMessages(MCS_UNBIND); 1132 Message ubmsg = obtainMessage(MCS_UNBIND); 1133 // Unbind after a little delay, to avoid 1134 // continual thrashing. 1135 sendMessageDelayed(ubmsg, 10000); 1136 } 1137 } else { 1138 // There are more pending requests in queue. 1139 // Just post MCS_BOUND message to trigger processing 1140 // of next pending install. 1141 if (DEBUG_SD_INSTALL) Log.i(TAG, 1142 "Posting MCS_BOUND for next work"); 1143 mHandler.sendEmptyMessage(MCS_BOUND); 1144 } 1145 } 1146 } 1147 } else { 1148 // Should never happen ideally. 1149 Slog.w(TAG, "Empty queue"); 1150 } 1151 break; 1152 } 1153 case MCS_RECONNECT: { 1154 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1155 if (mPendingInstalls.size() > 0) { 1156 if (mBound) { 1157 disconnectService(); 1158 } 1159 if (!connectToService()) { 1160 Slog.e(TAG, "Failed to bind to media container service"); 1161 for (HandlerParams params : mPendingInstalls) { 1162 // Indicate service bind error 1163 params.serviceError(); 1164 } 1165 mPendingInstalls.clear(); 1166 } 1167 } 1168 break; 1169 } 1170 case MCS_UNBIND: { 1171 // If there is no actual work left, then time to unbind. 1172 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1173 1174 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1175 if (mBound) { 1176 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1177 1178 disconnectService(); 1179 } 1180 } else if (mPendingInstalls.size() > 0) { 1181 // There are more pending requests in queue. 1182 // Just post MCS_BOUND message to trigger processing 1183 // of next pending install. 1184 mHandler.sendEmptyMessage(MCS_BOUND); 1185 } 1186 1187 break; 1188 } 1189 case MCS_GIVE_UP: { 1190 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1191 mPendingInstalls.remove(0); 1192 break; 1193 } 1194 case SEND_PENDING_BROADCAST: { 1195 String packages[]; 1196 ArrayList<String> components[]; 1197 int size = 0; 1198 int uids[]; 1199 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1200 synchronized (mPackages) { 1201 if (mPendingBroadcasts == null) { 1202 return; 1203 } 1204 size = mPendingBroadcasts.size(); 1205 if (size <= 0) { 1206 // Nothing to be done. Just return 1207 return; 1208 } 1209 packages = new String[size]; 1210 components = new ArrayList[size]; 1211 uids = new int[size]; 1212 int i = 0; // filling out the above arrays 1213 1214 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1215 int packageUserId = mPendingBroadcasts.userIdAt(n); 1216 Iterator<Map.Entry<String, ArrayList<String>>> it 1217 = mPendingBroadcasts.packagesForUserId(packageUserId) 1218 .entrySet().iterator(); 1219 while (it.hasNext() && i < size) { 1220 Map.Entry<String, ArrayList<String>> ent = it.next(); 1221 packages[i] = ent.getKey(); 1222 components[i] = ent.getValue(); 1223 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1224 uids[i] = (ps != null) 1225 ? UserHandle.getUid(packageUserId, ps.appId) 1226 : -1; 1227 i++; 1228 } 1229 } 1230 size = i; 1231 mPendingBroadcasts.clear(); 1232 } 1233 // Send broadcasts 1234 for (int i = 0; i < size; i++) { 1235 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1236 } 1237 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1238 break; 1239 } 1240 case START_CLEANING_PACKAGE: { 1241 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1242 final String packageName = (String)msg.obj; 1243 final int userId = msg.arg1; 1244 final boolean andCode = msg.arg2 != 0; 1245 synchronized (mPackages) { 1246 if (userId == UserHandle.USER_ALL) { 1247 int[] users = sUserManager.getUserIds(); 1248 for (int user : users) { 1249 mSettings.addPackageToCleanLPw( 1250 new PackageCleanItem(user, packageName, andCode)); 1251 } 1252 } else { 1253 mSettings.addPackageToCleanLPw( 1254 new PackageCleanItem(userId, packageName, andCode)); 1255 } 1256 } 1257 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1258 startCleaningPackages(); 1259 } break; 1260 case POST_INSTALL: { 1261 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1262 PostInstallData data = mRunningInstalls.get(msg.arg1); 1263 mRunningInstalls.delete(msg.arg1); 1264 boolean deleteOld = false; 1265 1266 if (data != null) { 1267 InstallArgs args = data.args; 1268 PackageInstalledInfo res = data.res; 1269 1270 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1271 res.removedInfo.sendBroadcast(false, true, false); 1272 Bundle extras = new Bundle(1); 1273 extras.putInt(Intent.EXTRA_UID, res.uid); 1274 1275 // Now that we successfully installed the package, grant runtime 1276 // permissions if requested before broadcasting the install. 1277 if ((args.installFlags 1278 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1279 grantRequestedRuntimePermissions(res.pkg, 1280 args.user.getIdentifier()); 1281 } 1282 1283 // Determine the set of users who are adding this 1284 // package for the first time vs. those who are seeing 1285 // an update. 1286 int[] firstUsers; 1287 int[] updateUsers = new int[0]; 1288 if (res.origUsers == null || res.origUsers.length == 0) { 1289 firstUsers = res.newUsers; 1290 } else { 1291 firstUsers = new int[0]; 1292 for (int i=0; i<res.newUsers.length; i++) { 1293 int user = res.newUsers[i]; 1294 boolean isNew = true; 1295 for (int j=0; j<res.origUsers.length; j++) { 1296 if (res.origUsers[j] == user) { 1297 isNew = false; 1298 break; 1299 } 1300 } 1301 if (isNew) { 1302 int[] newFirst = new int[firstUsers.length+1]; 1303 System.arraycopy(firstUsers, 0, newFirst, 0, 1304 firstUsers.length); 1305 newFirst[firstUsers.length] = user; 1306 firstUsers = newFirst; 1307 } else { 1308 int[] newUpdate = new int[updateUsers.length+1]; 1309 System.arraycopy(updateUsers, 0, newUpdate, 0, 1310 updateUsers.length); 1311 newUpdate[updateUsers.length] = user; 1312 updateUsers = newUpdate; 1313 } 1314 } 1315 } 1316 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1317 res.pkg.applicationInfo.packageName, 1318 extras, null, null, firstUsers); 1319 final boolean update = res.removedInfo.removedPackage != null; 1320 if (update) { 1321 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1322 } 1323 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1324 res.pkg.applicationInfo.packageName, 1325 extras, null, null, updateUsers); 1326 if (update) { 1327 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1328 res.pkg.applicationInfo.packageName, 1329 extras, null, null, updateUsers); 1330 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1331 null, null, 1332 res.pkg.applicationInfo.packageName, null, updateUsers); 1333 1334 // treat asec-hosted packages like removable media on upgrade 1335 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1336 if (DEBUG_INSTALL) { 1337 Slog.i(TAG, "upgrading pkg " + res.pkg 1338 + " is ASEC-hosted -> AVAILABLE"); 1339 } 1340 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1341 ArrayList<String> pkgList = new ArrayList<String>(1); 1342 pkgList.add(res.pkg.applicationInfo.packageName); 1343 sendResourcesChangedBroadcast(true, true, 1344 pkgList,uidArray, null); 1345 } 1346 } 1347 if (res.removedInfo.args != null) { 1348 // Remove the replaced package's older resources safely now 1349 deleteOld = true; 1350 } 1351 1352 // Log current value of "unknown sources" setting 1353 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1354 getUnknownSourcesSettings()); 1355 } 1356 // Force a gc to clear up things 1357 Runtime.getRuntime().gc(); 1358 // We delete after a gc for applications on sdcard. 1359 if (deleteOld) { 1360 synchronized (mInstallLock) { 1361 res.removedInfo.args.doPostDeleteLI(true); 1362 } 1363 } 1364 if (args.observer != null) { 1365 try { 1366 Bundle extras = extrasForInstallResult(res); 1367 args.observer.onPackageInstalled(res.name, res.returnCode, 1368 res.returnMsg, extras); 1369 } catch (RemoteException e) { 1370 Slog.i(TAG, "Observer no longer exists."); 1371 } 1372 } 1373 } else { 1374 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1375 } 1376 } break; 1377 case UPDATED_MEDIA_STATUS: { 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1379 boolean reportStatus = msg.arg1 == 1; 1380 boolean doGc = msg.arg2 == 1; 1381 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1382 if (doGc) { 1383 // Force a gc to clear up stale containers. 1384 Runtime.getRuntime().gc(); 1385 } 1386 if (msg.obj != null) { 1387 @SuppressWarnings("unchecked") 1388 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1389 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1390 // Unload containers 1391 unloadAllContainers(args); 1392 } 1393 if (reportStatus) { 1394 try { 1395 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1396 PackageHelper.getMountService().finishMediaUpdate(); 1397 } catch (RemoteException e) { 1398 Log.e(TAG, "MountService not running?"); 1399 } 1400 } 1401 } break; 1402 case WRITE_SETTINGS: { 1403 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1404 synchronized (mPackages) { 1405 removeMessages(WRITE_SETTINGS); 1406 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1407 mSettings.writeLPr(); 1408 mDirtyUsers.clear(); 1409 } 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1411 } break; 1412 case WRITE_PACKAGE_RESTRICTIONS: { 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 synchronized (mPackages) { 1415 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1416 for (int userId : mDirtyUsers) { 1417 mSettings.writePackageRestrictionsLPr(userId); 1418 } 1419 mDirtyUsers.clear(); 1420 } 1421 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1422 } break; 1423 case CHECK_PENDING_VERIFICATION: { 1424 final int verificationId = msg.arg1; 1425 final PackageVerificationState state = mPendingVerification.get(verificationId); 1426 1427 if ((state != null) && !state.timeoutExtended()) { 1428 final InstallArgs args = state.getInstallArgs(); 1429 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1430 1431 Slog.i(TAG, "Verification timed out for " + originUri); 1432 mPendingVerification.remove(verificationId); 1433 1434 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1435 1436 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1437 Slog.i(TAG, "Continuing with installation of " + originUri); 1438 state.setVerifierResponse(Binder.getCallingUid(), 1439 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1440 broadcastPackageVerified(verificationId, originUri, 1441 PackageManager.VERIFICATION_ALLOW, 1442 state.getInstallArgs().getUser()); 1443 try { 1444 ret = args.copyApk(mContainerService, true); 1445 } catch (RemoteException e) { 1446 Slog.e(TAG, "Could not contact the ContainerService"); 1447 } 1448 } else { 1449 broadcastPackageVerified(verificationId, originUri, 1450 PackageManager.VERIFICATION_REJECT, 1451 state.getInstallArgs().getUser()); 1452 } 1453 1454 processPendingInstall(args, ret); 1455 mHandler.sendEmptyMessage(MCS_UNBIND); 1456 } 1457 break; 1458 } 1459 case PACKAGE_VERIFIED: { 1460 final int verificationId = msg.arg1; 1461 1462 final PackageVerificationState state = mPendingVerification.get(verificationId); 1463 if (state == null) { 1464 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1465 break; 1466 } 1467 1468 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1469 1470 state.setVerifierResponse(response.callerUid, response.code); 1471 1472 if (state.isVerificationComplete()) { 1473 mPendingVerification.remove(verificationId); 1474 1475 final InstallArgs args = state.getInstallArgs(); 1476 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1477 1478 int ret; 1479 if (state.isInstallAllowed()) { 1480 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1481 broadcastPackageVerified(verificationId, originUri, 1482 response.code, state.getInstallArgs().getUser()); 1483 try { 1484 ret = args.copyApk(mContainerService, true); 1485 } catch (RemoteException e) { 1486 Slog.e(TAG, "Could not contact the ContainerService"); 1487 } 1488 } else { 1489 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1490 } 1491 1492 processPendingInstall(args, ret); 1493 1494 mHandler.sendEmptyMessage(MCS_UNBIND); 1495 } 1496 1497 break; 1498 } 1499 case START_INTENT_FILTER_VERIFICATIONS: { 1500 int userId = msg.arg1; 1501 int verifierUid = msg.arg2; 1502 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1503 1504 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1505 break; 1506 } 1507 case INTENT_FILTER_VERIFIED: { 1508 final int verificationId = msg.arg1; 1509 1510 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1511 verificationId); 1512 if (state == null) { 1513 Slog.w(TAG, "Invalid IntentFilter verification token " 1514 + verificationId + " received"); 1515 break; 1516 } 1517 1518 final int userId = state.getUserId(); 1519 1520 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1521 "Processing IntentFilter verification with token:" 1522 + verificationId + " and userId:" + userId); 1523 1524 final IntentFilterVerificationResponse response = 1525 (IntentFilterVerificationResponse) msg.obj; 1526 1527 state.setVerifierResponse(response.callerUid, response.code); 1528 1529 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1530 "IntentFilter verification with token:" + verificationId 1531 + " and userId:" + userId 1532 + " is settings verifier response with response code:" 1533 + response.code); 1534 1535 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1536 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1537 + response.getFailedDomainsString()); 1538 } 1539 1540 if (state.isVerificationComplete()) { 1541 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1542 } else { 1543 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1544 "IntentFilter verification with token:" + verificationId 1545 + " was not said to be complete"); 1546 } 1547 1548 break; 1549 } 1550 } 1551 } 1552 } 1553 1554 private StorageEventListener mStorageListener = new StorageEventListener() { 1555 @Override 1556 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1557 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1558 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1559 // TODO: ensure that private directories exist for all active users 1560 // TODO: remove user data whose serial number doesn't match 1561 loadPrivatePackages(vol); 1562 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1563 unloadPrivatePackages(vol); 1564 } 1565 } 1566 1567 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1568 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1569 updateExternalMediaStatus(true, false); 1570 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1571 updateExternalMediaStatus(false, false); 1572 } 1573 } 1574 } 1575 1576 @Override 1577 public void onVolumeForgotten(String fsUuid) { 1578 // TODO: remove all packages hosted on this uuid 1579 } 1580 }; 1581 1582 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1583 if (userId >= UserHandle.USER_OWNER) { 1584 grantRequestedRuntimePermissionsForUser(pkg, userId); 1585 } else if (userId == UserHandle.USER_ALL) { 1586 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1587 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1588 } 1589 } 1590 } 1591 1592 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1593 SettingBase sb = (SettingBase) pkg.mExtras; 1594 if (sb == null) { 1595 return; 1596 } 1597 1598 PermissionsState permissionsState = sb.getPermissionsState(); 1599 1600 for (String permission : pkg.requestedPermissions) { 1601 BasePermission bp = mSettings.mPermissions.get(permission); 1602 if (bp != null && bp.isRuntime()) { 1603 permissionsState.grantRuntimePermission(bp, userId); 1604 } 1605 } 1606 } 1607 1608 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1609 Bundle extras = null; 1610 switch (res.returnCode) { 1611 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1612 extras = new Bundle(); 1613 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1614 res.origPermission); 1615 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1616 res.origPackage); 1617 break; 1618 } 1619 case PackageManager.INSTALL_SUCCEEDED: { 1620 extras = new Bundle(); 1621 extras.putBoolean(Intent.EXTRA_REPLACING, 1622 res.removedInfo != null && res.removedInfo.removedPackage != null); 1623 break; 1624 } 1625 } 1626 return extras; 1627 } 1628 1629 void scheduleWriteSettingsLocked() { 1630 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1631 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1632 } 1633 } 1634 1635 void scheduleWritePackageRestrictionsLocked(int userId) { 1636 if (!sUserManager.exists(userId)) return; 1637 mDirtyUsers.add(userId); 1638 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1639 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1640 } 1641 } 1642 1643 public static PackageManagerService main(Context context, Installer installer, 1644 boolean factoryTest, boolean onlyCore) { 1645 PackageManagerService m = new PackageManagerService(context, installer, 1646 factoryTest, onlyCore); 1647 ServiceManager.addService("package", m); 1648 return m; 1649 } 1650 1651 static String[] splitString(String str, char sep) { 1652 int count = 1; 1653 int i = 0; 1654 while ((i=str.indexOf(sep, i)) >= 0) { 1655 count++; 1656 i++; 1657 } 1658 1659 String[] res = new String[count]; 1660 i=0; 1661 count = 0; 1662 int lastI=0; 1663 while ((i=str.indexOf(sep, i)) >= 0) { 1664 res[count] = str.substring(lastI, i); 1665 count++; 1666 i++; 1667 lastI = i; 1668 } 1669 res[count] = str.substring(lastI, str.length()); 1670 return res; 1671 } 1672 1673 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1674 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1675 Context.DISPLAY_SERVICE); 1676 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1677 } 1678 1679 public PackageManagerService(Context context, Installer installer, 1680 boolean factoryTest, boolean onlyCore) { 1681 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1682 SystemClock.uptimeMillis()); 1683 1684 if (mSdkVersion <= 0) { 1685 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1686 } 1687 1688 mContext = context; 1689 mFactoryTest = factoryTest; 1690 mOnlyCore = onlyCore; 1691 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1692 mMetrics = new DisplayMetrics(); 1693 mSettings = new Settings(mPackages); 1694 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1695 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1696 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1697 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1698 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1699 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1700 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1701 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1702 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1703 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1704 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1705 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1706 1707 // TODO: add a property to control this? 1708 long dexOptLRUThresholdInMinutes; 1709 if (mLazyDexOpt) { 1710 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1711 } else { 1712 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1713 } 1714 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1715 1716 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1717 if (separateProcesses != null && separateProcesses.length() > 0) { 1718 if ("*".equals(separateProcesses)) { 1719 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1720 mSeparateProcesses = null; 1721 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1722 } else { 1723 mDefParseFlags = 0; 1724 mSeparateProcesses = separateProcesses.split(","); 1725 Slog.w(TAG, "Running with debug.separate_processes: " 1726 + separateProcesses); 1727 } 1728 } else { 1729 mDefParseFlags = 0; 1730 mSeparateProcesses = null; 1731 } 1732 1733 mInstaller = installer; 1734 mPackageDexOptimizer = new PackageDexOptimizer(this); 1735 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1736 1737 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1738 FgThread.get().getLooper()); 1739 1740 getDefaultDisplayMetrics(context, mMetrics); 1741 1742 SystemConfig systemConfig = SystemConfig.getInstance(); 1743 mGlobalGids = systemConfig.getGlobalGids(); 1744 mSystemPermissions = systemConfig.getSystemPermissions(); 1745 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1746 1747 synchronized (mInstallLock) { 1748 // writer 1749 synchronized (mPackages) { 1750 mHandlerThread = new ServiceThread(TAG, 1751 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1752 mHandlerThread.start(); 1753 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1754 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1755 1756 File dataDir = Environment.getDataDirectory(); 1757 mAppDataDir = new File(dataDir, "data"); 1758 mAppInstallDir = new File(dataDir, "app"); 1759 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1760 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1761 mUserAppDataDir = new File(dataDir, "user"); 1762 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1763 1764 sUserManager = new UserManagerService(context, this, 1765 mInstallLock, mPackages); 1766 1767 // Propagate permission configuration in to package manager. 1768 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1769 = systemConfig.getPermissions(); 1770 for (int i=0; i<permConfig.size(); i++) { 1771 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1772 BasePermission bp = mSettings.mPermissions.get(perm.name); 1773 if (bp == null) { 1774 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1775 mSettings.mPermissions.put(perm.name, bp); 1776 } 1777 if (perm.gids != null) { 1778 bp.setGids(perm.gids, perm.perUser); 1779 } 1780 } 1781 1782 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1783 for (int i=0; i<libConfig.size(); i++) { 1784 mSharedLibraries.put(libConfig.keyAt(i), 1785 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1786 } 1787 1788 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1789 1790 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1791 mSdkVersion, mOnlyCore); 1792 1793 String customResolverActivity = Resources.getSystem().getString( 1794 R.string.config_customResolverActivity); 1795 if (TextUtils.isEmpty(customResolverActivity)) { 1796 customResolverActivity = null; 1797 } else { 1798 mCustomResolverComponentName = ComponentName.unflattenFromString( 1799 customResolverActivity); 1800 } 1801 1802 long startTime = SystemClock.uptimeMillis(); 1803 1804 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1805 startTime); 1806 1807 // Set flag to monitor and not change apk file paths when 1808 // scanning install directories. 1809 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1810 1811 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1812 1813 /** 1814 * Add everything in the in the boot class path to the 1815 * list of process files because dexopt will have been run 1816 * if necessary during zygote startup. 1817 */ 1818 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1819 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1820 1821 if (bootClassPath != null) { 1822 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1823 for (String element : bootClassPathElements) { 1824 alreadyDexOpted.add(element); 1825 } 1826 } else { 1827 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1828 } 1829 1830 if (systemServerClassPath != null) { 1831 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1832 for (String element : systemServerClassPathElements) { 1833 alreadyDexOpted.add(element); 1834 } 1835 } else { 1836 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1837 } 1838 1839 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1840 final String[] dexCodeInstructionSets = 1841 getDexCodeInstructionSets( 1842 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1843 1844 /** 1845 * Ensure all external libraries have had dexopt run on them. 1846 */ 1847 if (mSharedLibraries.size() > 0) { 1848 // NOTE: For now, we're compiling these system "shared libraries" 1849 // (and framework jars) into all available architectures. It's possible 1850 // to compile them only when we come across an app that uses them (there's 1851 // already logic for that in scanPackageLI) but that adds some complexity. 1852 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1853 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1854 final String lib = libEntry.path; 1855 if (lib == null) { 1856 continue; 1857 } 1858 1859 try { 1860 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1861 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1862 alreadyDexOpted.add(lib); 1863 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1864 } 1865 } catch (FileNotFoundException e) { 1866 Slog.w(TAG, "Library not found: " + lib); 1867 } catch (IOException e) { 1868 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1869 + e.getMessage()); 1870 } 1871 } 1872 } 1873 } 1874 1875 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1876 1877 // Gross hack for now: we know this file doesn't contain any 1878 // code, so don't dexopt it to avoid the resulting log spew. 1879 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1880 1881 // Gross hack for now: we know this file is only part of 1882 // the boot class path for art, so don't dexopt it to 1883 // avoid the resulting log spew. 1884 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1885 1886 /** 1887 * There are a number of commands implemented in Java, which 1888 * we currently need to do the dexopt on so that they can be 1889 * run from a non-root shell. 1890 */ 1891 String[] frameworkFiles = frameworkDir.list(); 1892 if (frameworkFiles != null) { 1893 // TODO: We could compile these only for the most preferred ABI. We should 1894 // first double check that the dex files for these commands are not referenced 1895 // by other system apps. 1896 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1897 for (int i=0; i<frameworkFiles.length; i++) { 1898 File libPath = new File(frameworkDir, frameworkFiles[i]); 1899 String path = libPath.getPath(); 1900 // Skip the file if we already did it. 1901 if (alreadyDexOpted.contains(path)) { 1902 continue; 1903 } 1904 // Skip the file if it is not a type we want to dexopt. 1905 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1906 continue; 1907 } 1908 try { 1909 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1910 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1911 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1912 } 1913 } catch (FileNotFoundException e) { 1914 Slog.w(TAG, "Jar not found: " + path); 1915 } catch (IOException e) { 1916 Slog.w(TAG, "Exception reading jar: " + path, e); 1917 } 1918 } 1919 } 1920 } 1921 1922 // Collect vendor overlay packages. 1923 // (Do this before scanning any apps.) 1924 // For security and version matching reason, only consider 1925 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1926 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1927 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1928 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1929 1930 // Find base frameworks (resource packages without code). 1931 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1932 | PackageParser.PARSE_IS_SYSTEM_DIR 1933 | PackageParser.PARSE_IS_PRIVILEGED, 1934 scanFlags | SCAN_NO_DEX, 0); 1935 1936 // Collected privileged system packages. 1937 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1938 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1939 | PackageParser.PARSE_IS_SYSTEM_DIR 1940 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1941 1942 // Collect ordinary system packages. 1943 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1944 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1945 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1946 1947 // Collect all vendor packages. 1948 File vendorAppDir = new File("/vendor/app"); 1949 try { 1950 vendorAppDir = vendorAppDir.getCanonicalFile(); 1951 } catch (IOException e) { 1952 // failed to look up canonical path, continue with original one 1953 } 1954 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1955 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1956 1957 // Collect all OEM packages. 1958 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1959 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1960 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1961 1962 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1963 mInstaller.moveFiles(); 1964 1965 // Prune any system packages that no longer exist. 1966 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1967 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1968 if (!mOnlyCore) { 1969 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1970 while (psit.hasNext()) { 1971 PackageSetting ps = psit.next(); 1972 1973 /* 1974 * If this is not a system app, it can't be a 1975 * disable system app. 1976 */ 1977 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1978 continue; 1979 } 1980 1981 /* 1982 * If the package is scanned, it's not erased. 1983 */ 1984 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1985 if (scannedPkg != null) { 1986 /* 1987 * If the system app is both scanned and in the 1988 * disabled packages list, then it must have been 1989 * added via OTA. Remove it from the currently 1990 * scanned package so the previously user-installed 1991 * application can be scanned. 1992 */ 1993 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1994 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1995 + ps.name + "; removing system app. Last known codePath=" 1996 + ps.codePathString + ", installStatus=" + ps.installStatus 1997 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1998 + scannedPkg.mVersionCode); 1999 removePackageLI(ps, true); 2000 expectingBetter.put(ps.name, ps.codePath); 2001 } 2002 2003 continue; 2004 } 2005 2006 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2007 psit.remove(); 2008 logCriticalInfo(Log.WARN, "System package " + ps.name 2009 + " no longer exists; wiping its data"); 2010 removeDataDirsLI(null, ps.name); 2011 } else { 2012 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2013 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2014 possiblyDeletedUpdatedSystemApps.add(ps.name); 2015 } 2016 } 2017 } 2018 } 2019 2020 //look for any incomplete package installations 2021 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2022 //clean up list 2023 for(int i = 0; i < deletePkgsList.size(); i++) { 2024 //clean up here 2025 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2026 } 2027 //delete tmp files 2028 deleteTempPackageFiles(); 2029 2030 // Remove any shared userIDs that have no associated packages 2031 mSettings.pruneSharedUsersLPw(); 2032 2033 if (!mOnlyCore) { 2034 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2035 SystemClock.uptimeMillis()); 2036 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2037 2038 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2039 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2040 2041 /** 2042 * Remove disable package settings for any updated system 2043 * apps that were removed via an OTA. If they're not a 2044 * previously-updated app, remove them completely. 2045 * Otherwise, just revoke their system-level permissions. 2046 */ 2047 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2048 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2049 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2050 2051 String msg; 2052 if (deletedPkg == null) { 2053 msg = "Updated system package " + deletedAppName 2054 + " no longer exists; wiping its data"; 2055 removeDataDirsLI(null, deletedAppName); 2056 } else { 2057 msg = "Updated system app + " + deletedAppName 2058 + " no longer present; removing system privileges for " 2059 + deletedAppName; 2060 2061 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2062 2063 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2064 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2065 } 2066 logCriticalInfo(Log.WARN, msg); 2067 } 2068 2069 /** 2070 * Make sure all system apps that we expected to appear on 2071 * the userdata partition actually showed up. If they never 2072 * appeared, crawl back and revive the system version. 2073 */ 2074 for (int i = 0; i < expectingBetter.size(); i++) { 2075 final String packageName = expectingBetter.keyAt(i); 2076 if (!mPackages.containsKey(packageName)) { 2077 final File scanFile = expectingBetter.valueAt(i); 2078 2079 logCriticalInfo(Log.WARN, "Expected better " + packageName 2080 + " but never showed up; reverting to system"); 2081 2082 final int reparseFlags; 2083 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2084 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2085 | PackageParser.PARSE_IS_SYSTEM_DIR 2086 | PackageParser.PARSE_IS_PRIVILEGED; 2087 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2088 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2089 | PackageParser.PARSE_IS_SYSTEM_DIR; 2090 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2091 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2092 | PackageParser.PARSE_IS_SYSTEM_DIR; 2093 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2094 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2095 | PackageParser.PARSE_IS_SYSTEM_DIR; 2096 } else { 2097 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2098 continue; 2099 } 2100 2101 mSettings.enableSystemPackageLPw(packageName); 2102 2103 try { 2104 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2105 } catch (PackageManagerException e) { 2106 Slog.e(TAG, "Failed to parse original system package: " 2107 + e.getMessage()); 2108 } 2109 } 2110 } 2111 } 2112 2113 // Now that we know all of the shared libraries, update all clients to have 2114 // the correct library paths. 2115 updateAllSharedLibrariesLPw(); 2116 2117 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2118 // NOTE: We ignore potential failures here during a system scan (like 2119 // the rest of the commands above) because there's precious little we 2120 // can do about it. A settings error is reported, though. 2121 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2122 false /* force dexopt */, false /* defer dexopt */); 2123 } 2124 2125 // Now that we know all the packages we are keeping, 2126 // read and update their last usage times. 2127 mPackageUsage.readLP(); 2128 2129 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2130 SystemClock.uptimeMillis()); 2131 Slog.i(TAG, "Time to scan packages: " 2132 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2133 + " seconds"); 2134 2135 // If the platform SDK has changed since the last time we booted, 2136 // we need to re-grant app permission to catch any new ones that 2137 // appear. This is really a hack, and means that apps can in some 2138 // cases get permissions that the user didn't initially explicitly 2139 // allow... it would be nice to have some better way to handle 2140 // this situation. 2141 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2142 != mSdkVersion; 2143 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2144 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2145 + "; regranting permissions for internal storage"); 2146 mSettings.mInternalSdkPlatform = mSdkVersion; 2147 2148 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2149 | (regrantPermissions 2150 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2151 : 0)); 2152 2153 // If this is the first boot, and it is a normal boot, then 2154 // we need to initialize the default preferred apps. 2155 if (!mRestoredSettings && !onlyCore) { 2156 mSettings.readDefaultPreferredAppsLPw(this, 0); 2157 } 2158 2159 // If this is first boot after an OTA, and a normal boot, then 2160 // we need to clear code cache directories. 2161 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2162 if (mIsUpgrade && !onlyCore) { 2163 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2164 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2165 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2166 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2167 } 2168 mSettings.mFingerprint = Build.FINGERPRINT; 2169 } 2170 2171 primeDomainVerificationsLPw(); 2172 checkDefaultBrowser(); 2173 2174 // All the changes are done during package scanning. 2175 mSettings.updateInternalDatabaseVersion(); 2176 2177 // can downgrade to reader 2178 mSettings.writeLPr(); 2179 2180 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2181 SystemClock.uptimeMillis()); 2182 2183 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2184 2185 mInstallerService = new PackageInstallerService(context, this); 2186 2187 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2188 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2189 mIntentFilterVerifierComponent); 2190 2191 } // synchronized (mPackages) 2192 } // synchronized (mInstallLock) 2193 2194 // Now after opening every single application zip, make sure they 2195 // are all flushed. Not really needed, but keeps things nice and 2196 // tidy. 2197 Runtime.getRuntime().gc(); 2198 } 2199 2200 @Override 2201 public boolean isFirstBoot() { 2202 return !mRestoredSettings; 2203 } 2204 2205 @Override 2206 public boolean isOnlyCoreApps() { 2207 return mOnlyCore; 2208 } 2209 2210 @Override 2211 public boolean isUpgrade() { 2212 return mIsUpgrade; 2213 } 2214 2215 private String getRequiredVerifierLPr() { 2216 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2217 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2218 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2219 2220 String requiredVerifier = null; 2221 2222 final int N = receivers.size(); 2223 for (int i = 0; i < N; i++) { 2224 final ResolveInfo info = receivers.get(i); 2225 2226 if (info.activityInfo == null) { 2227 continue; 2228 } 2229 2230 final String packageName = info.activityInfo.packageName; 2231 2232 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2233 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2234 continue; 2235 } 2236 2237 if (requiredVerifier != null) { 2238 throw new RuntimeException("There can be only one required verifier"); 2239 } 2240 2241 requiredVerifier = packageName; 2242 } 2243 2244 return requiredVerifier; 2245 } 2246 2247 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2248 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2249 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2250 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2251 2252 ComponentName verifierComponentName = null; 2253 2254 int priority = -1000; 2255 final int N = receivers.size(); 2256 for (int i = 0; i < N; i++) { 2257 final ResolveInfo info = receivers.get(i); 2258 2259 if (info.activityInfo == null) { 2260 continue; 2261 } 2262 2263 final String packageName = info.activityInfo.packageName; 2264 2265 final PackageSetting ps = mSettings.mPackages.get(packageName); 2266 if (ps == null) { 2267 continue; 2268 } 2269 2270 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2271 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2272 continue; 2273 } 2274 2275 // Select the IntentFilterVerifier with the highest priority 2276 if (priority < info.priority) { 2277 priority = info.priority; 2278 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2279 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2280 + verifierComponentName + " with priority: " + info.priority); 2281 } 2282 } 2283 2284 return verifierComponentName; 2285 } 2286 2287 private void primeDomainVerificationsLPw() { 2288 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2289 boolean updated = false; 2290 ArraySet<String> allHostsSet = new ArraySet<>(); 2291 for (PackageParser.Package pkg : mPackages.values()) { 2292 final String packageName = pkg.packageName; 2293 if (!hasDomainURLs(pkg)) { 2294 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2295 "package with no domain URLs: " + packageName); 2296 continue; 2297 } 2298 if (!pkg.isSystemApp()) { 2299 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2300 "No priming domain verifications for a non system package : " + 2301 packageName); 2302 continue; 2303 } 2304 for (PackageParser.Activity a : pkg.activities) { 2305 for (ActivityIntentInfo filter : a.intents) { 2306 if (hasValidDomains(filter)) { 2307 allHostsSet.addAll(filter.getHostsList()); 2308 } 2309 } 2310 } 2311 if (allHostsSet.size() == 0) { 2312 allHostsSet.add("*"); 2313 } 2314 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2315 IntentFilterVerificationInfo ivi = 2316 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2317 if (ivi != null) { 2318 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2319 "Priming domain verifications for package: " + packageName + 2320 " with hosts:" + ivi.getDomainsString()); 2321 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2322 updated = true; 2323 } 2324 else { 2325 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2326 "No priming domain verifications for package: " + packageName); 2327 } 2328 allHostsSet.clear(); 2329 } 2330 if (updated) { 2331 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2332 "Will need to write primed domain verifications"); 2333 } 2334 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2335 } 2336 2337 private void checkDefaultBrowser() { 2338 final int myUserId = UserHandle.myUserId(); 2339 final String packageName = getDefaultBrowserPackageName(myUserId); 2340 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2341 if (info == null) { 2342 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2343 packageName); 2344 setDefaultBrowserPackageName(null, myUserId); 2345 } 2346 } 2347 2348 @Override 2349 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2350 throws RemoteException { 2351 try { 2352 return super.onTransact(code, data, reply, flags); 2353 } catch (RuntimeException e) { 2354 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2355 Slog.wtf(TAG, "Package Manager Crash", e); 2356 } 2357 throw e; 2358 } 2359 } 2360 2361 void cleanupInstallFailedPackage(PackageSetting ps) { 2362 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2363 2364 removeDataDirsLI(ps.volumeUuid, ps.name); 2365 if (ps.codePath != null) { 2366 if (ps.codePath.isDirectory()) { 2367 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2368 } else { 2369 ps.codePath.delete(); 2370 } 2371 } 2372 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2373 if (ps.resourcePath.isDirectory()) { 2374 FileUtils.deleteContents(ps.resourcePath); 2375 } 2376 ps.resourcePath.delete(); 2377 } 2378 mSettings.removePackageLPw(ps.name); 2379 } 2380 2381 static int[] appendInts(int[] cur, int[] add) { 2382 if (add == null) return cur; 2383 if (cur == null) return add; 2384 final int N = add.length; 2385 for (int i=0; i<N; i++) { 2386 cur = appendInt(cur, add[i]); 2387 } 2388 return cur; 2389 } 2390 2391 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2392 if (!sUserManager.exists(userId)) return null; 2393 final PackageSetting ps = (PackageSetting) p.mExtras; 2394 if (ps == null) { 2395 return null; 2396 } 2397 2398 final PermissionsState permissionsState = ps.getPermissionsState(); 2399 2400 final int[] gids = permissionsState.computeGids(userId); 2401 final Set<String> permissions = permissionsState.getPermissions(userId); 2402 final PackageUserState state = ps.readUserState(userId); 2403 2404 return PackageParser.generatePackageInfo(p, gids, flags, 2405 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2406 } 2407 2408 @Override 2409 public boolean isPackageFrozen(String packageName) { 2410 synchronized (mPackages) { 2411 final PackageSetting ps = mSettings.mPackages.get(packageName); 2412 if (ps != null) { 2413 return ps.frozen; 2414 } 2415 } 2416 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2417 return true; 2418 } 2419 2420 @Override 2421 public boolean isPackageAvailable(String packageName, int userId) { 2422 if (!sUserManager.exists(userId)) return false; 2423 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2424 synchronized (mPackages) { 2425 PackageParser.Package p = mPackages.get(packageName); 2426 if (p != null) { 2427 final PackageSetting ps = (PackageSetting) p.mExtras; 2428 if (ps != null) { 2429 final PackageUserState state = ps.readUserState(userId); 2430 if (state != null) { 2431 return PackageParser.isAvailable(state); 2432 } 2433 } 2434 } 2435 } 2436 return false; 2437 } 2438 2439 @Override 2440 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2441 if (!sUserManager.exists(userId)) return null; 2442 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2443 // reader 2444 synchronized (mPackages) { 2445 PackageParser.Package p = mPackages.get(packageName); 2446 if (DEBUG_PACKAGE_INFO) 2447 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2448 if (p != null) { 2449 return generatePackageInfo(p, flags, userId); 2450 } 2451 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2452 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2453 } 2454 } 2455 return null; 2456 } 2457 2458 @Override 2459 public String[] currentToCanonicalPackageNames(String[] names) { 2460 String[] out = new String[names.length]; 2461 // reader 2462 synchronized (mPackages) { 2463 for (int i=names.length-1; i>=0; i--) { 2464 PackageSetting ps = mSettings.mPackages.get(names[i]); 2465 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2466 } 2467 } 2468 return out; 2469 } 2470 2471 @Override 2472 public String[] canonicalToCurrentPackageNames(String[] names) { 2473 String[] out = new String[names.length]; 2474 // reader 2475 synchronized (mPackages) { 2476 for (int i=names.length-1; i>=0; i--) { 2477 String cur = mSettings.mRenamedPackages.get(names[i]); 2478 out[i] = cur != null ? cur : names[i]; 2479 } 2480 } 2481 return out; 2482 } 2483 2484 @Override 2485 public int getPackageUid(String packageName, int userId) { 2486 if (!sUserManager.exists(userId)) return -1; 2487 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2488 2489 // reader 2490 synchronized (mPackages) { 2491 PackageParser.Package p = mPackages.get(packageName); 2492 if(p != null) { 2493 return UserHandle.getUid(userId, p.applicationInfo.uid); 2494 } 2495 PackageSetting ps = mSettings.mPackages.get(packageName); 2496 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2497 return -1; 2498 } 2499 p = ps.pkg; 2500 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2501 } 2502 } 2503 2504 @Override 2505 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2506 if (!sUserManager.exists(userId)) { 2507 return null; 2508 } 2509 2510 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2511 "getPackageGids"); 2512 2513 // reader 2514 synchronized (mPackages) { 2515 PackageParser.Package p = mPackages.get(packageName); 2516 if (DEBUG_PACKAGE_INFO) { 2517 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2518 } 2519 if (p != null) { 2520 PackageSetting ps = (PackageSetting) p.mExtras; 2521 return ps.getPermissionsState().computeGids(userId); 2522 } 2523 } 2524 2525 return null; 2526 } 2527 2528 static PermissionInfo generatePermissionInfo( 2529 BasePermission bp, int flags) { 2530 if (bp.perm != null) { 2531 return PackageParser.generatePermissionInfo(bp.perm, flags); 2532 } 2533 PermissionInfo pi = new PermissionInfo(); 2534 pi.name = bp.name; 2535 pi.packageName = bp.sourcePackage; 2536 pi.nonLocalizedLabel = bp.name; 2537 pi.protectionLevel = bp.protectionLevel; 2538 return pi; 2539 } 2540 2541 @Override 2542 public PermissionInfo getPermissionInfo(String name, int flags) { 2543 // reader 2544 synchronized (mPackages) { 2545 final BasePermission p = mSettings.mPermissions.get(name); 2546 if (p != null) { 2547 return generatePermissionInfo(p, flags); 2548 } 2549 return null; 2550 } 2551 } 2552 2553 @Override 2554 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2555 // reader 2556 synchronized (mPackages) { 2557 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2558 for (BasePermission p : mSettings.mPermissions.values()) { 2559 if (group == null) { 2560 if (p.perm == null || p.perm.info.group == null) { 2561 out.add(generatePermissionInfo(p, flags)); 2562 } 2563 } else { 2564 if (p.perm != null && group.equals(p.perm.info.group)) { 2565 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2566 } 2567 } 2568 } 2569 2570 if (out.size() > 0) { 2571 return out; 2572 } 2573 return mPermissionGroups.containsKey(group) ? out : null; 2574 } 2575 } 2576 2577 @Override 2578 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2579 // reader 2580 synchronized (mPackages) { 2581 return PackageParser.generatePermissionGroupInfo( 2582 mPermissionGroups.get(name), flags); 2583 } 2584 } 2585 2586 @Override 2587 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2588 // reader 2589 synchronized (mPackages) { 2590 final int N = mPermissionGroups.size(); 2591 ArrayList<PermissionGroupInfo> out 2592 = new ArrayList<PermissionGroupInfo>(N); 2593 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2594 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2595 } 2596 return out; 2597 } 2598 } 2599 2600 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2601 int userId) { 2602 if (!sUserManager.exists(userId)) return null; 2603 PackageSetting ps = mSettings.mPackages.get(packageName); 2604 if (ps != null) { 2605 if (ps.pkg == null) { 2606 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2607 flags, userId); 2608 if (pInfo != null) { 2609 return pInfo.applicationInfo; 2610 } 2611 return null; 2612 } 2613 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2614 ps.readUserState(userId), userId); 2615 } 2616 return null; 2617 } 2618 2619 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2620 int userId) { 2621 if (!sUserManager.exists(userId)) return null; 2622 PackageSetting ps = mSettings.mPackages.get(packageName); 2623 if (ps != null) { 2624 PackageParser.Package pkg = ps.pkg; 2625 if (pkg == null) { 2626 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2627 return null; 2628 } 2629 // Only data remains, so we aren't worried about code paths 2630 pkg = new PackageParser.Package(packageName); 2631 pkg.applicationInfo.packageName = packageName; 2632 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2633 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2634 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2635 packageName, userId).getAbsolutePath(); 2636 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2637 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2638 } 2639 return generatePackageInfo(pkg, flags, userId); 2640 } 2641 return null; 2642 } 2643 2644 @Override 2645 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2646 if (!sUserManager.exists(userId)) return null; 2647 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2648 // writer 2649 synchronized (mPackages) { 2650 PackageParser.Package p = mPackages.get(packageName); 2651 if (DEBUG_PACKAGE_INFO) Log.v( 2652 TAG, "getApplicationInfo " + packageName 2653 + ": " + p); 2654 if (p != null) { 2655 PackageSetting ps = mSettings.mPackages.get(packageName); 2656 if (ps == null) return null; 2657 // Note: isEnabledLP() does not apply here - always return info 2658 return PackageParser.generateApplicationInfo( 2659 p, flags, ps.readUserState(userId), userId); 2660 } 2661 if ("android".equals(packageName)||"system".equals(packageName)) { 2662 return mAndroidApplication; 2663 } 2664 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2665 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2666 } 2667 } 2668 return null; 2669 } 2670 2671 @Override 2672 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2673 final IPackageDataObserver observer) { 2674 mContext.enforceCallingOrSelfPermission( 2675 android.Manifest.permission.CLEAR_APP_CACHE, null); 2676 // Queue up an async operation since clearing cache may take a little while. 2677 mHandler.post(new Runnable() { 2678 public void run() { 2679 mHandler.removeCallbacks(this); 2680 int retCode = -1; 2681 synchronized (mInstallLock) { 2682 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2683 if (retCode < 0) { 2684 Slog.w(TAG, "Couldn't clear application caches"); 2685 } 2686 } 2687 if (observer != null) { 2688 try { 2689 observer.onRemoveCompleted(null, (retCode >= 0)); 2690 } catch (RemoteException e) { 2691 Slog.w(TAG, "RemoveException when invoking call back"); 2692 } 2693 } 2694 } 2695 }); 2696 } 2697 2698 @Override 2699 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2700 final IntentSender pi) { 2701 mContext.enforceCallingOrSelfPermission( 2702 android.Manifest.permission.CLEAR_APP_CACHE, null); 2703 // Queue up an async operation since clearing cache may take a little while. 2704 mHandler.post(new Runnable() { 2705 public void run() { 2706 mHandler.removeCallbacks(this); 2707 int retCode = -1; 2708 synchronized (mInstallLock) { 2709 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2710 if (retCode < 0) { 2711 Slog.w(TAG, "Couldn't clear application caches"); 2712 } 2713 } 2714 if(pi != null) { 2715 try { 2716 // Callback via pending intent 2717 int code = (retCode >= 0) ? 1 : 0; 2718 pi.sendIntent(null, code, null, 2719 null, null); 2720 } catch (SendIntentException e1) { 2721 Slog.i(TAG, "Failed to send pending intent"); 2722 } 2723 } 2724 } 2725 }); 2726 } 2727 2728 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2729 synchronized (mInstallLock) { 2730 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2731 throw new IOException("Failed to free enough space"); 2732 } 2733 } 2734 } 2735 2736 @Override 2737 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2738 if (!sUserManager.exists(userId)) return null; 2739 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2740 synchronized (mPackages) { 2741 PackageParser.Activity a = mActivities.mActivities.get(component); 2742 2743 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2744 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2745 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2746 if (ps == null) return null; 2747 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2748 userId); 2749 } 2750 if (mResolveComponentName.equals(component)) { 2751 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2752 new PackageUserState(), userId); 2753 } 2754 } 2755 return null; 2756 } 2757 2758 @Override 2759 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2760 String resolvedType) { 2761 synchronized (mPackages) { 2762 PackageParser.Activity a = mActivities.mActivities.get(component); 2763 if (a == null) { 2764 return false; 2765 } 2766 for (int i=0; i<a.intents.size(); i++) { 2767 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2768 intent.getData(), intent.getCategories(), TAG) >= 0) { 2769 return true; 2770 } 2771 } 2772 return false; 2773 } 2774 } 2775 2776 @Override 2777 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2778 if (!sUserManager.exists(userId)) return null; 2779 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2780 synchronized (mPackages) { 2781 PackageParser.Activity a = mReceivers.mActivities.get(component); 2782 if (DEBUG_PACKAGE_INFO) Log.v( 2783 TAG, "getReceiverInfo " + component + ": " + a); 2784 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2785 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2786 if (ps == null) return null; 2787 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2788 userId); 2789 } 2790 } 2791 return null; 2792 } 2793 2794 @Override 2795 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2796 if (!sUserManager.exists(userId)) return null; 2797 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2798 synchronized (mPackages) { 2799 PackageParser.Service s = mServices.mServices.get(component); 2800 if (DEBUG_PACKAGE_INFO) Log.v( 2801 TAG, "getServiceInfo " + component + ": " + s); 2802 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2803 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2804 if (ps == null) return null; 2805 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2806 userId); 2807 } 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2814 if (!sUserManager.exists(userId)) return null; 2815 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2816 synchronized (mPackages) { 2817 PackageParser.Provider p = mProviders.mProviders.get(component); 2818 if (DEBUG_PACKAGE_INFO) Log.v( 2819 TAG, "getProviderInfo " + component + ": " + p); 2820 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2821 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2822 if (ps == null) return null; 2823 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2824 userId); 2825 } 2826 } 2827 return null; 2828 } 2829 2830 @Override 2831 public String[] getSystemSharedLibraryNames() { 2832 Set<String> libSet; 2833 synchronized (mPackages) { 2834 libSet = mSharedLibraries.keySet(); 2835 int size = libSet.size(); 2836 if (size > 0) { 2837 String[] libs = new String[size]; 2838 libSet.toArray(libs); 2839 return libs; 2840 } 2841 } 2842 return null; 2843 } 2844 2845 /** 2846 * @hide 2847 */ 2848 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2849 synchronized (mPackages) { 2850 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2851 if (lib != null && lib.apk != null) { 2852 return mPackages.get(lib.apk); 2853 } 2854 } 2855 return null; 2856 } 2857 2858 @Override 2859 public FeatureInfo[] getSystemAvailableFeatures() { 2860 Collection<FeatureInfo> featSet; 2861 synchronized (mPackages) { 2862 featSet = mAvailableFeatures.values(); 2863 int size = featSet.size(); 2864 if (size > 0) { 2865 FeatureInfo[] features = new FeatureInfo[size+1]; 2866 featSet.toArray(features); 2867 FeatureInfo fi = new FeatureInfo(); 2868 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2869 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2870 features[size] = fi; 2871 return features; 2872 } 2873 } 2874 return null; 2875 } 2876 2877 @Override 2878 public boolean hasSystemFeature(String name) { 2879 synchronized (mPackages) { 2880 return mAvailableFeatures.containsKey(name); 2881 } 2882 } 2883 2884 private void checkValidCaller(int uid, int userId) { 2885 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2886 return; 2887 2888 throw new SecurityException("Caller uid=" + uid 2889 + " is not privileged to communicate with user=" + userId); 2890 } 2891 2892 @Override 2893 public int checkPermission(String permName, String pkgName, int userId) { 2894 if (!sUserManager.exists(userId)) { 2895 return PackageManager.PERMISSION_DENIED; 2896 } 2897 2898 synchronized (mPackages) { 2899 final PackageParser.Package p = mPackages.get(pkgName); 2900 if (p != null && p.mExtras != null) { 2901 final PackageSetting ps = (PackageSetting) p.mExtras; 2902 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2903 return PackageManager.PERMISSION_GRANTED; 2904 } 2905 } 2906 } 2907 2908 return PackageManager.PERMISSION_DENIED; 2909 } 2910 2911 @Override 2912 public int checkUidPermission(String permName, int uid) { 2913 final int userId = UserHandle.getUserId(uid); 2914 2915 if (!sUserManager.exists(userId)) { 2916 return PackageManager.PERMISSION_DENIED; 2917 } 2918 2919 synchronized (mPackages) { 2920 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2921 if (obj != null) { 2922 final SettingBase ps = (SettingBase) obj; 2923 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2924 return PackageManager.PERMISSION_GRANTED; 2925 } 2926 } else { 2927 ArraySet<String> perms = mSystemPermissions.get(uid); 2928 if (perms != null && perms.contains(permName)) { 2929 return PackageManager.PERMISSION_GRANTED; 2930 } 2931 } 2932 } 2933 2934 return PackageManager.PERMISSION_DENIED; 2935 } 2936 2937 /** 2938 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2939 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2940 * @param checkShell TODO(yamasani): 2941 * @param message the message to log on security exception 2942 */ 2943 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2944 boolean checkShell, String message) { 2945 if (userId < 0) { 2946 throw new IllegalArgumentException("Invalid userId " + userId); 2947 } 2948 if (checkShell) { 2949 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2950 } 2951 if (userId == UserHandle.getUserId(callingUid)) return; 2952 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2953 if (requireFullPermission) { 2954 mContext.enforceCallingOrSelfPermission( 2955 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2956 } else { 2957 try { 2958 mContext.enforceCallingOrSelfPermission( 2959 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2960 } catch (SecurityException se) { 2961 mContext.enforceCallingOrSelfPermission( 2962 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2963 } 2964 } 2965 } 2966 } 2967 2968 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2969 if (callingUid == Process.SHELL_UID) { 2970 if (userHandle >= 0 2971 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2972 throw new SecurityException("Shell does not have permission to access user " 2973 + userHandle); 2974 } else if (userHandle < 0) { 2975 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2976 + Debug.getCallers(3)); 2977 } 2978 } 2979 } 2980 2981 private BasePermission findPermissionTreeLP(String permName) { 2982 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2983 if (permName.startsWith(bp.name) && 2984 permName.length() > bp.name.length() && 2985 permName.charAt(bp.name.length()) == '.') { 2986 return bp; 2987 } 2988 } 2989 return null; 2990 } 2991 2992 private BasePermission checkPermissionTreeLP(String permName) { 2993 if (permName != null) { 2994 BasePermission bp = findPermissionTreeLP(permName); 2995 if (bp != null) { 2996 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2997 return bp; 2998 } 2999 throw new SecurityException("Calling uid " 3000 + Binder.getCallingUid() 3001 + " is not allowed to add to permission tree " 3002 + bp.name + " owned by uid " + bp.uid); 3003 } 3004 } 3005 throw new SecurityException("No permission tree found for " + permName); 3006 } 3007 3008 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3009 if (s1 == null) { 3010 return s2 == null; 3011 } 3012 if (s2 == null) { 3013 return false; 3014 } 3015 if (s1.getClass() != s2.getClass()) { 3016 return false; 3017 } 3018 return s1.equals(s2); 3019 } 3020 3021 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3022 if (pi1.icon != pi2.icon) return false; 3023 if (pi1.logo != pi2.logo) return false; 3024 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3025 if (!compareStrings(pi1.name, pi2.name)) return false; 3026 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3027 // We'll take care of setting this one. 3028 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3029 // These are not currently stored in settings. 3030 //if (!compareStrings(pi1.group, pi2.group)) return false; 3031 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3032 //if (pi1.labelRes != pi2.labelRes) return false; 3033 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3034 return true; 3035 } 3036 3037 int permissionInfoFootprint(PermissionInfo info) { 3038 int size = info.name.length(); 3039 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3040 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3041 return size; 3042 } 3043 3044 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3045 int size = 0; 3046 for (BasePermission perm : mSettings.mPermissions.values()) { 3047 if (perm.uid == tree.uid) { 3048 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3049 } 3050 } 3051 return size; 3052 } 3053 3054 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3055 // We calculate the max size of permissions defined by this uid and throw 3056 // if that plus the size of 'info' would exceed our stated maximum. 3057 if (tree.uid != Process.SYSTEM_UID) { 3058 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3059 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3060 throw new SecurityException("Permission tree size cap exceeded"); 3061 } 3062 } 3063 } 3064 3065 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3066 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3067 throw new SecurityException("Label must be specified in permission"); 3068 } 3069 BasePermission tree = checkPermissionTreeLP(info.name); 3070 BasePermission bp = mSettings.mPermissions.get(info.name); 3071 boolean added = bp == null; 3072 boolean changed = true; 3073 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3074 if (added) { 3075 enforcePermissionCapLocked(info, tree); 3076 bp = new BasePermission(info.name, tree.sourcePackage, 3077 BasePermission.TYPE_DYNAMIC); 3078 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3079 throw new SecurityException( 3080 "Not allowed to modify non-dynamic permission " 3081 + info.name); 3082 } else { 3083 if (bp.protectionLevel == fixedLevel 3084 && bp.perm.owner.equals(tree.perm.owner) 3085 && bp.uid == tree.uid 3086 && comparePermissionInfos(bp.perm.info, info)) { 3087 changed = false; 3088 } 3089 } 3090 bp.protectionLevel = fixedLevel; 3091 info = new PermissionInfo(info); 3092 info.protectionLevel = fixedLevel; 3093 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3094 bp.perm.info.packageName = tree.perm.info.packageName; 3095 bp.uid = tree.uid; 3096 if (added) { 3097 mSettings.mPermissions.put(info.name, bp); 3098 } 3099 if (changed) { 3100 if (!async) { 3101 mSettings.writeLPr(); 3102 } else { 3103 scheduleWriteSettingsLocked(); 3104 } 3105 } 3106 return added; 3107 } 3108 3109 @Override 3110 public boolean addPermission(PermissionInfo info) { 3111 synchronized (mPackages) { 3112 return addPermissionLocked(info, false); 3113 } 3114 } 3115 3116 @Override 3117 public boolean addPermissionAsync(PermissionInfo info) { 3118 synchronized (mPackages) { 3119 return addPermissionLocked(info, true); 3120 } 3121 } 3122 3123 @Override 3124 public void removePermission(String name) { 3125 synchronized (mPackages) { 3126 checkPermissionTreeLP(name); 3127 BasePermission bp = mSettings.mPermissions.get(name); 3128 if (bp != null) { 3129 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3130 throw new SecurityException( 3131 "Not allowed to modify non-dynamic permission " 3132 + name); 3133 } 3134 mSettings.mPermissions.remove(name); 3135 mSettings.writeLPr(); 3136 } 3137 } 3138 } 3139 3140 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3141 BasePermission bp) { 3142 int index = pkg.requestedPermissions.indexOf(bp.name); 3143 if (index == -1) { 3144 throw new SecurityException("Package " + pkg.packageName 3145 + " has not requested permission " + bp.name); 3146 } 3147 if (!bp.isRuntime()) { 3148 throw new SecurityException("Permission " + bp.name 3149 + " is not a changeable permission type"); 3150 } 3151 } 3152 3153 @Override 3154 public void grantRuntimePermission(String packageName, String name, int userId) { 3155 if (!sUserManager.exists(userId)) { 3156 Log.e(TAG, "No such user:" + userId); 3157 return; 3158 } 3159 3160 mContext.enforceCallingOrSelfPermission( 3161 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3162 "grantRuntimePermission"); 3163 3164 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3165 "grantRuntimePermission"); 3166 3167 boolean gidsChanged = false; 3168 final SettingBase sb; 3169 3170 synchronized (mPackages) { 3171 final PackageParser.Package pkg = mPackages.get(packageName); 3172 if (pkg == null) { 3173 throw new IllegalArgumentException("Unknown package: " + packageName); 3174 } 3175 3176 final BasePermission bp = mSettings.mPermissions.get(name); 3177 if (bp == null) { 3178 throw new IllegalArgumentException("Unknown permission: " + name); 3179 } 3180 3181 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3182 3183 sb = (SettingBase) pkg.mExtras; 3184 if (sb == null) { 3185 throw new IllegalArgumentException("Unknown package: " + packageName); 3186 } 3187 3188 final PermissionsState permissionsState = sb.getPermissionsState(); 3189 3190 final int flags = permissionsState.getPermissionFlags(name, userId); 3191 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3192 throw new SecurityException("Cannot grant system fixed permission: " 3193 + name + " for package: " + packageName); 3194 } 3195 3196 final int result = permissionsState.grantRuntimePermission(bp, userId); 3197 switch (result) { 3198 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3199 return; 3200 } 3201 3202 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3203 gidsChanged = true; 3204 } break; 3205 } 3206 3207 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3208 3209 // Not critical if that is lost - app has to request again. 3210 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3211 } 3212 3213 if (gidsChanged) { 3214 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3215 } 3216 } 3217 3218 @Override 3219 public void revokeRuntimePermission(String packageName, String name, int userId) { 3220 if (!sUserManager.exists(userId)) { 3221 Log.e(TAG, "No such user:" + userId); 3222 return; 3223 } 3224 3225 mContext.enforceCallingOrSelfPermission( 3226 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3227 "revokeRuntimePermission"); 3228 3229 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3230 "revokeRuntimePermission"); 3231 3232 final SettingBase sb; 3233 3234 synchronized (mPackages) { 3235 final PackageParser.Package pkg = mPackages.get(packageName); 3236 if (pkg == null) { 3237 throw new IllegalArgumentException("Unknown package: " + packageName); 3238 } 3239 3240 final BasePermission bp = mSettings.mPermissions.get(name); 3241 if (bp == null) { 3242 throw new IllegalArgumentException("Unknown permission: " + name); 3243 } 3244 3245 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3246 3247 sb = (SettingBase) pkg.mExtras; 3248 if (sb == null) { 3249 throw new IllegalArgumentException("Unknown package: " + packageName); 3250 } 3251 3252 final PermissionsState permissionsState = sb.getPermissionsState(); 3253 3254 final int flags = permissionsState.getPermissionFlags(name, userId); 3255 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3256 throw new SecurityException("Cannot revoke system fixed permission: " 3257 + name + " for package: " + packageName); 3258 } 3259 3260 if (permissionsState.revokeRuntimePermission(bp, userId) == 3261 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3262 return; 3263 } 3264 3265 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3266 3267 // Critical, after this call app should never have the permission. 3268 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3269 } 3270 3271 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3272 } 3273 3274 @Override 3275 public int getPermissionFlags(String name, String packageName, int userId) { 3276 if (!sUserManager.exists(userId)) { 3277 return 0; 3278 } 3279 3280 mContext.enforceCallingOrSelfPermission( 3281 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3282 "getPermissionFlags"); 3283 3284 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3285 "getPermissionFlags"); 3286 3287 synchronized (mPackages) { 3288 final PackageParser.Package pkg = mPackages.get(packageName); 3289 if (pkg == null) { 3290 throw new IllegalArgumentException("Unknown package: " + packageName); 3291 } 3292 3293 final BasePermission bp = mSettings.mPermissions.get(name); 3294 if (bp == null) { 3295 throw new IllegalArgumentException("Unknown permission: " + name); 3296 } 3297 3298 SettingBase sb = (SettingBase) pkg.mExtras; 3299 if (sb == null) { 3300 throw new IllegalArgumentException("Unknown package: " + packageName); 3301 } 3302 3303 PermissionsState permissionsState = sb.getPermissionsState(); 3304 return permissionsState.getPermissionFlags(name, userId); 3305 } 3306 } 3307 3308 @Override 3309 public void updatePermissionFlags(String name, String packageName, int flagMask, 3310 int flagValues, int userId) { 3311 if (!sUserManager.exists(userId)) { 3312 return; 3313 } 3314 3315 mContext.enforceCallingOrSelfPermission( 3316 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3317 "updatePermissionFlags"); 3318 3319 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3320 "updatePermissionFlags"); 3321 3322 // Only the system can change policy flags. 3323 if (getCallingUid() != Process.SYSTEM_UID) { 3324 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3325 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3326 } 3327 3328 // Only the package manager can change system flags. 3329 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3330 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3331 3332 synchronized (mPackages) { 3333 final PackageParser.Package pkg = mPackages.get(packageName); 3334 if (pkg == null) { 3335 throw new IllegalArgumentException("Unknown package: " + packageName); 3336 } 3337 3338 final BasePermission bp = mSettings.mPermissions.get(name); 3339 if (bp == null) { 3340 throw new IllegalArgumentException("Unknown permission: " + name); 3341 } 3342 3343 SettingBase sb = (SettingBase) pkg.mExtras; 3344 if (sb == null) { 3345 throw new IllegalArgumentException("Unknown package: " + packageName); 3346 } 3347 3348 PermissionsState permissionsState = sb.getPermissionsState(); 3349 3350 // Only the package manager can change flags for system component permissions. 3351 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3352 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3353 return; 3354 } 3355 3356 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3357 // Install and runtime permissions are stored in different places, 3358 // so figure out what permission changed and persist the change. 3359 if (permissionsState.getInstallPermissionState(name) != null) { 3360 scheduleWriteSettingsLocked(); 3361 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3362 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3363 } 3364 } 3365 } 3366 } 3367 3368 @Override 3369 public boolean shouldShowRequestPermissionRationale(String permissionName, 3370 String packageName, int userId) { 3371 if (UserHandle.getCallingUserId() != userId) { 3372 mContext.enforceCallingPermission( 3373 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3374 "canShowRequestPermissionRationale for user " + userId); 3375 } 3376 3377 final int uid = getPackageUid(packageName, userId); 3378 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3379 return false; 3380 } 3381 3382 if (checkPermission(permissionName, packageName, userId) 3383 == PackageManager.PERMISSION_GRANTED) { 3384 return false; 3385 } 3386 3387 final int flags; 3388 3389 final long identity = Binder.clearCallingIdentity(); 3390 try { 3391 flags = getPermissionFlags(permissionName, 3392 packageName, userId); 3393 } finally { 3394 Binder.restoreCallingIdentity(identity); 3395 } 3396 3397 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3398 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3399 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3400 3401 if ((flags & fixedFlags) != 0) { 3402 return false; 3403 } 3404 3405 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3406 } 3407 3408 @Override 3409 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3410 mContext.enforceCallingOrSelfPermission( 3411 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3412 "addOnPermissionsChangeListener"); 3413 3414 synchronized (mPackages) { 3415 mOnPermissionChangeListeners.addListenerLocked(listener); 3416 } 3417 } 3418 3419 @Override 3420 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3421 synchronized (mPackages) { 3422 mOnPermissionChangeListeners.removeListenerLocked(listener); 3423 } 3424 } 3425 3426 @Override 3427 public boolean isProtectedBroadcast(String actionName) { 3428 synchronized (mPackages) { 3429 return mProtectedBroadcasts.contains(actionName); 3430 } 3431 } 3432 3433 @Override 3434 public int checkSignatures(String pkg1, String pkg2) { 3435 synchronized (mPackages) { 3436 final PackageParser.Package p1 = mPackages.get(pkg1); 3437 final PackageParser.Package p2 = mPackages.get(pkg2); 3438 if (p1 == null || p1.mExtras == null 3439 || p2 == null || p2.mExtras == null) { 3440 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3441 } 3442 return compareSignatures(p1.mSignatures, p2.mSignatures); 3443 } 3444 } 3445 3446 @Override 3447 public int checkUidSignatures(int uid1, int uid2) { 3448 // Map to base uids. 3449 uid1 = UserHandle.getAppId(uid1); 3450 uid2 = UserHandle.getAppId(uid2); 3451 // reader 3452 synchronized (mPackages) { 3453 Signature[] s1; 3454 Signature[] s2; 3455 Object obj = mSettings.getUserIdLPr(uid1); 3456 if (obj != null) { 3457 if (obj instanceof SharedUserSetting) { 3458 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3459 } else if (obj instanceof PackageSetting) { 3460 s1 = ((PackageSetting)obj).signatures.mSignatures; 3461 } else { 3462 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3463 } 3464 } else { 3465 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3466 } 3467 obj = mSettings.getUserIdLPr(uid2); 3468 if (obj != null) { 3469 if (obj instanceof SharedUserSetting) { 3470 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3471 } else if (obj instanceof PackageSetting) { 3472 s2 = ((PackageSetting)obj).signatures.mSignatures; 3473 } else { 3474 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3475 } 3476 } else { 3477 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3478 } 3479 return compareSignatures(s1, s2); 3480 } 3481 } 3482 3483 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3484 final long identity = Binder.clearCallingIdentity(); 3485 try { 3486 if (sb instanceof SharedUserSetting) { 3487 SharedUserSetting sus = (SharedUserSetting) sb; 3488 final int packageCount = sus.packages.size(); 3489 for (int i = 0; i < packageCount; i++) { 3490 PackageSetting susPs = sus.packages.valueAt(i); 3491 if (userId == UserHandle.USER_ALL) { 3492 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3493 } else { 3494 final int uid = UserHandle.getUid(userId, susPs.appId); 3495 killUid(uid, reason); 3496 } 3497 } 3498 } else if (sb instanceof PackageSetting) { 3499 PackageSetting ps = (PackageSetting) sb; 3500 if (userId == UserHandle.USER_ALL) { 3501 killApplication(ps.pkg.packageName, ps.appId, reason); 3502 } else { 3503 final int uid = UserHandle.getUid(userId, ps.appId); 3504 killUid(uid, reason); 3505 } 3506 } 3507 } finally { 3508 Binder.restoreCallingIdentity(identity); 3509 } 3510 } 3511 3512 private static void killUid(int uid, String reason) { 3513 IActivityManager am = ActivityManagerNative.getDefault(); 3514 if (am != null) { 3515 try { 3516 am.killUid(uid, reason); 3517 } catch (RemoteException e) { 3518 /* ignore - same process */ 3519 } 3520 } 3521 } 3522 3523 /** 3524 * Compares two sets of signatures. Returns: 3525 * <br /> 3526 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3527 * <br /> 3528 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3529 * <br /> 3530 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3531 * <br /> 3532 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3533 * <br /> 3534 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3535 */ 3536 static int compareSignatures(Signature[] s1, Signature[] s2) { 3537 if (s1 == null) { 3538 return s2 == null 3539 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3540 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3541 } 3542 3543 if (s2 == null) { 3544 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3545 } 3546 3547 if (s1.length != s2.length) { 3548 return PackageManager.SIGNATURE_NO_MATCH; 3549 } 3550 3551 // Since both signature sets are of size 1, we can compare without HashSets. 3552 if (s1.length == 1) { 3553 return s1[0].equals(s2[0]) ? 3554 PackageManager.SIGNATURE_MATCH : 3555 PackageManager.SIGNATURE_NO_MATCH; 3556 } 3557 3558 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3559 for (Signature sig : s1) { 3560 set1.add(sig); 3561 } 3562 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3563 for (Signature sig : s2) { 3564 set2.add(sig); 3565 } 3566 // Make sure s2 contains all signatures in s1. 3567 if (set1.equals(set2)) { 3568 return PackageManager.SIGNATURE_MATCH; 3569 } 3570 return PackageManager.SIGNATURE_NO_MATCH; 3571 } 3572 3573 /** 3574 * If the database version for this type of package (internal storage or 3575 * external storage) is less than the version where package signatures 3576 * were updated, return true. 3577 */ 3578 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3579 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3580 DatabaseVersion.SIGNATURE_END_ENTITY)) 3581 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3582 DatabaseVersion.SIGNATURE_END_ENTITY)); 3583 } 3584 3585 /** 3586 * Used for backward compatibility to make sure any packages with 3587 * certificate chains get upgraded to the new style. {@code existingSigs} 3588 * will be in the old format (since they were stored on disk from before the 3589 * system upgrade) and {@code scannedSigs} will be in the newer format. 3590 */ 3591 private int compareSignaturesCompat(PackageSignatures existingSigs, 3592 PackageParser.Package scannedPkg) { 3593 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3594 return PackageManager.SIGNATURE_NO_MATCH; 3595 } 3596 3597 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3598 for (Signature sig : existingSigs.mSignatures) { 3599 existingSet.add(sig); 3600 } 3601 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3602 for (Signature sig : scannedPkg.mSignatures) { 3603 try { 3604 Signature[] chainSignatures = sig.getChainSignatures(); 3605 for (Signature chainSig : chainSignatures) { 3606 scannedCompatSet.add(chainSig); 3607 } 3608 } catch (CertificateEncodingException e) { 3609 scannedCompatSet.add(sig); 3610 } 3611 } 3612 /* 3613 * Make sure the expanded scanned set contains all signatures in the 3614 * existing one. 3615 */ 3616 if (scannedCompatSet.equals(existingSet)) { 3617 // Migrate the old signatures to the new scheme. 3618 existingSigs.assignSignatures(scannedPkg.mSignatures); 3619 // The new KeySets will be re-added later in the scanning process. 3620 synchronized (mPackages) { 3621 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3622 } 3623 return PackageManager.SIGNATURE_MATCH; 3624 } 3625 return PackageManager.SIGNATURE_NO_MATCH; 3626 } 3627 3628 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3629 if (isExternal(scannedPkg)) { 3630 return mSettings.isExternalDatabaseVersionOlderThan( 3631 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3632 } else { 3633 return mSettings.isInternalDatabaseVersionOlderThan( 3634 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3635 } 3636 } 3637 3638 private int compareSignaturesRecover(PackageSignatures existingSigs, 3639 PackageParser.Package scannedPkg) { 3640 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3641 return PackageManager.SIGNATURE_NO_MATCH; 3642 } 3643 3644 String msg = null; 3645 try { 3646 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3647 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3648 + scannedPkg.packageName); 3649 return PackageManager.SIGNATURE_MATCH; 3650 } 3651 } catch (CertificateException e) { 3652 msg = e.getMessage(); 3653 } 3654 3655 logCriticalInfo(Log.INFO, 3656 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3657 return PackageManager.SIGNATURE_NO_MATCH; 3658 } 3659 3660 @Override 3661 public String[] getPackagesForUid(int uid) { 3662 uid = UserHandle.getAppId(uid); 3663 // reader 3664 synchronized (mPackages) { 3665 Object obj = mSettings.getUserIdLPr(uid); 3666 if (obj instanceof SharedUserSetting) { 3667 final SharedUserSetting sus = (SharedUserSetting) obj; 3668 final int N = sus.packages.size(); 3669 final String[] res = new String[N]; 3670 final Iterator<PackageSetting> it = sus.packages.iterator(); 3671 int i = 0; 3672 while (it.hasNext()) { 3673 res[i++] = it.next().name; 3674 } 3675 return res; 3676 } else if (obj instanceof PackageSetting) { 3677 final PackageSetting ps = (PackageSetting) obj; 3678 return new String[] { ps.name }; 3679 } 3680 } 3681 return null; 3682 } 3683 3684 @Override 3685 public String getNameForUid(int uid) { 3686 // reader 3687 synchronized (mPackages) { 3688 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3689 if (obj instanceof SharedUserSetting) { 3690 final SharedUserSetting sus = (SharedUserSetting) obj; 3691 return sus.name + ":" + sus.userId; 3692 } else if (obj instanceof PackageSetting) { 3693 final PackageSetting ps = (PackageSetting) obj; 3694 return ps.name; 3695 } 3696 } 3697 return null; 3698 } 3699 3700 @Override 3701 public int getUidForSharedUser(String sharedUserName) { 3702 if(sharedUserName == null) { 3703 return -1; 3704 } 3705 // reader 3706 synchronized (mPackages) { 3707 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3708 if (suid == null) { 3709 return -1; 3710 } 3711 return suid.userId; 3712 } 3713 } 3714 3715 @Override 3716 public int getFlagsForUid(int uid) { 3717 synchronized (mPackages) { 3718 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3719 if (obj instanceof SharedUserSetting) { 3720 final SharedUserSetting sus = (SharedUserSetting) obj; 3721 return sus.pkgFlags; 3722 } else if (obj instanceof PackageSetting) { 3723 final PackageSetting ps = (PackageSetting) obj; 3724 return ps.pkgFlags; 3725 } 3726 } 3727 return 0; 3728 } 3729 3730 @Override 3731 public int getPrivateFlagsForUid(int uid) { 3732 synchronized (mPackages) { 3733 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3734 if (obj instanceof SharedUserSetting) { 3735 final SharedUserSetting sus = (SharedUserSetting) obj; 3736 return sus.pkgPrivateFlags; 3737 } else if (obj instanceof PackageSetting) { 3738 final PackageSetting ps = (PackageSetting) obj; 3739 return ps.pkgPrivateFlags; 3740 } 3741 } 3742 return 0; 3743 } 3744 3745 @Override 3746 public boolean isUidPrivileged(int uid) { 3747 uid = UserHandle.getAppId(uid); 3748 // reader 3749 synchronized (mPackages) { 3750 Object obj = mSettings.getUserIdLPr(uid); 3751 if (obj instanceof SharedUserSetting) { 3752 final SharedUserSetting sus = (SharedUserSetting) obj; 3753 final Iterator<PackageSetting> it = sus.packages.iterator(); 3754 while (it.hasNext()) { 3755 if (it.next().isPrivileged()) { 3756 return true; 3757 } 3758 } 3759 } else if (obj instanceof PackageSetting) { 3760 final PackageSetting ps = (PackageSetting) obj; 3761 return ps.isPrivileged(); 3762 } 3763 } 3764 return false; 3765 } 3766 3767 @Override 3768 public String[] getAppOpPermissionPackages(String permissionName) { 3769 synchronized (mPackages) { 3770 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3771 if (pkgs == null) { 3772 return null; 3773 } 3774 return pkgs.toArray(new String[pkgs.size()]); 3775 } 3776 } 3777 3778 @Override 3779 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3780 int flags, int userId) { 3781 if (!sUserManager.exists(userId)) return null; 3782 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3783 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3784 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3785 } 3786 3787 @Override 3788 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3789 IntentFilter filter, int match, ComponentName activity) { 3790 final int userId = UserHandle.getCallingUserId(); 3791 if (DEBUG_PREFERRED) { 3792 Log.v(TAG, "setLastChosenActivity intent=" + intent 3793 + " resolvedType=" + resolvedType 3794 + " flags=" + flags 3795 + " filter=" + filter 3796 + " match=" + match 3797 + " activity=" + activity); 3798 filter.dump(new PrintStreamPrinter(System.out), " "); 3799 } 3800 intent.setComponent(null); 3801 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3802 // Find any earlier preferred or last chosen entries and nuke them 3803 findPreferredActivity(intent, resolvedType, 3804 flags, query, 0, false, true, false, userId); 3805 // Add the new activity as the last chosen for this filter 3806 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3807 "Setting last chosen"); 3808 } 3809 3810 @Override 3811 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3812 final int userId = UserHandle.getCallingUserId(); 3813 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3814 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3815 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3816 false, false, false, userId); 3817 } 3818 3819 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3820 int flags, List<ResolveInfo> query, int userId) { 3821 if (query != null) { 3822 final int N = query.size(); 3823 if (N == 1) { 3824 return query.get(0); 3825 } else if (N > 1) { 3826 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3827 // If there is more than one activity with the same priority, 3828 // then let the user decide between them. 3829 ResolveInfo r0 = query.get(0); 3830 ResolveInfo r1 = query.get(1); 3831 if (DEBUG_INTENT_MATCHING || debug) { 3832 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3833 + r1.activityInfo.name + "=" + r1.priority); 3834 } 3835 // If the first activity has a higher priority, or a different 3836 // default, then it is always desireable to pick it. 3837 if (r0.priority != r1.priority 3838 || r0.preferredOrder != r1.preferredOrder 3839 || r0.isDefault != r1.isDefault) { 3840 return query.get(0); 3841 } 3842 // If we have saved a preference for a preferred activity for 3843 // this Intent, use that. 3844 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3845 flags, query, r0.priority, true, false, debug, userId); 3846 if (ri != null) { 3847 return ri; 3848 } 3849 if (userId != 0) { 3850 ri = new ResolveInfo(mResolveInfo); 3851 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3852 ri.activityInfo.applicationInfo = new ApplicationInfo( 3853 ri.activityInfo.applicationInfo); 3854 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3855 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3856 return ri; 3857 } 3858 return mResolveInfo; 3859 } 3860 } 3861 return null; 3862 } 3863 3864 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3865 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3866 final int N = query.size(); 3867 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3868 .get(userId); 3869 // Get the list of persistent preferred activities that handle the intent 3870 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3871 List<PersistentPreferredActivity> pprefs = ppir != null 3872 ? ppir.queryIntent(intent, resolvedType, 3873 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3874 : null; 3875 if (pprefs != null && pprefs.size() > 0) { 3876 final int M = pprefs.size(); 3877 for (int i=0; i<M; i++) { 3878 final PersistentPreferredActivity ppa = pprefs.get(i); 3879 if (DEBUG_PREFERRED || debug) { 3880 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3881 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3882 + "\n component=" + ppa.mComponent); 3883 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3884 } 3885 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3886 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3887 if (DEBUG_PREFERRED || debug) { 3888 Slog.v(TAG, "Found persistent preferred activity:"); 3889 if (ai != null) { 3890 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3891 } else { 3892 Slog.v(TAG, " null"); 3893 } 3894 } 3895 if (ai == null) { 3896 // This previously registered persistent preferred activity 3897 // component is no longer known. Ignore it and do NOT remove it. 3898 continue; 3899 } 3900 for (int j=0; j<N; j++) { 3901 final ResolveInfo ri = query.get(j); 3902 if (!ri.activityInfo.applicationInfo.packageName 3903 .equals(ai.applicationInfo.packageName)) { 3904 continue; 3905 } 3906 if (!ri.activityInfo.name.equals(ai.name)) { 3907 continue; 3908 } 3909 // Found a persistent preference that can handle the intent. 3910 if (DEBUG_PREFERRED || debug) { 3911 Slog.v(TAG, "Returning persistent preferred activity: " + 3912 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3913 } 3914 return ri; 3915 } 3916 } 3917 } 3918 return null; 3919 } 3920 3921 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3922 List<ResolveInfo> query, int priority, boolean always, 3923 boolean removeMatches, boolean debug, int userId) { 3924 if (!sUserManager.exists(userId)) return null; 3925 // writer 3926 synchronized (mPackages) { 3927 if (intent.getSelector() != null) { 3928 intent = intent.getSelector(); 3929 } 3930 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3931 3932 // Try to find a matching persistent preferred activity. 3933 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3934 debug, userId); 3935 3936 // If a persistent preferred activity matched, use it. 3937 if (pri != null) { 3938 return pri; 3939 } 3940 3941 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3942 // Get the list of preferred activities that handle the intent 3943 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3944 List<PreferredActivity> prefs = pir != null 3945 ? pir.queryIntent(intent, resolvedType, 3946 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3947 : null; 3948 if (prefs != null && prefs.size() > 0) { 3949 boolean changed = false; 3950 try { 3951 // First figure out how good the original match set is. 3952 // We will only allow preferred activities that came 3953 // from the same match quality. 3954 int match = 0; 3955 3956 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3957 3958 final int N = query.size(); 3959 for (int j=0; j<N; j++) { 3960 final ResolveInfo ri = query.get(j); 3961 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3962 + ": 0x" + Integer.toHexString(match)); 3963 if (ri.match > match) { 3964 match = ri.match; 3965 } 3966 } 3967 3968 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3969 + Integer.toHexString(match)); 3970 3971 match &= IntentFilter.MATCH_CATEGORY_MASK; 3972 final int M = prefs.size(); 3973 for (int i=0; i<M; i++) { 3974 final PreferredActivity pa = prefs.get(i); 3975 if (DEBUG_PREFERRED || debug) { 3976 Slog.v(TAG, "Checking PreferredActivity ds=" 3977 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3978 + "\n component=" + pa.mPref.mComponent); 3979 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3980 } 3981 if (pa.mPref.mMatch != match) { 3982 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3983 + Integer.toHexString(pa.mPref.mMatch)); 3984 continue; 3985 } 3986 // If it's not an "always" type preferred activity and that's what we're 3987 // looking for, skip it. 3988 if (always && !pa.mPref.mAlways) { 3989 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3990 continue; 3991 } 3992 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3993 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3994 if (DEBUG_PREFERRED || debug) { 3995 Slog.v(TAG, "Found preferred activity:"); 3996 if (ai != null) { 3997 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3998 } else { 3999 Slog.v(TAG, " null"); 4000 } 4001 } 4002 if (ai == null) { 4003 // This previously registered preferred activity 4004 // component is no longer known. Most likely an update 4005 // to the app was installed and in the new version this 4006 // component no longer exists. Clean it up by removing 4007 // it from the preferred activities list, and skip it. 4008 Slog.w(TAG, "Removing dangling preferred activity: " 4009 + pa.mPref.mComponent); 4010 pir.removeFilter(pa); 4011 changed = true; 4012 continue; 4013 } 4014 for (int j=0; j<N; j++) { 4015 final ResolveInfo ri = query.get(j); 4016 if (!ri.activityInfo.applicationInfo.packageName 4017 .equals(ai.applicationInfo.packageName)) { 4018 continue; 4019 } 4020 if (!ri.activityInfo.name.equals(ai.name)) { 4021 continue; 4022 } 4023 4024 if (removeMatches) { 4025 pir.removeFilter(pa); 4026 changed = true; 4027 if (DEBUG_PREFERRED) { 4028 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4029 } 4030 break; 4031 } 4032 4033 // Okay we found a previously set preferred or last chosen app. 4034 // If the result set is different from when this 4035 // was created, we need to clear it and re-ask the 4036 // user their preference, if we're looking for an "always" type entry. 4037 if (always && !pa.mPref.sameSet(query)) { 4038 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4039 + intent + " type " + resolvedType); 4040 if (DEBUG_PREFERRED) { 4041 Slog.v(TAG, "Removing preferred activity since set changed " 4042 + pa.mPref.mComponent); 4043 } 4044 pir.removeFilter(pa); 4045 // Re-add the filter as a "last chosen" entry (!always) 4046 PreferredActivity lastChosen = new PreferredActivity( 4047 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4048 pir.addFilter(lastChosen); 4049 changed = true; 4050 return null; 4051 } 4052 4053 // Yay! Either the set matched or we're looking for the last chosen 4054 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4055 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4056 return ri; 4057 } 4058 } 4059 } finally { 4060 if (changed) { 4061 if (DEBUG_PREFERRED) { 4062 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4063 } 4064 scheduleWritePackageRestrictionsLocked(userId); 4065 } 4066 } 4067 } 4068 } 4069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4070 return null; 4071 } 4072 4073 /* 4074 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4075 */ 4076 @Override 4077 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4078 int targetUserId) { 4079 mContext.enforceCallingOrSelfPermission( 4080 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4081 List<CrossProfileIntentFilter> matches = 4082 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4083 if (matches != null) { 4084 int size = matches.size(); 4085 for (int i = 0; i < size; i++) { 4086 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4087 } 4088 } 4089 return false; 4090 } 4091 4092 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4093 String resolvedType, int userId) { 4094 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4095 if (resolver != null) { 4096 return resolver.queryIntent(intent, resolvedType, false, userId); 4097 } 4098 return null; 4099 } 4100 4101 @Override 4102 public List<ResolveInfo> queryIntentActivities(Intent intent, 4103 String resolvedType, int flags, int userId) { 4104 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4105 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4106 ComponentName comp = intent.getComponent(); 4107 if (comp == null) { 4108 if (intent.getSelector() != null) { 4109 intent = intent.getSelector(); 4110 comp = intent.getComponent(); 4111 } 4112 } 4113 4114 if (comp != null) { 4115 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4116 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4117 if (ai != null) { 4118 final ResolveInfo ri = new ResolveInfo(); 4119 ri.activityInfo = ai; 4120 list.add(ri); 4121 } 4122 return list; 4123 } 4124 4125 // reader 4126 synchronized (mPackages) { 4127 final String pkgName = intent.getPackage(); 4128 if (pkgName == null) { 4129 List<CrossProfileIntentFilter> matchingFilters = 4130 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4131 // Check for results that need to skip the current profile. 4132 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4133 resolvedType, flags, userId); 4134 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4135 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4136 result.add(resolveInfo); 4137 return filterIfNotPrimaryUser(result, userId); 4138 } 4139 4140 // Check for results in the current profile. 4141 List<ResolveInfo> result = mActivities.queryIntent( 4142 intent, resolvedType, flags, userId); 4143 4144 // Check for cross profile results. 4145 resolveInfo = queryCrossProfileIntents( 4146 matchingFilters, intent, resolvedType, flags, userId); 4147 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4148 result.add(resolveInfo); 4149 Collections.sort(result, mResolvePrioritySorter); 4150 } 4151 result = filterIfNotPrimaryUser(result, userId); 4152 if (result.size() > 1 && hasWebURI(intent)) { 4153 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4154 } 4155 return result; 4156 } 4157 final PackageParser.Package pkg = mPackages.get(pkgName); 4158 if (pkg != null) { 4159 return filterIfNotPrimaryUser( 4160 mActivities.queryIntentForPackage( 4161 intent, resolvedType, flags, pkg.activities, userId), 4162 userId); 4163 } 4164 return new ArrayList<ResolveInfo>(); 4165 } 4166 } 4167 4168 private boolean isUserEnabled(int userId) { 4169 long callingId = Binder.clearCallingIdentity(); 4170 try { 4171 UserInfo userInfo = sUserManager.getUserInfo(userId); 4172 return userInfo != null && userInfo.isEnabled(); 4173 } finally { 4174 Binder.restoreCallingIdentity(callingId); 4175 } 4176 } 4177 4178 /** 4179 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4180 * 4181 * @return filtered list 4182 */ 4183 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4184 if (userId == UserHandle.USER_OWNER) { 4185 return resolveInfos; 4186 } 4187 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4188 ResolveInfo info = resolveInfos.get(i); 4189 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4190 resolveInfos.remove(i); 4191 } 4192 } 4193 return resolveInfos; 4194 } 4195 4196 private static boolean hasWebURI(Intent intent) { 4197 if (intent.getData() == null) { 4198 return false; 4199 } 4200 final String scheme = intent.getScheme(); 4201 if (TextUtils.isEmpty(scheme)) { 4202 return false; 4203 } 4204 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4205 } 4206 4207 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4208 int flags, List<ResolveInfo> candidates) { 4209 if (DEBUG_PREFERRED) { 4210 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4211 candidates.size()); 4212 } 4213 4214 final int userId = UserHandle.getCallingUserId(); 4215 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4216 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4217 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4218 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4219 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4220 4221 synchronized (mPackages) { 4222 final int count = candidates.size(); 4223 // First, try to use the domain prefered App. Partition the candidates into four lists: 4224 // one for the final results, one for the "do not use ever", one for "undefined status" 4225 // and finally one for "Browser App type". 4226 for (int n=0; n<count; n++) { 4227 ResolveInfo info = candidates.get(n); 4228 String packageName = info.activityInfo.packageName; 4229 PackageSetting ps = mSettings.mPackages.get(packageName); 4230 if (ps != null) { 4231 // Add to the special match all list (Browser use case) 4232 if (info.handleAllWebDataURI) { 4233 matchAllList.add(info); 4234 continue; 4235 } 4236 // Try to get the status from User settings first 4237 int status = getDomainVerificationStatusLPr(ps, userId); 4238 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4239 alwaysList.add(info); 4240 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4241 neverList.add(info); 4242 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4243 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4244 undefinedList.add(info); 4245 } 4246 } 4247 } 4248 // First try to add the "always" if there is any 4249 if (alwaysList.size() > 0) { 4250 result.addAll(alwaysList); 4251 } else { 4252 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4253 result.addAll(undefinedList); 4254 // Also add Browsers (all of them or only the default one) 4255 if ((flags & MATCH_ALL) != 0) { 4256 result.addAll(matchAllList); 4257 } else { 4258 // Try to add the Default Browser if we can 4259 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4260 UserHandle.myUserId()); 4261 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4262 boolean defaultBrowserFound = false; 4263 final int browserCount = matchAllList.size(); 4264 for (int n=0; n<browserCount; n++) { 4265 ResolveInfo browser = matchAllList.get(n); 4266 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4267 result.add(browser); 4268 defaultBrowserFound = true; 4269 break; 4270 } 4271 } 4272 if (!defaultBrowserFound) { 4273 result.addAll(matchAllList); 4274 } 4275 } else { 4276 result.addAll(matchAllList); 4277 } 4278 } 4279 4280 // If there is nothing selected, add all candidates and remove the ones that the User 4281 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4282 if (result.size() == 0) { 4283 result.addAll(candidates); 4284 result.removeAll(neverList); 4285 } 4286 } 4287 } 4288 if (DEBUG_PREFERRED) { 4289 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4290 result.size()); 4291 } 4292 return result; 4293 } 4294 4295 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4296 int status = ps.getDomainVerificationStatusForUser(userId); 4297 // if none available, get the master status 4298 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4299 if (ps.getIntentFilterVerificationInfo() != null) { 4300 status = ps.getIntentFilterVerificationInfo().getStatus(); 4301 } 4302 } 4303 return status; 4304 } 4305 4306 private ResolveInfo querySkipCurrentProfileIntents( 4307 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4308 int flags, int sourceUserId) { 4309 if (matchingFilters != null) { 4310 int size = matchingFilters.size(); 4311 for (int i = 0; i < size; i ++) { 4312 CrossProfileIntentFilter filter = matchingFilters.get(i); 4313 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4314 // Checking if there are activities in the target user that can handle the 4315 // intent. 4316 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4317 flags, sourceUserId); 4318 if (resolveInfo != null) { 4319 return resolveInfo; 4320 } 4321 } 4322 } 4323 } 4324 return null; 4325 } 4326 4327 // Return matching ResolveInfo if any for skip current profile intent filters. 4328 private ResolveInfo queryCrossProfileIntents( 4329 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4330 int flags, int sourceUserId) { 4331 if (matchingFilters != null) { 4332 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4333 // match the same intent. For performance reasons, it is better not to 4334 // run queryIntent twice for the same userId 4335 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4336 int size = matchingFilters.size(); 4337 for (int i = 0; i < size; i++) { 4338 CrossProfileIntentFilter filter = matchingFilters.get(i); 4339 int targetUserId = filter.getTargetUserId(); 4340 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4341 && !alreadyTriedUserIds.get(targetUserId)) { 4342 // Checking if there are activities in the target user that can handle the 4343 // intent. 4344 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4345 flags, sourceUserId); 4346 if (resolveInfo != null) return resolveInfo; 4347 alreadyTriedUserIds.put(targetUserId, true); 4348 } 4349 } 4350 } 4351 return null; 4352 } 4353 4354 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4355 String resolvedType, int flags, int sourceUserId) { 4356 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4357 resolvedType, flags, filter.getTargetUserId()); 4358 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4359 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4360 } 4361 return null; 4362 } 4363 4364 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4365 int sourceUserId, int targetUserId) { 4366 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4367 String className; 4368 if (targetUserId == UserHandle.USER_OWNER) { 4369 className = FORWARD_INTENT_TO_USER_OWNER; 4370 } else { 4371 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4372 } 4373 ComponentName forwardingActivityComponentName = new ComponentName( 4374 mAndroidApplication.packageName, className); 4375 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4376 sourceUserId); 4377 if (targetUserId == UserHandle.USER_OWNER) { 4378 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4379 forwardingResolveInfo.noResourceId = true; 4380 } 4381 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4382 forwardingResolveInfo.priority = 0; 4383 forwardingResolveInfo.preferredOrder = 0; 4384 forwardingResolveInfo.match = 0; 4385 forwardingResolveInfo.isDefault = true; 4386 forwardingResolveInfo.filter = filter; 4387 forwardingResolveInfo.targetUserId = targetUserId; 4388 return forwardingResolveInfo; 4389 } 4390 4391 @Override 4392 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4393 Intent[] specifics, String[] specificTypes, Intent intent, 4394 String resolvedType, int flags, int userId) { 4395 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4396 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4397 false, "query intent activity options"); 4398 final String resultsAction = intent.getAction(); 4399 4400 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4401 | PackageManager.GET_RESOLVED_FILTER, userId); 4402 4403 if (DEBUG_INTENT_MATCHING) { 4404 Log.v(TAG, "Query " + intent + ": " + results); 4405 } 4406 4407 int specificsPos = 0; 4408 int N; 4409 4410 // todo: note that the algorithm used here is O(N^2). This 4411 // isn't a problem in our current environment, but if we start running 4412 // into situations where we have more than 5 or 10 matches then this 4413 // should probably be changed to something smarter... 4414 4415 // First we go through and resolve each of the specific items 4416 // that were supplied, taking care of removing any corresponding 4417 // duplicate items in the generic resolve list. 4418 if (specifics != null) { 4419 for (int i=0; i<specifics.length; i++) { 4420 final Intent sintent = specifics[i]; 4421 if (sintent == null) { 4422 continue; 4423 } 4424 4425 if (DEBUG_INTENT_MATCHING) { 4426 Log.v(TAG, "Specific #" + i + ": " + sintent); 4427 } 4428 4429 String action = sintent.getAction(); 4430 if (resultsAction != null && resultsAction.equals(action)) { 4431 // If this action was explicitly requested, then don't 4432 // remove things that have it. 4433 action = null; 4434 } 4435 4436 ResolveInfo ri = null; 4437 ActivityInfo ai = null; 4438 4439 ComponentName comp = sintent.getComponent(); 4440 if (comp == null) { 4441 ri = resolveIntent( 4442 sintent, 4443 specificTypes != null ? specificTypes[i] : null, 4444 flags, userId); 4445 if (ri == null) { 4446 continue; 4447 } 4448 if (ri == mResolveInfo) { 4449 // ACK! Must do something better with this. 4450 } 4451 ai = ri.activityInfo; 4452 comp = new ComponentName(ai.applicationInfo.packageName, 4453 ai.name); 4454 } else { 4455 ai = getActivityInfo(comp, flags, userId); 4456 if (ai == null) { 4457 continue; 4458 } 4459 } 4460 4461 // Look for any generic query activities that are duplicates 4462 // of this specific one, and remove them from the results. 4463 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4464 N = results.size(); 4465 int j; 4466 for (j=specificsPos; j<N; j++) { 4467 ResolveInfo sri = results.get(j); 4468 if ((sri.activityInfo.name.equals(comp.getClassName()) 4469 && sri.activityInfo.applicationInfo.packageName.equals( 4470 comp.getPackageName())) 4471 || (action != null && sri.filter.matchAction(action))) { 4472 results.remove(j); 4473 if (DEBUG_INTENT_MATCHING) Log.v( 4474 TAG, "Removing duplicate item from " + j 4475 + " due to specific " + specificsPos); 4476 if (ri == null) { 4477 ri = sri; 4478 } 4479 j--; 4480 N--; 4481 } 4482 } 4483 4484 // Add this specific item to its proper place. 4485 if (ri == null) { 4486 ri = new ResolveInfo(); 4487 ri.activityInfo = ai; 4488 } 4489 results.add(specificsPos, ri); 4490 ri.specificIndex = i; 4491 specificsPos++; 4492 } 4493 } 4494 4495 // Now we go through the remaining generic results and remove any 4496 // duplicate actions that are found here. 4497 N = results.size(); 4498 for (int i=specificsPos; i<N-1; i++) { 4499 final ResolveInfo rii = results.get(i); 4500 if (rii.filter == null) { 4501 continue; 4502 } 4503 4504 // Iterate over all of the actions of this result's intent 4505 // filter... typically this should be just one. 4506 final Iterator<String> it = rii.filter.actionsIterator(); 4507 if (it == null) { 4508 continue; 4509 } 4510 while (it.hasNext()) { 4511 final String action = it.next(); 4512 if (resultsAction != null && resultsAction.equals(action)) { 4513 // If this action was explicitly requested, then don't 4514 // remove things that have it. 4515 continue; 4516 } 4517 for (int j=i+1; j<N; j++) { 4518 final ResolveInfo rij = results.get(j); 4519 if (rij.filter != null && rij.filter.hasAction(action)) { 4520 results.remove(j); 4521 if (DEBUG_INTENT_MATCHING) Log.v( 4522 TAG, "Removing duplicate item from " + j 4523 + " due to action " + action + " at " + i); 4524 j--; 4525 N--; 4526 } 4527 } 4528 } 4529 4530 // If the caller didn't request filter information, drop it now 4531 // so we don't have to marshall/unmarshall it. 4532 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4533 rii.filter = null; 4534 } 4535 } 4536 4537 // Filter out the caller activity if so requested. 4538 if (caller != null) { 4539 N = results.size(); 4540 for (int i=0; i<N; i++) { 4541 ActivityInfo ainfo = results.get(i).activityInfo; 4542 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4543 && caller.getClassName().equals(ainfo.name)) { 4544 results.remove(i); 4545 break; 4546 } 4547 } 4548 } 4549 4550 // If the caller didn't request filter information, 4551 // drop them now so we don't have to 4552 // marshall/unmarshall it. 4553 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4554 N = results.size(); 4555 for (int i=0; i<N; i++) { 4556 results.get(i).filter = null; 4557 } 4558 } 4559 4560 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4561 return results; 4562 } 4563 4564 @Override 4565 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4566 int userId) { 4567 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4568 ComponentName comp = intent.getComponent(); 4569 if (comp == null) { 4570 if (intent.getSelector() != null) { 4571 intent = intent.getSelector(); 4572 comp = intent.getComponent(); 4573 } 4574 } 4575 if (comp != null) { 4576 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4577 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4578 if (ai != null) { 4579 ResolveInfo ri = new ResolveInfo(); 4580 ri.activityInfo = ai; 4581 list.add(ri); 4582 } 4583 return list; 4584 } 4585 4586 // reader 4587 synchronized (mPackages) { 4588 String pkgName = intent.getPackage(); 4589 if (pkgName == null) { 4590 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4591 } 4592 final PackageParser.Package pkg = mPackages.get(pkgName); 4593 if (pkg != null) { 4594 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4595 userId); 4596 } 4597 return null; 4598 } 4599 } 4600 4601 @Override 4602 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4603 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4604 if (!sUserManager.exists(userId)) return null; 4605 if (query != null) { 4606 if (query.size() >= 1) { 4607 // If there is more than one service with the same priority, 4608 // just arbitrarily pick the first one. 4609 return query.get(0); 4610 } 4611 } 4612 return null; 4613 } 4614 4615 @Override 4616 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4617 int userId) { 4618 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4619 ComponentName comp = intent.getComponent(); 4620 if (comp == null) { 4621 if (intent.getSelector() != null) { 4622 intent = intent.getSelector(); 4623 comp = intent.getComponent(); 4624 } 4625 } 4626 if (comp != null) { 4627 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4628 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4629 if (si != null) { 4630 final ResolveInfo ri = new ResolveInfo(); 4631 ri.serviceInfo = si; 4632 list.add(ri); 4633 } 4634 return list; 4635 } 4636 4637 // reader 4638 synchronized (mPackages) { 4639 String pkgName = intent.getPackage(); 4640 if (pkgName == null) { 4641 return mServices.queryIntent(intent, resolvedType, flags, userId); 4642 } 4643 final PackageParser.Package pkg = mPackages.get(pkgName); 4644 if (pkg != null) { 4645 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4646 userId); 4647 } 4648 return null; 4649 } 4650 } 4651 4652 @Override 4653 public List<ResolveInfo> queryIntentContentProviders( 4654 Intent intent, String resolvedType, int flags, int userId) { 4655 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4656 ComponentName comp = intent.getComponent(); 4657 if (comp == null) { 4658 if (intent.getSelector() != null) { 4659 intent = intent.getSelector(); 4660 comp = intent.getComponent(); 4661 } 4662 } 4663 if (comp != null) { 4664 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4665 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4666 if (pi != null) { 4667 final ResolveInfo ri = new ResolveInfo(); 4668 ri.providerInfo = pi; 4669 list.add(ri); 4670 } 4671 return list; 4672 } 4673 4674 // reader 4675 synchronized (mPackages) { 4676 String pkgName = intent.getPackage(); 4677 if (pkgName == null) { 4678 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4679 } 4680 final PackageParser.Package pkg = mPackages.get(pkgName); 4681 if (pkg != null) { 4682 return mProviders.queryIntentForPackage( 4683 intent, resolvedType, flags, pkg.providers, userId); 4684 } 4685 return null; 4686 } 4687 } 4688 4689 @Override 4690 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4691 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4692 4693 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4694 4695 // writer 4696 synchronized (mPackages) { 4697 ArrayList<PackageInfo> list; 4698 if (listUninstalled) { 4699 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4700 for (PackageSetting ps : mSettings.mPackages.values()) { 4701 PackageInfo pi; 4702 if (ps.pkg != null) { 4703 pi = generatePackageInfo(ps.pkg, flags, userId); 4704 } else { 4705 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4706 } 4707 if (pi != null) { 4708 list.add(pi); 4709 } 4710 } 4711 } else { 4712 list = new ArrayList<PackageInfo>(mPackages.size()); 4713 for (PackageParser.Package p : mPackages.values()) { 4714 PackageInfo pi = generatePackageInfo(p, flags, userId); 4715 if (pi != null) { 4716 list.add(pi); 4717 } 4718 } 4719 } 4720 4721 return new ParceledListSlice<PackageInfo>(list); 4722 } 4723 } 4724 4725 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4726 String[] permissions, boolean[] tmp, int flags, int userId) { 4727 int numMatch = 0; 4728 final PermissionsState permissionsState = ps.getPermissionsState(); 4729 for (int i=0; i<permissions.length; i++) { 4730 final String permission = permissions[i]; 4731 if (permissionsState.hasPermission(permission, userId)) { 4732 tmp[i] = true; 4733 numMatch++; 4734 } else { 4735 tmp[i] = false; 4736 } 4737 } 4738 if (numMatch == 0) { 4739 return; 4740 } 4741 PackageInfo pi; 4742 if (ps.pkg != null) { 4743 pi = generatePackageInfo(ps.pkg, flags, userId); 4744 } else { 4745 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4746 } 4747 // The above might return null in cases of uninstalled apps or install-state 4748 // skew across users/profiles. 4749 if (pi != null) { 4750 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4751 if (numMatch == permissions.length) { 4752 pi.requestedPermissions = permissions; 4753 } else { 4754 pi.requestedPermissions = new String[numMatch]; 4755 numMatch = 0; 4756 for (int i=0; i<permissions.length; i++) { 4757 if (tmp[i]) { 4758 pi.requestedPermissions[numMatch] = permissions[i]; 4759 numMatch++; 4760 } 4761 } 4762 } 4763 } 4764 list.add(pi); 4765 } 4766 } 4767 4768 @Override 4769 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4770 String[] permissions, int flags, int userId) { 4771 if (!sUserManager.exists(userId)) return null; 4772 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4773 4774 // writer 4775 synchronized (mPackages) { 4776 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4777 boolean[] tmpBools = new boolean[permissions.length]; 4778 if (listUninstalled) { 4779 for (PackageSetting ps : mSettings.mPackages.values()) { 4780 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4781 } 4782 } else { 4783 for (PackageParser.Package pkg : mPackages.values()) { 4784 PackageSetting ps = (PackageSetting)pkg.mExtras; 4785 if (ps != null) { 4786 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4787 userId); 4788 } 4789 } 4790 } 4791 4792 return new ParceledListSlice<PackageInfo>(list); 4793 } 4794 } 4795 4796 @Override 4797 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4798 if (!sUserManager.exists(userId)) return null; 4799 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4800 4801 // writer 4802 synchronized (mPackages) { 4803 ArrayList<ApplicationInfo> list; 4804 if (listUninstalled) { 4805 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4806 for (PackageSetting ps : mSettings.mPackages.values()) { 4807 ApplicationInfo ai; 4808 if (ps.pkg != null) { 4809 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4810 ps.readUserState(userId), userId); 4811 } else { 4812 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4813 } 4814 if (ai != null) { 4815 list.add(ai); 4816 } 4817 } 4818 } else { 4819 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4820 for (PackageParser.Package p : mPackages.values()) { 4821 if (p.mExtras != null) { 4822 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4823 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4824 if (ai != null) { 4825 list.add(ai); 4826 } 4827 } 4828 } 4829 } 4830 4831 return new ParceledListSlice<ApplicationInfo>(list); 4832 } 4833 } 4834 4835 public List<ApplicationInfo> getPersistentApplications(int flags) { 4836 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4837 4838 // reader 4839 synchronized (mPackages) { 4840 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4841 final int userId = UserHandle.getCallingUserId(); 4842 while (i.hasNext()) { 4843 final PackageParser.Package p = i.next(); 4844 if (p.applicationInfo != null 4845 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4846 && (!mSafeMode || isSystemApp(p))) { 4847 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4848 if (ps != null) { 4849 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4850 ps.readUserState(userId), userId); 4851 if (ai != null) { 4852 finalList.add(ai); 4853 } 4854 } 4855 } 4856 } 4857 } 4858 4859 return finalList; 4860 } 4861 4862 @Override 4863 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4864 if (!sUserManager.exists(userId)) return null; 4865 // reader 4866 synchronized (mPackages) { 4867 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4868 PackageSetting ps = provider != null 4869 ? mSettings.mPackages.get(provider.owner.packageName) 4870 : null; 4871 return ps != null 4872 && mSettings.isEnabledLPr(provider.info, flags, userId) 4873 && (!mSafeMode || (provider.info.applicationInfo.flags 4874 &ApplicationInfo.FLAG_SYSTEM) != 0) 4875 ? PackageParser.generateProviderInfo(provider, flags, 4876 ps.readUserState(userId), userId) 4877 : null; 4878 } 4879 } 4880 4881 /** 4882 * @deprecated 4883 */ 4884 @Deprecated 4885 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4886 // reader 4887 synchronized (mPackages) { 4888 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4889 .entrySet().iterator(); 4890 final int userId = UserHandle.getCallingUserId(); 4891 while (i.hasNext()) { 4892 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4893 PackageParser.Provider p = entry.getValue(); 4894 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4895 4896 if (ps != null && p.syncable 4897 && (!mSafeMode || (p.info.applicationInfo.flags 4898 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4899 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4900 ps.readUserState(userId), userId); 4901 if (info != null) { 4902 outNames.add(entry.getKey()); 4903 outInfo.add(info); 4904 } 4905 } 4906 } 4907 } 4908 } 4909 4910 @Override 4911 public List<ProviderInfo> queryContentProviders(String processName, 4912 int uid, int flags) { 4913 ArrayList<ProviderInfo> finalList = null; 4914 // reader 4915 synchronized (mPackages) { 4916 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4917 final int userId = processName != null ? 4918 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4919 while (i.hasNext()) { 4920 final PackageParser.Provider p = i.next(); 4921 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4922 if (ps != null && p.info.authority != null 4923 && (processName == null 4924 || (p.info.processName.equals(processName) 4925 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4926 && mSettings.isEnabledLPr(p.info, flags, userId) 4927 && (!mSafeMode 4928 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4929 if (finalList == null) { 4930 finalList = new ArrayList<ProviderInfo>(3); 4931 } 4932 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4933 ps.readUserState(userId), userId); 4934 if (info != null) { 4935 finalList.add(info); 4936 } 4937 } 4938 } 4939 } 4940 4941 if (finalList != null) { 4942 Collections.sort(finalList, mProviderInitOrderSorter); 4943 } 4944 4945 return finalList; 4946 } 4947 4948 @Override 4949 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4950 int flags) { 4951 // reader 4952 synchronized (mPackages) { 4953 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4954 return PackageParser.generateInstrumentationInfo(i, flags); 4955 } 4956 } 4957 4958 @Override 4959 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4960 int flags) { 4961 ArrayList<InstrumentationInfo> finalList = 4962 new ArrayList<InstrumentationInfo>(); 4963 4964 // reader 4965 synchronized (mPackages) { 4966 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4967 while (i.hasNext()) { 4968 final PackageParser.Instrumentation p = i.next(); 4969 if (targetPackage == null 4970 || targetPackage.equals(p.info.targetPackage)) { 4971 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4972 flags); 4973 if (ii != null) { 4974 finalList.add(ii); 4975 } 4976 } 4977 } 4978 } 4979 4980 return finalList; 4981 } 4982 4983 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4984 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4985 if (overlays == null) { 4986 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4987 return; 4988 } 4989 for (PackageParser.Package opkg : overlays.values()) { 4990 // Not much to do if idmap fails: we already logged the error 4991 // and we certainly don't want to abort installation of pkg simply 4992 // because an overlay didn't fit properly. For these reasons, 4993 // ignore the return value of createIdmapForPackagePairLI. 4994 createIdmapForPackagePairLI(pkg, opkg); 4995 } 4996 } 4997 4998 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4999 PackageParser.Package opkg) { 5000 if (!opkg.mTrustedOverlay) { 5001 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5002 opkg.baseCodePath + ": overlay not trusted"); 5003 return false; 5004 } 5005 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5006 if (overlaySet == null) { 5007 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5008 opkg.baseCodePath + " but target package has no known overlays"); 5009 return false; 5010 } 5011 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5012 // TODO: generate idmap for split APKs 5013 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5014 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5015 + opkg.baseCodePath); 5016 return false; 5017 } 5018 PackageParser.Package[] overlayArray = 5019 overlaySet.values().toArray(new PackageParser.Package[0]); 5020 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5021 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5022 return p1.mOverlayPriority - p2.mOverlayPriority; 5023 } 5024 }; 5025 Arrays.sort(overlayArray, cmp); 5026 5027 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5028 int i = 0; 5029 for (PackageParser.Package p : overlayArray) { 5030 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5031 } 5032 return true; 5033 } 5034 5035 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5036 final File[] files = dir.listFiles(); 5037 if (ArrayUtils.isEmpty(files)) { 5038 Log.d(TAG, "No files in app dir " + dir); 5039 return; 5040 } 5041 5042 if (DEBUG_PACKAGE_SCANNING) { 5043 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5044 + " flags=0x" + Integer.toHexString(parseFlags)); 5045 } 5046 5047 for (File file : files) { 5048 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5049 && !PackageInstallerService.isStageName(file.getName()); 5050 if (!isPackage) { 5051 // Ignore entries which are not packages 5052 continue; 5053 } 5054 try { 5055 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5056 scanFlags, currentTime, null); 5057 } catch (PackageManagerException e) { 5058 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5059 5060 // Delete invalid userdata apps 5061 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5062 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5063 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5064 if (file.isDirectory()) { 5065 mInstaller.rmPackageDir(file.getAbsolutePath()); 5066 } else { 5067 file.delete(); 5068 } 5069 } 5070 } 5071 } 5072 } 5073 5074 private static File getSettingsProblemFile() { 5075 File dataDir = Environment.getDataDirectory(); 5076 File systemDir = new File(dataDir, "system"); 5077 File fname = new File(systemDir, "uiderrors.txt"); 5078 return fname; 5079 } 5080 5081 static void reportSettingsProblem(int priority, String msg) { 5082 logCriticalInfo(priority, msg); 5083 } 5084 5085 static void logCriticalInfo(int priority, String msg) { 5086 Slog.println(priority, TAG, msg); 5087 EventLogTags.writePmCriticalInfo(msg); 5088 try { 5089 File fname = getSettingsProblemFile(); 5090 FileOutputStream out = new FileOutputStream(fname, true); 5091 PrintWriter pw = new FastPrintWriter(out); 5092 SimpleDateFormat formatter = new SimpleDateFormat(); 5093 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5094 pw.println(dateString + ": " + msg); 5095 pw.close(); 5096 FileUtils.setPermissions( 5097 fname.toString(), 5098 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5099 -1, -1); 5100 } catch (java.io.IOException e) { 5101 } 5102 } 5103 5104 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5105 PackageParser.Package pkg, File srcFile, int parseFlags) 5106 throws PackageManagerException { 5107 if (ps != null 5108 && ps.codePath.equals(srcFile) 5109 && ps.timeStamp == srcFile.lastModified() 5110 && !isCompatSignatureUpdateNeeded(pkg) 5111 && !isRecoverSignatureUpdateNeeded(pkg)) { 5112 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5113 if (ps.signatures.mSignatures != null 5114 && ps.signatures.mSignatures.length != 0 5115 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5116 // Optimization: reuse the existing cached certificates 5117 // if the package appears to be unchanged. 5118 pkg.mSignatures = ps.signatures.mSignatures; 5119 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5120 synchronized (mPackages) { 5121 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5122 } 5123 return; 5124 } 5125 5126 Slog.w(TAG, "PackageSetting for " + ps.name 5127 + " is missing signatures. Collecting certs again to recover them."); 5128 } else { 5129 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5130 } 5131 5132 try { 5133 pp.collectCertificates(pkg, parseFlags); 5134 pp.collectManifestDigest(pkg); 5135 } catch (PackageParserException e) { 5136 throw PackageManagerException.from(e); 5137 } 5138 } 5139 5140 /* 5141 * Scan a package and return the newly parsed package. 5142 * Returns null in case of errors and the error code is stored in mLastScanError 5143 */ 5144 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5145 long currentTime, UserHandle user) throws PackageManagerException { 5146 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5147 parseFlags |= mDefParseFlags; 5148 PackageParser pp = new PackageParser(); 5149 pp.setSeparateProcesses(mSeparateProcesses); 5150 pp.setOnlyCoreApps(mOnlyCore); 5151 pp.setDisplayMetrics(mMetrics); 5152 5153 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5154 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5155 } 5156 5157 final PackageParser.Package pkg; 5158 try { 5159 pkg = pp.parsePackage(scanFile, parseFlags); 5160 } catch (PackageParserException e) { 5161 throw PackageManagerException.from(e); 5162 } 5163 5164 PackageSetting ps = null; 5165 PackageSetting updatedPkg; 5166 // reader 5167 synchronized (mPackages) { 5168 // Look to see if we already know about this package. 5169 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5170 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5171 // This package has been renamed to its original name. Let's 5172 // use that. 5173 ps = mSettings.peekPackageLPr(oldName); 5174 } 5175 // If there was no original package, see one for the real package name. 5176 if (ps == null) { 5177 ps = mSettings.peekPackageLPr(pkg.packageName); 5178 } 5179 // Check to see if this package could be hiding/updating a system 5180 // package. Must look for it either under the original or real 5181 // package name depending on our state. 5182 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5183 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5184 } 5185 boolean updatedPkgBetter = false; 5186 // First check if this is a system package that may involve an update 5187 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5188 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5189 // it needs to drop FLAG_PRIVILEGED. 5190 if (locationIsPrivileged(scanFile)) { 5191 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5192 } else { 5193 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5194 } 5195 5196 if (ps != null && !ps.codePath.equals(scanFile)) { 5197 // The path has changed from what was last scanned... check the 5198 // version of the new path against what we have stored to determine 5199 // what to do. 5200 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5201 if (pkg.mVersionCode <= ps.versionCode) { 5202 // The system package has been updated and the code path does not match 5203 // Ignore entry. Skip it. 5204 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5205 + " ignored: updated version " + ps.versionCode 5206 + " better than this " + pkg.mVersionCode); 5207 if (!updatedPkg.codePath.equals(scanFile)) { 5208 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5209 + ps.name + " changing from " + updatedPkg.codePathString 5210 + " to " + scanFile); 5211 updatedPkg.codePath = scanFile; 5212 updatedPkg.codePathString = scanFile.toString(); 5213 updatedPkg.resourcePath = scanFile; 5214 updatedPkg.resourcePathString = scanFile.toString(); 5215 } 5216 updatedPkg.pkg = pkg; 5217 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5218 } else { 5219 // The current app on the system partition is better than 5220 // what we have updated to on the data partition; switch 5221 // back to the system partition version. 5222 // At this point, its safely assumed that package installation for 5223 // apps in system partition will go through. If not there won't be a working 5224 // version of the app 5225 // writer 5226 synchronized (mPackages) { 5227 // Just remove the loaded entries from package lists. 5228 mPackages.remove(ps.name); 5229 } 5230 5231 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5232 + " reverting from " + ps.codePathString 5233 + ": new version " + pkg.mVersionCode 5234 + " better than installed " + ps.versionCode); 5235 5236 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5237 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5238 synchronized (mInstallLock) { 5239 args.cleanUpResourcesLI(); 5240 } 5241 synchronized (mPackages) { 5242 mSettings.enableSystemPackageLPw(ps.name); 5243 } 5244 updatedPkgBetter = true; 5245 } 5246 } 5247 } 5248 5249 if (updatedPkg != null) { 5250 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5251 // initially 5252 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5253 5254 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5255 // flag set initially 5256 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5257 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5258 } 5259 } 5260 5261 // Verify certificates against what was last scanned 5262 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5263 5264 /* 5265 * A new system app appeared, but we already had a non-system one of the 5266 * same name installed earlier. 5267 */ 5268 boolean shouldHideSystemApp = false; 5269 if (updatedPkg == null && ps != null 5270 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5271 /* 5272 * Check to make sure the signatures match first. If they don't, 5273 * wipe the installed application and its data. 5274 */ 5275 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5276 != PackageManager.SIGNATURE_MATCH) { 5277 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5278 + " signatures don't match existing userdata copy; removing"); 5279 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5280 ps = null; 5281 } else { 5282 /* 5283 * If the newly-added system app is an older version than the 5284 * already installed version, hide it. It will be scanned later 5285 * and re-added like an update. 5286 */ 5287 if (pkg.mVersionCode <= ps.versionCode) { 5288 shouldHideSystemApp = true; 5289 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5290 + " but new version " + pkg.mVersionCode + " better than installed " 5291 + ps.versionCode + "; hiding system"); 5292 } else { 5293 /* 5294 * The newly found system app is a newer version that the 5295 * one previously installed. Simply remove the 5296 * already-installed application and replace it with our own 5297 * while keeping the application data. 5298 */ 5299 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5300 + " reverting from " + ps.codePathString + ": new version " 5301 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5302 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5303 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5304 synchronized (mInstallLock) { 5305 args.cleanUpResourcesLI(); 5306 } 5307 } 5308 } 5309 } 5310 5311 // The apk is forward locked (not public) if its code and resources 5312 // are kept in different files. (except for app in either system or 5313 // vendor path). 5314 // TODO grab this value from PackageSettings 5315 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5316 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5317 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5318 } 5319 } 5320 5321 // TODO: extend to support forward-locked splits 5322 String resourcePath = null; 5323 String baseResourcePath = null; 5324 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5325 if (ps != null && ps.resourcePathString != null) { 5326 resourcePath = ps.resourcePathString; 5327 baseResourcePath = ps.resourcePathString; 5328 } else { 5329 // Should not happen at all. Just log an error. 5330 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5331 } 5332 } else { 5333 resourcePath = pkg.codePath; 5334 baseResourcePath = pkg.baseCodePath; 5335 } 5336 5337 // Set application objects path explicitly. 5338 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5339 pkg.applicationInfo.setCodePath(pkg.codePath); 5340 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5341 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5342 pkg.applicationInfo.setResourcePath(resourcePath); 5343 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5344 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5345 5346 // Note that we invoke the following method only if we are about to unpack an application 5347 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5348 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5349 5350 /* 5351 * If the system app should be overridden by a previously installed 5352 * data, hide the system app now and let the /data/app scan pick it up 5353 * again. 5354 */ 5355 if (shouldHideSystemApp) { 5356 synchronized (mPackages) { 5357 /* 5358 * We have to grant systems permissions before we hide, because 5359 * grantPermissions will assume the package update is trying to 5360 * expand its permissions. 5361 */ 5362 grantPermissionsLPw(pkg, true, pkg.packageName); 5363 mSettings.disableSystemPackageLPw(pkg.packageName); 5364 } 5365 } 5366 5367 return scannedPkg; 5368 } 5369 5370 private static String fixProcessName(String defProcessName, 5371 String processName, int uid) { 5372 if (processName == null) { 5373 return defProcessName; 5374 } 5375 return processName; 5376 } 5377 5378 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5379 throws PackageManagerException { 5380 if (pkgSetting.signatures.mSignatures != null) { 5381 // Already existing package. Make sure signatures match 5382 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5383 == PackageManager.SIGNATURE_MATCH; 5384 if (!match) { 5385 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5386 == PackageManager.SIGNATURE_MATCH; 5387 } 5388 if (!match) { 5389 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5390 == PackageManager.SIGNATURE_MATCH; 5391 } 5392 if (!match) { 5393 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5394 + pkg.packageName + " signatures do not match the " 5395 + "previously installed version; ignoring!"); 5396 } 5397 } 5398 5399 // Check for shared user signatures 5400 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5401 // Already existing package. Make sure signatures match 5402 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5403 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5404 if (!match) { 5405 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5406 == PackageManager.SIGNATURE_MATCH; 5407 } 5408 if (!match) { 5409 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5410 == PackageManager.SIGNATURE_MATCH; 5411 } 5412 if (!match) { 5413 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5414 "Package " + pkg.packageName 5415 + " has no signatures that match those in shared user " 5416 + pkgSetting.sharedUser.name + "; ignoring!"); 5417 } 5418 } 5419 } 5420 5421 /** 5422 * Enforces that only the system UID or root's UID can call a method exposed 5423 * via Binder. 5424 * 5425 * @param message used as message if SecurityException is thrown 5426 * @throws SecurityException if the caller is not system or root 5427 */ 5428 private static final void enforceSystemOrRoot(String message) { 5429 final int uid = Binder.getCallingUid(); 5430 if (uid != Process.SYSTEM_UID && uid != 0) { 5431 throw new SecurityException(message); 5432 } 5433 } 5434 5435 @Override 5436 public void performBootDexOpt() { 5437 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5438 5439 // Before everything else, see whether we need to fstrim. 5440 try { 5441 IMountService ms = PackageHelper.getMountService(); 5442 if (ms != null) { 5443 final boolean isUpgrade = isUpgrade(); 5444 boolean doTrim = isUpgrade; 5445 if (doTrim) { 5446 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5447 } else { 5448 final long interval = android.provider.Settings.Global.getLong( 5449 mContext.getContentResolver(), 5450 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5451 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5452 if (interval > 0) { 5453 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5454 if (timeSinceLast > interval) { 5455 doTrim = true; 5456 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5457 + "; running immediately"); 5458 } 5459 } 5460 } 5461 if (doTrim) { 5462 if (!isFirstBoot()) { 5463 try { 5464 ActivityManagerNative.getDefault().showBootMessage( 5465 mContext.getResources().getString( 5466 R.string.android_upgrading_fstrim), true); 5467 } catch (RemoteException e) { 5468 } 5469 } 5470 ms.runMaintenance(); 5471 } 5472 } else { 5473 Slog.e(TAG, "Mount service unavailable!"); 5474 } 5475 } catch (RemoteException e) { 5476 // Can't happen; MountService is local 5477 } 5478 5479 final ArraySet<PackageParser.Package> pkgs; 5480 synchronized (mPackages) { 5481 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5482 } 5483 5484 if (pkgs != null) { 5485 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5486 // in case the device runs out of space. 5487 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5488 // Give priority to core apps. 5489 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5490 PackageParser.Package pkg = it.next(); 5491 if (pkg.coreApp) { 5492 if (DEBUG_DEXOPT) { 5493 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5494 } 5495 sortedPkgs.add(pkg); 5496 it.remove(); 5497 } 5498 } 5499 // Give priority to system apps that listen for pre boot complete. 5500 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5501 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5502 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5503 PackageParser.Package pkg = it.next(); 5504 if (pkgNames.contains(pkg.packageName)) { 5505 if (DEBUG_DEXOPT) { 5506 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5507 } 5508 sortedPkgs.add(pkg); 5509 it.remove(); 5510 } 5511 } 5512 // Give priority to system apps. 5513 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5514 PackageParser.Package pkg = it.next(); 5515 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5516 if (DEBUG_DEXOPT) { 5517 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5518 } 5519 sortedPkgs.add(pkg); 5520 it.remove(); 5521 } 5522 } 5523 // Give priority to updated system apps. 5524 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5525 PackageParser.Package pkg = it.next(); 5526 if (pkg.isUpdatedSystemApp()) { 5527 if (DEBUG_DEXOPT) { 5528 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5529 } 5530 sortedPkgs.add(pkg); 5531 it.remove(); 5532 } 5533 } 5534 // Give priority to apps that listen for boot complete. 5535 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5536 pkgNames = getPackageNamesForIntent(intent); 5537 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5538 PackageParser.Package pkg = it.next(); 5539 if (pkgNames.contains(pkg.packageName)) { 5540 if (DEBUG_DEXOPT) { 5541 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5542 } 5543 sortedPkgs.add(pkg); 5544 it.remove(); 5545 } 5546 } 5547 // Filter out packages that aren't recently used. 5548 filterRecentlyUsedApps(pkgs); 5549 // Add all remaining apps. 5550 for (PackageParser.Package pkg : pkgs) { 5551 if (DEBUG_DEXOPT) { 5552 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5553 } 5554 sortedPkgs.add(pkg); 5555 } 5556 5557 // If we want to be lazy, filter everything that wasn't recently used. 5558 if (mLazyDexOpt) { 5559 filterRecentlyUsedApps(sortedPkgs); 5560 } 5561 5562 int i = 0; 5563 int total = sortedPkgs.size(); 5564 File dataDir = Environment.getDataDirectory(); 5565 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5566 if (lowThreshold == 0) { 5567 throw new IllegalStateException("Invalid low memory threshold"); 5568 } 5569 for (PackageParser.Package pkg : sortedPkgs) { 5570 long usableSpace = dataDir.getUsableSpace(); 5571 if (usableSpace < lowThreshold) { 5572 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5573 break; 5574 } 5575 performBootDexOpt(pkg, ++i, total); 5576 } 5577 } 5578 } 5579 5580 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5581 // Filter out packages that aren't recently used. 5582 // 5583 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5584 // should do a full dexopt. 5585 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5586 int total = pkgs.size(); 5587 int skipped = 0; 5588 long now = System.currentTimeMillis(); 5589 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5590 PackageParser.Package pkg = i.next(); 5591 long then = pkg.mLastPackageUsageTimeInMills; 5592 if (then + mDexOptLRUThresholdInMills < now) { 5593 if (DEBUG_DEXOPT) { 5594 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5595 ((then == 0) ? "never" : new Date(then))); 5596 } 5597 i.remove(); 5598 skipped++; 5599 } 5600 } 5601 if (DEBUG_DEXOPT) { 5602 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5603 } 5604 } 5605 } 5606 5607 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5608 List<ResolveInfo> ris = null; 5609 try { 5610 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5611 intent, null, 0, UserHandle.USER_OWNER); 5612 } catch (RemoteException e) { 5613 } 5614 ArraySet<String> pkgNames = new ArraySet<String>(); 5615 if (ris != null) { 5616 for (ResolveInfo ri : ris) { 5617 pkgNames.add(ri.activityInfo.packageName); 5618 } 5619 } 5620 return pkgNames; 5621 } 5622 5623 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5624 if (DEBUG_DEXOPT) { 5625 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5626 } 5627 if (!isFirstBoot()) { 5628 try { 5629 ActivityManagerNative.getDefault().showBootMessage( 5630 mContext.getResources().getString(R.string.android_upgrading_apk, 5631 curr, total), true); 5632 } catch (RemoteException e) { 5633 } 5634 } 5635 PackageParser.Package p = pkg; 5636 synchronized (mInstallLock) { 5637 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5638 false /* force dex */, false /* defer */, true /* include dependencies */); 5639 } 5640 } 5641 5642 @Override 5643 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5644 return performDexOpt(packageName, instructionSet, false); 5645 } 5646 5647 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5648 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5649 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5650 if (!dexopt && !updateUsage) { 5651 // We aren't going to dexopt or update usage, so bail early. 5652 return false; 5653 } 5654 PackageParser.Package p; 5655 final String targetInstructionSet; 5656 synchronized (mPackages) { 5657 p = mPackages.get(packageName); 5658 if (p == null) { 5659 return false; 5660 } 5661 if (updateUsage) { 5662 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5663 } 5664 mPackageUsage.write(false); 5665 if (!dexopt) { 5666 // We aren't going to dexopt, so bail early. 5667 return false; 5668 } 5669 5670 targetInstructionSet = instructionSet != null ? instructionSet : 5671 getPrimaryInstructionSet(p.applicationInfo); 5672 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5673 return false; 5674 } 5675 } 5676 5677 synchronized (mInstallLock) { 5678 final String[] instructionSets = new String[] { targetInstructionSet }; 5679 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5680 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5681 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5682 } 5683 } 5684 5685 public ArraySet<String> getPackagesThatNeedDexOpt() { 5686 ArraySet<String> pkgs = null; 5687 synchronized (mPackages) { 5688 for (PackageParser.Package p : mPackages.values()) { 5689 if (DEBUG_DEXOPT) { 5690 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5691 } 5692 if (!p.mDexOptPerformed.isEmpty()) { 5693 continue; 5694 } 5695 if (pkgs == null) { 5696 pkgs = new ArraySet<String>(); 5697 } 5698 pkgs.add(p.packageName); 5699 } 5700 } 5701 return pkgs; 5702 } 5703 5704 public void shutdown() { 5705 mPackageUsage.write(true); 5706 } 5707 5708 @Override 5709 public void forceDexOpt(String packageName) { 5710 enforceSystemOrRoot("forceDexOpt"); 5711 5712 PackageParser.Package pkg; 5713 synchronized (mPackages) { 5714 pkg = mPackages.get(packageName); 5715 if (pkg == null) { 5716 throw new IllegalArgumentException("Missing package: " + packageName); 5717 } 5718 } 5719 5720 synchronized (mInstallLock) { 5721 final String[] instructionSets = new String[] { 5722 getPrimaryInstructionSet(pkg.applicationInfo) }; 5723 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5724 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5725 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5726 throw new IllegalStateException("Failed to dexopt: " + res); 5727 } 5728 } 5729 } 5730 5731 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5732 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5733 Slog.w(TAG, "Unable to update from " + oldPkg.name 5734 + " to " + newPkg.packageName 5735 + ": old package not in system partition"); 5736 return false; 5737 } else if (mPackages.get(oldPkg.name) != null) { 5738 Slog.w(TAG, "Unable to update from " + oldPkg.name 5739 + " to " + newPkg.packageName 5740 + ": old package still exists"); 5741 return false; 5742 } 5743 return true; 5744 } 5745 5746 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5747 int[] users = sUserManager.getUserIds(); 5748 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5749 if (res < 0) { 5750 return res; 5751 } 5752 for (int user : users) { 5753 if (user != 0) { 5754 res = mInstaller.createUserData(volumeUuid, packageName, 5755 UserHandle.getUid(user, uid), user, seinfo); 5756 if (res < 0) { 5757 return res; 5758 } 5759 } 5760 } 5761 return res; 5762 } 5763 5764 private int removeDataDirsLI(String volumeUuid, String packageName) { 5765 int[] users = sUserManager.getUserIds(); 5766 int res = 0; 5767 for (int user : users) { 5768 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5769 if (resInner < 0) { 5770 res = resInner; 5771 } 5772 } 5773 5774 return res; 5775 } 5776 5777 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5778 int[] users = sUserManager.getUserIds(); 5779 int res = 0; 5780 for (int user : users) { 5781 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5782 if (resInner < 0) { 5783 res = resInner; 5784 } 5785 } 5786 return res; 5787 } 5788 5789 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5790 PackageParser.Package changingLib) { 5791 if (file.path != null) { 5792 usesLibraryFiles.add(file.path); 5793 return; 5794 } 5795 PackageParser.Package p = mPackages.get(file.apk); 5796 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5797 // If we are doing this while in the middle of updating a library apk, 5798 // then we need to make sure to use that new apk for determining the 5799 // dependencies here. (We haven't yet finished committing the new apk 5800 // to the package manager state.) 5801 if (p == null || p.packageName.equals(changingLib.packageName)) { 5802 p = changingLib; 5803 } 5804 } 5805 if (p != null) { 5806 usesLibraryFiles.addAll(p.getAllCodePaths()); 5807 } 5808 } 5809 5810 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5811 PackageParser.Package changingLib) throws PackageManagerException { 5812 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5813 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5814 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5815 for (int i=0; i<N; i++) { 5816 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5817 if (file == null) { 5818 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5819 "Package " + pkg.packageName + " requires unavailable shared library " 5820 + pkg.usesLibraries.get(i) + "; failing!"); 5821 } 5822 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5823 } 5824 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5825 for (int i=0; i<N; i++) { 5826 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5827 if (file == null) { 5828 Slog.w(TAG, "Package " + pkg.packageName 5829 + " desires unavailable shared library " 5830 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5831 } else { 5832 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5833 } 5834 } 5835 N = usesLibraryFiles.size(); 5836 if (N > 0) { 5837 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5838 } else { 5839 pkg.usesLibraryFiles = null; 5840 } 5841 } 5842 } 5843 5844 private static boolean hasString(List<String> list, List<String> which) { 5845 if (list == null) { 5846 return false; 5847 } 5848 for (int i=list.size()-1; i>=0; i--) { 5849 for (int j=which.size()-1; j>=0; j--) { 5850 if (which.get(j).equals(list.get(i))) { 5851 return true; 5852 } 5853 } 5854 } 5855 return false; 5856 } 5857 5858 private void updateAllSharedLibrariesLPw() { 5859 for (PackageParser.Package pkg : mPackages.values()) { 5860 try { 5861 updateSharedLibrariesLPw(pkg, null); 5862 } catch (PackageManagerException e) { 5863 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5864 } 5865 } 5866 } 5867 5868 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5869 PackageParser.Package changingPkg) { 5870 ArrayList<PackageParser.Package> res = null; 5871 for (PackageParser.Package pkg : mPackages.values()) { 5872 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5873 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5874 if (res == null) { 5875 res = new ArrayList<PackageParser.Package>(); 5876 } 5877 res.add(pkg); 5878 try { 5879 updateSharedLibrariesLPw(pkg, changingPkg); 5880 } catch (PackageManagerException e) { 5881 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5882 } 5883 } 5884 } 5885 return res; 5886 } 5887 5888 /** 5889 * Derive the value of the {@code cpuAbiOverride} based on the provided 5890 * value and an optional stored value from the package settings. 5891 */ 5892 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5893 String cpuAbiOverride = null; 5894 5895 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5896 cpuAbiOverride = null; 5897 } else if (abiOverride != null) { 5898 cpuAbiOverride = abiOverride; 5899 } else if (settings != null) { 5900 cpuAbiOverride = settings.cpuAbiOverrideString; 5901 } 5902 5903 return cpuAbiOverride; 5904 } 5905 5906 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5907 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5908 boolean success = false; 5909 try { 5910 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5911 currentTime, user); 5912 success = true; 5913 return res; 5914 } finally { 5915 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5916 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5917 } 5918 } 5919 } 5920 5921 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5922 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5923 final File scanFile = new File(pkg.codePath); 5924 if (pkg.applicationInfo.getCodePath() == null || 5925 pkg.applicationInfo.getResourcePath() == null) { 5926 // Bail out. The resource and code paths haven't been set. 5927 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5928 "Code and resource paths haven't been set correctly"); 5929 } 5930 5931 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5932 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5933 } else { 5934 // Only allow system apps to be flagged as core apps. 5935 pkg.coreApp = false; 5936 } 5937 5938 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5939 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5940 } 5941 5942 if (mCustomResolverComponentName != null && 5943 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5944 setUpCustomResolverActivity(pkg); 5945 } 5946 5947 if (pkg.packageName.equals("android")) { 5948 synchronized (mPackages) { 5949 if (mAndroidApplication != null) { 5950 Slog.w(TAG, "*************************************************"); 5951 Slog.w(TAG, "Core android package being redefined. Skipping."); 5952 Slog.w(TAG, " file=" + scanFile); 5953 Slog.w(TAG, "*************************************************"); 5954 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5955 "Core android package being redefined. Skipping."); 5956 } 5957 5958 // Set up information for our fall-back user intent resolution activity. 5959 mPlatformPackage = pkg; 5960 pkg.mVersionCode = mSdkVersion; 5961 mAndroidApplication = pkg.applicationInfo; 5962 5963 if (!mResolverReplaced) { 5964 mResolveActivity.applicationInfo = mAndroidApplication; 5965 mResolveActivity.name = ResolverActivity.class.getName(); 5966 mResolveActivity.packageName = mAndroidApplication.packageName; 5967 mResolveActivity.processName = "system:ui"; 5968 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5969 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5970 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5971 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5972 mResolveActivity.exported = true; 5973 mResolveActivity.enabled = true; 5974 mResolveInfo.activityInfo = mResolveActivity; 5975 mResolveInfo.priority = 0; 5976 mResolveInfo.preferredOrder = 0; 5977 mResolveInfo.match = 0; 5978 mResolveComponentName = new ComponentName( 5979 mAndroidApplication.packageName, mResolveActivity.name); 5980 } 5981 } 5982 } 5983 5984 if (DEBUG_PACKAGE_SCANNING) { 5985 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5986 Log.d(TAG, "Scanning package " + pkg.packageName); 5987 } 5988 5989 if (mPackages.containsKey(pkg.packageName) 5990 || mSharedLibraries.containsKey(pkg.packageName)) { 5991 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5992 "Application package " + pkg.packageName 5993 + " already installed. Skipping duplicate."); 5994 } 5995 5996 // If we're only installing presumed-existing packages, require that the 5997 // scanned APK is both already known and at the path previously established 5998 // for it. Previously unknown packages we pick up normally, but if we have an 5999 // a priori expectation about this package's install presence, enforce it. 6000 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6001 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6002 if (known != null) { 6003 if (DEBUG_PACKAGE_SCANNING) { 6004 Log.d(TAG, "Examining " + pkg.codePath 6005 + " and requiring known paths " + known.codePathString 6006 + " & " + known.resourcePathString); 6007 } 6008 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6009 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6010 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6011 "Application package " + pkg.packageName 6012 + " found at " + pkg.applicationInfo.getCodePath() 6013 + " but expected at " + known.codePathString + "; ignoring."); 6014 } 6015 } 6016 } 6017 6018 // Initialize package source and resource directories 6019 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6020 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6021 6022 SharedUserSetting suid = null; 6023 PackageSetting pkgSetting = null; 6024 6025 if (!isSystemApp(pkg)) { 6026 // Only system apps can use these features. 6027 pkg.mOriginalPackages = null; 6028 pkg.mRealPackage = null; 6029 pkg.mAdoptPermissions = null; 6030 } 6031 6032 // writer 6033 synchronized (mPackages) { 6034 if (pkg.mSharedUserId != null) { 6035 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6036 if (suid == null) { 6037 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6038 "Creating application package " + pkg.packageName 6039 + " for shared user failed"); 6040 } 6041 if (DEBUG_PACKAGE_SCANNING) { 6042 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6043 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6044 + "): packages=" + suid.packages); 6045 } 6046 } 6047 6048 // Check if we are renaming from an original package name. 6049 PackageSetting origPackage = null; 6050 String realName = null; 6051 if (pkg.mOriginalPackages != null) { 6052 // This package may need to be renamed to a previously 6053 // installed name. Let's check on that... 6054 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6055 if (pkg.mOriginalPackages.contains(renamed)) { 6056 // This package had originally been installed as the 6057 // original name, and we have already taken care of 6058 // transitioning to the new one. Just update the new 6059 // one to continue using the old name. 6060 realName = pkg.mRealPackage; 6061 if (!pkg.packageName.equals(renamed)) { 6062 // Callers into this function may have already taken 6063 // care of renaming the package; only do it here if 6064 // it is not already done. 6065 pkg.setPackageName(renamed); 6066 } 6067 6068 } else { 6069 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6070 if ((origPackage = mSettings.peekPackageLPr( 6071 pkg.mOriginalPackages.get(i))) != null) { 6072 // We do have the package already installed under its 6073 // original name... should we use it? 6074 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6075 // New package is not compatible with original. 6076 origPackage = null; 6077 continue; 6078 } else if (origPackage.sharedUser != null) { 6079 // Make sure uid is compatible between packages. 6080 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6081 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6082 + " to " + pkg.packageName + ": old uid " 6083 + origPackage.sharedUser.name 6084 + " differs from " + pkg.mSharedUserId); 6085 origPackage = null; 6086 continue; 6087 } 6088 } else { 6089 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6090 + pkg.packageName + " to old name " + origPackage.name); 6091 } 6092 break; 6093 } 6094 } 6095 } 6096 } 6097 6098 if (mTransferedPackages.contains(pkg.packageName)) { 6099 Slog.w(TAG, "Package " + pkg.packageName 6100 + " was transferred to another, but its .apk remains"); 6101 } 6102 6103 // Just create the setting, don't add it yet. For already existing packages 6104 // the PkgSetting exists already and doesn't have to be created. 6105 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6106 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6107 pkg.applicationInfo.primaryCpuAbi, 6108 pkg.applicationInfo.secondaryCpuAbi, 6109 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6110 user, false); 6111 if (pkgSetting == null) { 6112 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6113 "Creating application package " + pkg.packageName + " failed"); 6114 } 6115 6116 if (pkgSetting.origPackage != null) { 6117 // If we are first transitioning from an original package, 6118 // fix up the new package's name now. We need to do this after 6119 // looking up the package under its new name, so getPackageLP 6120 // can take care of fiddling things correctly. 6121 pkg.setPackageName(origPackage.name); 6122 6123 // File a report about this. 6124 String msg = "New package " + pkgSetting.realName 6125 + " renamed to replace old package " + pkgSetting.name; 6126 reportSettingsProblem(Log.WARN, msg); 6127 6128 // Make a note of it. 6129 mTransferedPackages.add(origPackage.name); 6130 6131 // No longer need to retain this. 6132 pkgSetting.origPackage = null; 6133 } 6134 6135 if (realName != null) { 6136 // Make a note of it. 6137 mTransferedPackages.add(pkg.packageName); 6138 } 6139 6140 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6141 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6142 } 6143 6144 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6145 // Check all shared libraries and map to their actual file path. 6146 // We only do this here for apps not on a system dir, because those 6147 // are the only ones that can fail an install due to this. We 6148 // will take care of the system apps by updating all of their 6149 // library paths after the scan is done. 6150 updateSharedLibrariesLPw(pkg, null); 6151 } 6152 6153 if (mFoundPolicyFile) { 6154 SELinuxMMAC.assignSeinfoValue(pkg); 6155 } 6156 6157 pkg.applicationInfo.uid = pkgSetting.appId; 6158 pkg.mExtras = pkgSetting; 6159 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6160 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6161 // We just determined the app is signed correctly, so bring 6162 // over the latest parsed certs. 6163 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6164 } else { 6165 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6166 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6167 "Package " + pkg.packageName + " upgrade keys do not match the " 6168 + "previously installed version"); 6169 } else { 6170 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6171 String msg = "System package " + pkg.packageName 6172 + " signature changed; retaining data."; 6173 reportSettingsProblem(Log.WARN, msg); 6174 } 6175 } 6176 } else { 6177 try { 6178 verifySignaturesLP(pkgSetting, pkg); 6179 // We just determined the app is signed correctly, so bring 6180 // over the latest parsed certs. 6181 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6182 } catch (PackageManagerException e) { 6183 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6184 throw e; 6185 } 6186 // The signature has changed, but this package is in the system 6187 // image... let's recover! 6188 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6189 // However... if this package is part of a shared user, but it 6190 // doesn't match the signature of the shared user, let's fail. 6191 // What this means is that you can't change the signatures 6192 // associated with an overall shared user, which doesn't seem all 6193 // that unreasonable. 6194 if (pkgSetting.sharedUser != null) { 6195 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6196 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6197 throw new PackageManagerException( 6198 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6199 "Signature mismatch for shared user : " 6200 + pkgSetting.sharedUser); 6201 } 6202 } 6203 // File a report about this. 6204 String msg = "System package " + pkg.packageName 6205 + " signature changed; retaining data."; 6206 reportSettingsProblem(Log.WARN, msg); 6207 } 6208 } 6209 // Verify that this new package doesn't have any content providers 6210 // that conflict with existing packages. Only do this if the 6211 // package isn't already installed, since we don't want to break 6212 // things that are installed. 6213 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6214 final int N = pkg.providers.size(); 6215 int i; 6216 for (i=0; i<N; i++) { 6217 PackageParser.Provider p = pkg.providers.get(i); 6218 if (p.info.authority != null) { 6219 String names[] = p.info.authority.split(";"); 6220 for (int j = 0; j < names.length; j++) { 6221 if (mProvidersByAuthority.containsKey(names[j])) { 6222 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6223 final String otherPackageName = 6224 ((other != null && other.getComponentName() != null) ? 6225 other.getComponentName().getPackageName() : "?"); 6226 throw new PackageManagerException( 6227 INSTALL_FAILED_CONFLICTING_PROVIDER, 6228 "Can't install because provider name " + names[j] 6229 + " (in package " + pkg.applicationInfo.packageName 6230 + ") is already used by " + otherPackageName); 6231 } 6232 } 6233 } 6234 } 6235 } 6236 6237 if (pkg.mAdoptPermissions != null) { 6238 // This package wants to adopt ownership of permissions from 6239 // another package. 6240 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6241 final String origName = pkg.mAdoptPermissions.get(i); 6242 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6243 if (orig != null) { 6244 if (verifyPackageUpdateLPr(orig, pkg)) { 6245 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6246 + pkg.packageName); 6247 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6248 } 6249 } 6250 } 6251 } 6252 } 6253 6254 final String pkgName = pkg.packageName; 6255 6256 final long scanFileTime = scanFile.lastModified(); 6257 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6258 pkg.applicationInfo.processName = fixProcessName( 6259 pkg.applicationInfo.packageName, 6260 pkg.applicationInfo.processName, 6261 pkg.applicationInfo.uid); 6262 6263 File dataPath; 6264 if (mPlatformPackage == pkg) { 6265 // The system package is special. 6266 dataPath = new File(Environment.getDataDirectory(), "system"); 6267 6268 pkg.applicationInfo.dataDir = dataPath.getPath(); 6269 6270 } else { 6271 // This is a normal package, need to make its data directory. 6272 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6273 UserHandle.USER_OWNER); 6274 6275 boolean uidError = false; 6276 if (dataPath.exists()) { 6277 int currentUid = 0; 6278 try { 6279 StructStat stat = Os.stat(dataPath.getPath()); 6280 currentUid = stat.st_uid; 6281 } catch (ErrnoException e) { 6282 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6283 } 6284 6285 // If we have mismatched owners for the data path, we have a problem. 6286 if (currentUid != pkg.applicationInfo.uid) { 6287 boolean recovered = false; 6288 if (currentUid == 0) { 6289 // The directory somehow became owned by root. Wow. 6290 // This is probably because the system was stopped while 6291 // installd was in the middle of messing with its libs 6292 // directory. Ask installd to fix that. 6293 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6294 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6295 if (ret >= 0) { 6296 recovered = true; 6297 String msg = "Package " + pkg.packageName 6298 + " unexpectedly changed to uid 0; recovered to " + 6299 + pkg.applicationInfo.uid; 6300 reportSettingsProblem(Log.WARN, msg); 6301 } 6302 } 6303 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6304 || (scanFlags&SCAN_BOOTING) != 0)) { 6305 // If this is a system app, we can at least delete its 6306 // current data so the application will still work. 6307 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6308 if (ret >= 0) { 6309 // TODO: Kill the processes first 6310 // Old data gone! 6311 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6312 ? "System package " : "Third party package "; 6313 String msg = prefix + pkg.packageName 6314 + " has changed from uid: " 6315 + currentUid + " to " 6316 + pkg.applicationInfo.uid + "; old data erased"; 6317 reportSettingsProblem(Log.WARN, msg); 6318 recovered = true; 6319 6320 // And now re-install the app. 6321 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6322 pkg.applicationInfo.seinfo); 6323 if (ret == -1) { 6324 // Ack should not happen! 6325 msg = prefix + pkg.packageName 6326 + " could not have data directory re-created after delete."; 6327 reportSettingsProblem(Log.WARN, msg); 6328 throw new PackageManagerException( 6329 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6330 } 6331 } 6332 if (!recovered) { 6333 mHasSystemUidErrors = true; 6334 } 6335 } else if (!recovered) { 6336 // If we allow this install to proceed, we will be broken. 6337 // Abort, abort! 6338 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6339 "scanPackageLI"); 6340 } 6341 if (!recovered) { 6342 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6343 + pkg.applicationInfo.uid + "/fs_" 6344 + currentUid; 6345 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6346 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6347 String msg = "Package " + pkg.packageName 6348 + " has mismatched uid: " 6349 + currentUid + " on disk, " 6350 + pkg.applicationInfo.uid + " in settings"; 6351 // writer 6352 synchronized (mPackages) { 6353 mSettings.mReadMessages.append(msg); 6354 mSettings.mReadMessages.append('\n'); 6355 uidError = true; 6356 if (!pkgSetting.uidError) { 6357 reportSettingsProblem(Log.ERROR, msg); 6358 } 6359 } 6360 } 6361 } 6362 pkg.applicationInfo.dataDir = dataPath.getPath(); 6363 if (mShouldRestoreconData) { 6364 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6365 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6366 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6367 } 6368 } else { 6369 if (DEBUG_PACKAGE_SCANNING) { 6370 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6371 Log.v(TAG, "Want this data dir: " + dataPath); 6372 } 6373 //invoke installer to do the actual installation 6374 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6375 pkg.applicationInfo.seinfo); 6376 if (ret < 0) { 6377 // Error from installer 6378 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6379 "Unable to create data dirs [errorCode=" + ret + "]"); 6380 } 6381 6382 if (dataPath.exists()) { 6383 pkg.applicationInfo.dataDir = dataPath.getPath(); 6384 } else { 6385 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6386 pkg.applicationInfo.dataDir = null; 6387 } 6388 } 6389 6390 pkgSetting.uidError = uidError; 6391 } 6392 6393 final String path = scanFile.getPath(); 6394 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6395 6396 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6397 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6398 6399 // Some system apps still use directory structure for native libraries 6400 // in which case we might end up not detecting abi solely based on apk 6401 // structure. Try to detect abi based on directory structure. 6402 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6403 pkg.applicationInfo.primaryCpuAbi == null) { 6404 setBundledAppAbisAndRoots(pkg, pkgSetting); 6405 setNativeLibraryPaths(pkg); 6406 } 6407 6408 } else { 6409 if ((scanFlags & SCAN_MOVE) != 0) { 6410 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6411 // but we already have this packages package info in the PackageSetting. We just 6412 // use that and derive the native library path based on the new codepath. 6413 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6414 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6415 } 6416 6417 // Set native library paths again. For moves, the path will be updated based on the 6418 // ABIs we've determined above. For non-moves, the path will be updated based on the 6419 // ABIs we determined during compilation, but the path will depend on the final 6420 // package path (after the rename away from the stage path). 6421 setNativeLibraryPaths(pkg); 6422 } 6423 6424 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6425 final int[] userIds = sUserManager.getUserIds(); 6426 synchronized (mInstallLock) { 6427 // Create a native library symlink only if we have native libraries 6428 // and if the native libraries are 32 bit libraries. We do not provide 6429 // this symlink for 64 bit libraries. 6430 if (pkg.applicationInfo.primaryCpuAbi != null && 6431 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6432 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6433 for (int userId : userIds) { 6434 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6435 nativeLibPath, userId) < 0) { 6436 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6437 "Failed linking native library dir (user=" + userId + ")"); 6438 } 6439 } 6440 } 6441 } 6442 6443 // This is a special case for the "system" package, where the ABI is 6444 // dictated by the zygote configuration (and init.rc). We should keep track 6445 // of this ABI so that we can deal with "normal" applications that run under 6446 // the same UID correctly. 6447 if (mPlatformPackage == pkg) { 6448 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6449 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6450 } 6451 6452 // If there's a mismatch between the abi-override in the package setting 6453 // and the abiOverride specified for the install. Warn about this because we 6454 // would've already compiled the app without taking the package setting into 6455 // account. 6456 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6457 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6458 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6459 " for package: " + pkg.packageName); 6460 } 6461 } 6462 6463 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6464 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6465 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6466 6467 // Copy the derived override back to the parsed package, so that we can 6468 // update the package settings accordingly. 6469 pkg.cpuAbiOverride = cpuAbiOverride; 6470 6471 if (DEBUG_ABI_SELECTION) { 6472 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6473 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6474 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6475 } 6476 6477 // Push the derived path down into PackageSettings so we know what to 6478 // clean up at uninstall time. 6479 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6480 6481 if (DEBUG_ABI_SELECTION) { 6482 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6483 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6484 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6485 } 6486 6487 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6488 // We don't do this here during boot because we can do it all 6489 // at once after scanning all existing packages. 6490 // 6491 // We also do this *before* we perform dexopt on this package, so that 6492 // we can avoid redundant dexopts, and also to make sure we've got the 6493 // code and package path correct. 6494 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6495 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6496 } 6497 6498 if ((scanFlags & SCAN_NO_DEX) == 0) { 6499 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6500 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6501 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6502 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6503 } 6504 } 6505 if (mFactoryTest && pkg.requestedPermissions.contains( 6506 android.Manifest.permission.FACTORY_TEST)) { 6507 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6508 } 6509 6510 ArrayList<PackageParser.Package> clientLibPkgs = null; 6511 6512 // writer 6513 synchronized (mPackages) { 6514 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6515 // Only system apps can add new shared libraries. 6516 if (pkg.libraryNames != null) { 6517 for (int i=0; i<pkg.libraryNames.size(); i++) { 6518 String name = pkg.libraryNames.get(i); 6519 boolean allowed = false; 6520 if (pkg.isUpdatedSystemApp()) { 6521 // New library entries can only be added through the 6522 // system image. This is important to get rid of a lot 6523 // of nasty edge cases: for example if we allowed a non- 6524 // system update of the app to add a library, then uninstalling 6525 // the update would make the library go away, and assumptions 6526 // we made such as through app install filtering would now 6527 // have allowed apps on the device which aren't compatible 6528 // with it. Better to just have the restriction here, be 6529 // conservative, and create many fewer cases that can negatively 6530 // impact the user experience. 6531 final PackageSetting sysPs = mSettings 6532 .getDisabledSystemPkgLPr(pkg.packageName); 6533 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6534 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6535 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6536 allowed = true; 6537 allowed = true; 6538 break; 6539 } 6540 } 6541 } 6542 } else { 6543 allowed = true; 6544 } 6545 if (allowed) { 6546 if (!mSharedLibraries.containsKey(name)) { 6547 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6548 } else if (!name.equals(pkg.packageName)) { 6549 Slog.w(TAG, "Package " + pkg.packageName + " library " 6550 + name + " already exists; skipping"); 6551 } 6552 } else { 6553 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6554 + name + " that is not declared on system image; skipping"); 6555 } 6556 } 6557 if ((scanFlags&SCAN_BOOTING) == 0) { 6558 // If we are not booting, we need to update any applications 6559 // that are clients of our shared library. If we are booting, 6560 // this will all be done once the scan is complete. 6561 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6562 } 6563 } 6564 } 6565 } 6566 6567 // We also need to dexopt any apps that are dependent on this library. Note that 6568 // if these fail, we should abort the install since installing the library will 6569 // result in some apps being broken. 6570 if (clientLibPkgs != null) { 6571 if ((scanFlags & SCAN_NO_DEX) == 0) { 6572 for (int i = 0; i < clientLibPkgs.size(); i++) { 6573 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6574 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6575 null /* instruction sets */, forceDex, 6576 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6577 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6578 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6579 "scanPackageLI failed to dexopt clientLibPkgs"); 6580 } 6581 } 6582 } 6583 } 6584 6585 // Also need to kill any apps that are dependent on the library. 6586 if (clientLibPkgs != null) { 6587 for (int i=0; i<clientLibPkgs.size(); i++) { 6588 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6589 killApplication(clientPkg.applicationInfo.packageName, 6590 clientPkg.applicationInfo.uid, "update lib"); 6591 } 6592 } 6593 6594 // writer 6595 synchronized (mPackages) { 6596 // We don't expect installation to fail beyond this point 6597 6598 // Add the new setting to mSettings 6599 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6600 // Add the new setting to mPackages 6601 mPackages.put(pkg.applicationInfo.packageName, pkg); 6602 // Make sure we don't accidentally delete its data. 6603 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6604 while (iter.hasNext()) { 6605 PackageCleanItem item = iter.next(); 6606 if (pkgName.equals(item.packageName)) { 6607 iter.remove(); 6608 } 6609 } 6610 6611 // Take care of first install / last update times. 6612 if (currentTime != 0) { 6613 if (pkgSetting.firstInstallTime == 0) { 6614 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6615 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6616 pkgSetting.lastUpdateTime = currentTime; 6617 } 6618 } else if (pkgSetting.firstInstallTime == 0) { 6619 // We need *something*. Take time time stamp of the file. 6620 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6621 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6622 if (scanFileTime != pkgSetting.timeStamp) { 6623 // A package on the system image has changed; consider this 6624 // to be an update. 6625 pkgSetting.lastUpdateTime = scanFileTime; 6626 } 6627 } 6628 6629 // Add the package's KeySets to the global KeySetManagerService 6630 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6631 try { 6632 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6633 if (pkg.mKeySetMapping != null) { 6634 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6635 if (pkg.mUpgradeKeySets != null) { 6636 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6637 } 6638 } 6639 } catch (NullPointerException e) { 6640 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6641 } catch (IllegalArgumentException e) { 6642 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6643 } 6644 6645 int N = pkg.providers.size(); 6646 StringBuilder r = null; 6647 int i; 6648 for (i=0; i<N; i++) { 6649 PackageParser.Provider p = pkg.providers.get(i); 6650 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6651 p.info.processName, pkg.applicationInfo.uid); 6652 mProviders.addProvider(p); 6653 p.syncable = p.info.isSyncable; 6654 if (p.info.authority != null) { 6655 String names[] = p.info.authority.split(";"); 6656 p.info.authority = null; 6657 for (int j = 0; j < names.length; j++) { 6658 if (j == 1 && p.syncable) { 6659 // We only want the first authority for a provider to possibly be 6660 // syncable, so if we already added this provider using a different 6661 // authority clear the syncable flag. We copy the provider before 6662 // changing it because the mProviders object contains a reference 6663 // to a provider that we don't want to change. 6664 // Only do this for the second authority since the resulting provider 6665 // object can be the same for all future authorities for this provider. 6666 p = new PackageParser.Provider(p); 6667 p.syncable = false; 6668 } 6669 if (!mProvidersByAuthority.containsKey(names[j])) { 6670 mProvidersByAuthority.put(names[j], p); 6671 if (p.info.authority == null) { 6672 p.info.authority = names[j]; 6673 } else { 6674 p.info.authority = p.info.authority + ";" + names[j]; 6675 } 6676 if (DEBUG_PACKAGE_SCANNING) { 6677 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6678 Log.d(TAG, "Registered content provider: " + names[j] 6679 + ", className = " + p.info.name + ", isSyncable = " 6680 + p.info.isSyncable); 6681 } 6682 } else { 6683 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6684 Slog.w(TAG, "Skipping provider name " + names[j] + 6685 " (in package " + pkg.applicationInfo.packageName + 6686 "): name already used by " 6687 + ((other != null && other.getComponentName() != null) 6688 ? other.getComponentName().getPackageName() : "?")); 6689 } 6690 } 6691 } 6692 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6693 if (r == null) { 6694 r = new StringBuilder(256); 6695 } else { 6696 r.append(' '); 6697 } 6698 r.append(p.info.name); 6699 } 6700 } 6701 if (r != null) { 6702 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6703 } 6704 6705 N = pkg.services.size(); 6706 r = null; 6707 for (i=0; i<N; i++) { 6708 PackageParser.Service s = pkg.services.get(i); 6709 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6710 s.info.processName, pkg.applicationInfo.uid); 6711 mServices.addService(s); 6712 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6713 if (r == null) { 6714 r = new StringBuilder(256); 6715 } else { 6716 r.append(' '); 6717 } 6718 r.append(s.info.name); 6719 } 6720 } 6721 if (r != null) { 6722 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6723 } 6724 6725 N = pkg.receivers.size(); 6726 r = null; 6727 for (i=0; i<N; i++) { 6728 PackageParser.Activity a = pkg.receivers.get(i); 6729 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6730 a.info.processName, pkg.applicationInfo.uid); 6731 mReceivers.addActivity(a, "receiver"); 6732 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6733 if (r == null) { 6734 r = new StringBuilder(256); 6735 } else { 6736 r.append(' '); 6737 } 6738 r.append(a.info.name); 6739 } 6740 } 6741 if (r != null) { 6742 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6743 } 6744 6745 N = pkg.activities.size(); 6746 r = null; 6747 for (i=0; i<N; i++) { 6748 PackageParser.Activity a = pkg.activities.get(i); 6749 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6750 a.info.processName, pkg.applicationInfo.uid); 6751 mActivities.addActivity(a, "activity"); 6752 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6753 if (r == null) { 6754 r = new StringBuilder(256); 6755 } else { 6756 r.append(' '); 6757 } 6758 r.append(a.info.name); 6759 } 6760 } 6761 if (r != null) { 6762 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6763 } 6764 6765 N = pkg.permissionGroups.size(); 6766 r = null; 6767 for (i=0; i<N; i++) { 6768 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6769 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6770 if (cur == null) { 6771 mPermissionGroups.put(pg.info.name, pg); 6772 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6773 if (r == null) { 6774 r = new StringBuilder(256); 6775 } else { 6776 r.append(' '); 6777 } 6778 r.append(pg.info.name); 6779 } 6780 } else { 6781 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6782 + pg.info.packageName + " ignored: original from " 6783 + cur.info.packageName); 6784 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6785 if (r == null) { 6786 r = new StringBuilder(256); 6787 } else { 6788 r.append(' '); 6789 } 6790 r.append("DUP:"); 6791 r.append(pg.info.name); 6792 } 6793 } 6794 } 6795 if (r != null) { 6796 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6797 } 6798 6799 N = pkg.permissions.size(); 6800 r = null; 6801 for (i=0; i<N; i++) { 6802 PackageParser.Permission p = pkg.permissions.get(i); 6803 6804 // Now that permission groups have a special meaning, we ignore permission 6805 // groups for legacy apps to prevent unexpected behavior. In particular, 6806 // permissions for one app being granted to someone just becuase they happen 6807 // to be in a group defined by another app (before this had no implications). 6808 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6809 p.group = mPermissionGroups.get(p.info.group); 6810 // Warn for a permission in an unknown group. 6811 if (p.info.group != null && p.group == null) { 6812 Slog.w(TAG, "Permission " + p.info.name + " from package " 6813 + p.info.packageName + " in an unknown group " + p.info.group); 6814 } 6815 } 6816 6817 ArrayMap<String, BasePermission> permissionMap = 6818 p.tree ? mSettings.mPermissionTrees 6819 : mSettings.mPermissions; 6820 BasePermission bp = permissionMap.get(p.info.name); 6821 6822 // Allow system apps to redefine non-system permissions 6823 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6824 final boolean currentOwnerIsSystem = (bp.perm != null 6825 && isSystemApp(bp.perm.owner)); 6826 if (isSystemApp(p.owner)) { 6827 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6828 // It's a built-in permission and no owner, take ownership now 6829 bp.packageSetting = pkgSetting; 6830 bp.perm = p; 6831 bp.uid = pkg.applicationInfo.uid; 6832 bp.sourcePackage = p.info.packageName; 6833 } else if (!currentOwnerIsSystem) { 6834 String msg = "New decl " + p.owner + " of permission " 6835 + p.info.name + " is system; overriding " + bp.sourcePackage; 6836 reportSettingsProblem(Log.WARN, msg); 6837 bp = null; 6838 } 6839 } 6840 } 6841 6842 if (bp == null) { 6843 bp = new BasePermission(p.info.name, p.info.packageName, 6844 BasePermission.TYPE_NORMAL); 6845 permissionMap.put(p.info.name, bp); 6846 } 6847 6848 if (bp.perm == null) { 6849 if (bp.sourcePackage == null 6850 || bp.sourcePackage.equals(p.info.packageName)) { 6851 BasePermission tree = findPermissionTreeLP(p.info.name); 6852 if (tree == null 6853 || tree.sourcePackage.equals(p.info.packageName)) { 6854 bp.packageSetting = pkgSetting; 6855 bp.perm = p; 6856 bp.uid = pkg.applicationInfo.uid; 6857 bp.sourcePackage = p.info.packageName; 6858 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6859 if (r == null) { 6860 r = new StringBuilder(256); 6861 } else { 6862 r.append(' '); 6863 } 6864 r.append(p.info.name); 6865 } 6866 } else { 6867 Slog.w(TAG, "Permission " + p.info.name + " from package " 6868 + p.info.packageName + " ignored: base tree " 6869 + tree.name + " is from package " 6870 + tree.sourcePackage); 6871 } 6872 } else { 6873 Slog.w(TAG, "Permission " + p.info.name + " from package " 6874 + p.info.packageName + " ignored: original from " 6875 + bp.sourcePackage); 6876 } 6877 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6878 if (r == null) { 6879 r = new StringBuilder(256); 6880 } else { 6881 r.append(' '); 6882 } 6883 r.append("DUP:"); 6884 r.append(p.info.name); 6885 } 6886 if (bp.perm == p) { 6887 bp.protectionLevel = p.info.protectionLevel; 6888 } 6889 } 6890 6891 if (r != null) { 6892 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6893 } 6894 6895 N = pkg.instrumentation.size(); 6896 r = null; 6897 for (i=0; i<N; i++) { 6898 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6899 a.info.packageName = pkg.applicationInfo.packageName; 6900 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6901 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6902 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6903 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6904 a.info.dataDir = pkg.applicationInfo.dataDir; 6905 6906 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6907 // need other information about the application, like the ABI and what not ? 6908 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6909 mInstrumentation.put(a.getComponentName(), a); 6910 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6911 if (r == null) { 6912 r = new StringBuilder(256); 6913 } else { 6914 r.append(' '); 6915 } 6916 r.append(a.info.name); 6917 } 6918 } 6919 if (r != null) { 6920 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6921 } 6922 6923 if (pkg.protectedBroadcasts != null) { 6924 N = pkg.protectedBroadcasts.size(); 6925 for (i=0; i<N; i++) { 6926 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6927 } 6928 } 6929 6930 pkgSetting.setTimeStamp(scanFileTime); 6931 6932 // Create idmap files for pairs of (packages, overlay packages). 6933 // Note: "android", ie framework-res.apk, is handled by native layers. 6934 if (pkg.mOverlayTarget != null) { 6935 // This is an overlay package. 6936 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6937 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6938 mOverlays.put(pkg.mOverlayTarget, 6939 new ArrayMap<String, PackageParser.Package>()); 6940 } 6941 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6942 map.put(pkg.packageName, pkg); 6943 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6944 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6945 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6946 "scanPackageLI failed to createIdmap"); 6947 } 6948 } 6949 } else if (mOverlays.containsKey(pkg.packageName) && 6950 !pkg.packageName.equals("android")) { 6951 // This is a regular package, with one or more known overlay packages. 6952 createIdmapsForPackageLI(pkg); 6953 } 6954 } 6955 6956 return pkg; 6957 } 6958 6959 /** 6960 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6961 * is derived purely on the basis of the contents of {@code scanFile} and 6962 * {@code cpuAbiOverride}. 6963 * 6964 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6965 */ 6966 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6967 String cpuAbiOverride, boolean extractLibs) 6968 throws PackageManagerException { 6969 // TODO: We can probably be smarter about this stuff. For installed apps, 6970 // we can calculate this information at install time once and for all. For 6971 // system apps, we can probably assume that this information doesn't change 6972 // after the first boot scan. As things stand, we do lots of unnecessary work. 6973 6974 // Give ourselves some initial paths; we'll come back for another 6975 // pass once we've determined ABI below. 6976 setNativeLibraryPaths(pkg); 6977 6978 // We would never need to extract libs for forward-locked and external packages, 6979 // since the container service will do it for us. We shouldn't attempt to 6980 // extract libs from system app when it was not updated. 6981 if (pkg.isForwardLocked() || isExternal(pkg) || 6982 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 6983 extractLibs = false; 6984 } 6985 6986 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6987 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6988 6989 NativeLibraryHelper.Handle handle = null; 6990 try { 6991 handle = NativeLibraryHelper.Handle.create(scanFile); 6992 // TODO(multiArch): This can be null for apps that didn't go through the 6993 // usual installation process. We can calculate it again, like we 6994 // do during install time. 6995 // 6996 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6997 // unnecessary. 6998 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6999 7000 // Null out the abis so that they can be recalculated. 7001 pkg.applicationInfo.primaryCpuAbi = null; 7002 pkg.applicationInfo.secondaryCpuAbi = null; 7003 if (isMultiArch(pkg.applicationInfo)) { 7004 // Warn if we've set an abiOverride for multi-lib packages.. 7005 // By definition, we need to copy both 32 and 64 bit libraries for 7006 // such packages. 7007 if (pkg.cpuAbiOverride != null 7008 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7009 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7010 } 7011 7012 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7013 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7014 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7015 if (extractLibs) { 7016 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7017 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7018 useIsaSpecificSubdirs); 7019 } else { 7020 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7021 } 7022 } 7023 7024 maybeThrowExceptionForMultiArchCopy( 7025 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7026 7027 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7028 if (extractLibs) { 7029 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7030 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7031 useIsaSpecificSubdirs); 7032 } else { 7033 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7034 } 7035 } 7036 7037 maybeThrowExceptionForMultiArchCopy( 7038 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7039 7040 if (abi64 >= 0) { 7041 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7042 } 7043 7044 if (abi32 >= 0) { 7045 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7046 if (abi64 >= 0) { 7047 pkg.applicationInfo.secondaryCpuAbi = abi; 7048 } else { 7049 pkg.applicationInfo.primaryCpuAbi = abi; 7050 } 7051 } 7052 } else { 7053 String[] abiList = (cpuAbiOverride != null) ? 7054 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7055 7056 // Enable gross and lame hacks for apps that are built with old 7057 // SDK tools. We must scan their APKs for renderscript bitcode and 7058 // not launch them if it's present. Don't bother checking on devices 7059 // that don't have 64 bit support. 7060 boolean needsRenderScriptOverride = false; 7061 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7062 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7063 abiList = Build.SUPPORTED_32_BIT_ABIS; 7064 needsRenderScriptOverride = true; 7065 } 7066 7067 final int copyRet; 7068 if (extractLibs) { 7069 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7070 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7071 } else { 7072 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7073 } 7074 7075 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7076 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7077 "Error unpackaging native libs for app, errorCode=" + copyRet); 7078 } 7079 7080 if (copyRet >= 0) { 7081 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7082 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7083 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7084 } else if (needsRenderScriptOverride) { 7085 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7086 } 7087 } 7088 } catch (IOException ioe) { 7089 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7090 } finally { 7091 IoUtils.closeQuietly(handle); 7092 } 7093 7094 // Now that we've calculated the ABIs and determined if it's an internal app, 7095 // we will go ahead and populate the nativeLibraryPath. 7096 setNativeLibraryPaths(pkg); 7097 } 7098 7099 /** 7100 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7101 * i.e, so that all packages can be run inside a single process if required. 7102 * 7103 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7104 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7105 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7106 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7107 * updating a package that belongs to a shared user. 7108 * 7109 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7110 * adds unnecessary complexity. 7111 */ 7112 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7113 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7114 String requiredInstructionSet = null; 7115 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7116 requiredInstructionSet = VMRuntime.getInstructionSet( 7117 scannedPackage.applicationInfo.primaryCpuAbi); 7118 } 7119 7120 PackageSetting requirer = null; 7121 for (PackageSetting ps : packagesForUser) { 7122 // If packagesForUser contains scannedPackage, we skip it. This will happen 7123 // when scannedPackage is an update of an existing package. Without this check, 7124 // we will never be able to change the ABI of any package belonging to a shared 7125 // user, even if it's compatible with other packages. 7126 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7127 if (ps.primaryCpuAbiString == null) { 7128 continue; 7129 } 7130 7131 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7132 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7133 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7134 // this but there's not much we can do. 7135 String errorMessage = "Instruction set mismatch, " 7136 + ((requirer == null) ? "[caller]" : requirer) 7137 + " requires " + requiredInstructionSet + " whereas " + ps 7138 + " requires " + instructionSet; 7139 Slog.w(TAG, errorMessage); 7140 } 7141 7142 if (requiredInstructionSet == null) { 7143 requiredInstructionSet = instructionSet; 7144 requirer = ps; 7145 } 7146 } 7147 } 7148 7149 if (requiredInstructionSet != null) { 7150 String adjustedAbi; 7151 if (requirer != null) { 7152 // requirer != null implies that either scannedPackage was null or that scannedPackage 7153 // did not require an ABI, in which case we have to adjust scannedPackage to match 7154 // the ABI of the set (which is the same as requirer's ABI) 7155 adjustedAbi = requirer.primaryCpuAbiString; 7156 if (scannedPackage != null) { 7157 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7158 } 7159 } else { 7160 // requirer == null implies that we're updating all ABIs in the set to 7161 // match scannedPackage. 7162 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7163 } 7164 7165 for (PackageSetting ps : packagesForUser) { 7166 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7167 if (ps.primaryCpuAbiString != null) { 7168 continue; 7169 } 7170 7171 ps.primaryCpuAbiString = adjustedAbi; 7172 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7173 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7174 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7175 7176 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7177 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7178 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7179 ps.primaryCpuAbiString = null; 7180 ps.pkg.applicationInfo.primaryCpuAbi = null; 7181 return; 7182 } else { 7183 mInstaller.rmdex(ps.codePathString, 7184 getDexCodeInstructionSet(getPreferredInstructionSet())); 7185 } 7186 } 7187 } 7188 } 7189 } 7190 } 7191 7192 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7193 synchronized (mPackages) { 7194 mResolverReplaced = true; 7195 // Set up information for custom user intent resolution activity. 7196 mResolveActivity.applicationInfo = pkg.applicationInfo; 7197 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7198 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7199 mResolveActivity.processName = pkg.applicationInfo.packageName; 7200 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7201 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7202 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7203 mResolveActivity.theme = 0; 7204 mResolveActivity.exported = true; 7205 mResolveActivity.enabled = true; 7206 mResolveInfo.activityInfo = mResolveActivity; 7207 mResolveInfo.priority = 0; 7208 mResolveInfo.preferredOrder = 0; 7209 mResolveInfo.match = 0; 7210 mResolveComponentName = mCustomResolverComponentName; 7211 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7212 mResolveComponentName); 7213 } 7214 } 7215 7216 private static String calculateBundledApkRoot(final String codePathString) { 7217 final File codePath = new File(codePathString); 7218 final File codeRoot; 7219 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7220 codeRoot = Environment.getRootDirectory(); 7221 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7222 codeRoot = Environment.getOemDirectory(); 7223 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7224 codeRoot = Environment.getVendorDirectory(); 7225 } else { 7226 // Unrecognized code path; take its top real segment as the apk root: 7227 // e.g. /something/app/blah.apk => /something 7228 try { 7229 File f = codePath.getCanonicalFile(); 7230 File parent = f.getParentFile(); // non-null because codePath is a file 7231 File tmp; 7232 while ((tmp = parent.getParentFile()) != null) { 7233 f = parent; 7234 parent = tmp; 7235 } 7236 codeRoot = f; 7237 Slog.w(TAG, "Unrecognized code path " 7238 + codePath + " - using " + codeRoot); 7239 } catch (IOException e) { 7240 // Can't canonicalize the code path -- shenanigans? 7241 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7242 return Environment.getRootDirectory().getPath(); 7243 } 7244 } 7245 return codeRoot.getPath(); 7246 } 7247 7248 /** 7249 * Derive and set the location of native libraries for the given package, 7250 * which varies depending on where and how the package was installed. 7251 */ 7252 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7253 final ApplicationInfo info = pkg.applicationInfo; 7254 final String codePath = pkg.codePath; 7255 final File codeFile = new File(codePath); 7256 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7257 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7258 7259 info.nativeLibraryRootDir = null; 7260 info.nativeLibraryRootRequiresIsa = false; 7261 info.nativeLibraryDir = null; 7262 info.secondaryNativeLibraryDir = null; 7263 7264 if (isApkFile(codeFile)) { 7265 // Monolithic install 7266 if (bundledApp) { 7267 // If "/system/lib64/apkname" exists, assume that is the per-package 7268 // native library directory to use; otherwise use "/system/lib/apkname". 7269 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7270 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7271 getPrimaryInstructionSet(info)); 7272 7273 // This is a bundled system app so choose the path based on the ABI. 7274 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7275 // is just the default path. 7276 final String apkName = deriveCodePathName(codePath); 7277 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7278 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7279 apkName).getAbsolutePath(); 7280 7281 if (info.secondaryCpuAbi != null) { 7282 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7283 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7284 secondaryLibDir, apkName).getAbsolutePath(); 7285 } 7286 } else if (asecApp) { 7287 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7288 .getAbsolutePath(); 7289 } else { 7290 final String apkName = deriveCodePathName(codePath); 7291 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7292 .getAbsolutePath(); 7293 } 7294 7295 info.nativeLibraryRootRequiresIsa = false; 7296 info.nativeLibraryDir = info.nativeLibraryRootDir; 7297 } else { 7298 // Cluster install 7299 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7300 info.nativeLibraryRootRequiresIsa = true; 7301 7302 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7303 getPrimaryInstructionSet(info)).getAbsolutePath(); 7304 7305 if (info.secondaryCpuAbi != null) { 7306 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7307 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7308 } 7309 } 7310 } 7311 7312 /** 7313 * Calculate the abis and roots for a bundled app. These can uniquely 7314 * be determined from the contents of the system partition, i.e whether 7315 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7316 * of this information, and instead assume that the system was built 7317 * sensibly. 7318 */ 7319 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7320 PackageSetting pkgSetting) { 7321 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7322 7323 // If "/system/lib64/apkname" exists, assume that is the per-package 7324 // native library directory to use; otherwise use "/system/lib/apkname". 7325 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7326 setBundledAppAbi(pkg, apkRoot, apkName); 7327 // pkgSetting might be null during rescan following uninstall of updates 7328 // to a bundled app, so accommodate that possibility. The settings in 7329 // that case will be established later from the parsed package. 7330 // 7331 // If the settings aren't null, sync them up with what we've just derived. 7332 // note that apkRoot isn't stored in the package settings. 7333 if (pkgSetting != null) { 7334 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7335 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7336 } 7337 } 7338 7339 /** 7340 * Deduces the ABI of a bundled app and sets the relevant fields on the 7341 * parsed pkg object. 7342 * 7343 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7344 * under which system libraries are installed. 7345 * @param apkName the name of the installed package. 7346 */ 7347 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7348 final File codeFile = new File(pkg.codePath); 7349 7350 final boolean has64BitLibs; 7351 final boolean has32BitLibs; 7352 if (isApkFile(codeFile)) { 7353 // Monolithic install 7354 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7355 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7356 } else { 7357 // Cluster install 7358 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7359 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7360 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7361 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7362 has64BitLibs = (new File(rootDir, isa)).exists(); 7363 } else { 7364 has64BitLibs = false; 7365 } 7366 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7367 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7368 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7369 has32BitLibs = (new File(rootDir, isa)).exists(); 7370 } else { 7371 has32BitLibs = false; 7372 } 7373 } 7374 7375 if (has64BitLibs && !has32BitLibs) { 7376 // The package has 64 bit libs, but not 32 bit libs. Its primary 7377 // ABI should be 64 bit. We can safely assume here that the bundled 7378 // native libraries correspond to the most preferred ABI in the list. 7379 7380 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7381 pkg.applicationInfo.secondaryCpuAbi = null; 7382 } else if (has32BitLibs && !has64BitLibs) { 7383 // The package has 32 bit libs but not 64 bit libs. Its primary 7384 // ABI should be 32 bit. 7385 7386 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7387 pkg.applicationInfo.secondaryCpuAbi = null; 7388 } else if (has32BitLibs && has64BitLibs) { 7389 // The application has both 64 and 32 bit bundled libraries. We check 7390 // here that the app declares multiArch support, and warn if it doesn't. 7391 // 7392 // We will be lenient here and record both ABIs. The primary will be the 7393 // ABI that's higher on the list, i.e, a device that's configured to prefer 7394 // 64 bit apps will see a 64 bit primary ABI, 7395 7396 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7397 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7398 } 7399 7400 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7401 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7402 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7403 } else { 7404 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7405 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7406 } 7407 } else { 7408 pkg.applicationInfo.primaryCpuAbi = null; 7409 pkg.applicationInfo.secondaryCpuAbi = null; 7410 } 7411 } 7412 7413 private void killApplication(String pkgName, int appId, String reason) { 7414 // Request the ActivityManager to kill the process(only for existing packages) 7415 // so that we do not end up in a confused state while the user is still using the older 7416 // version of the application while the new one gets installed. 7417 IActivityManager am = ActivityManagerNative.getDefault(); 7418 if (am != null) { 7419 try { 7420 am.killApplicationWithAppId(pkgName, appId, reason); 7421 } catch (RemoteException e) { 7422 } 7423 } 7424 } 7425 7426 void removePackageLI(PackageSetting ps, boolean chatty) { 7427 if (DEBUG_INSTALL) { 7428 if (chatty) 7429 Log.d(TAG, "Removing package " + ps.name); 7430 } 7431 7432 // writer 7433 synchronized (mPackages) { 7434 mPackages.remove(ps.name); 7435 final PackageParser.Package pkg = ps.pkg; 7436 if (pkg != null) { 7437 cleanPackageDataStructuresLILPw(pkg, chatty); 7438 } 7439 } 7440 } 7441 7442 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7443 if (DEBUG_INSTALL) { 7444 if (chatty) 7445 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7446 } 7447 7448 // writer 7449 synchronized (mPackages) { 7450 mPackages.remove(pkg.applicationInfo.packageName); 7451 cleanPackageDataStructuresLILPw(pkg, chatty); 7452 } 7453 } 7454 7455 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7456 int N = pkg.providers.size(); 7457 StringBuilder r = null; 7458 int i; 7459 for (i=0; i<N; i++) { 7460 PackageParser.Provider p = pkg.providers.get(i); 7461 mProviders.removeProvider(p); 7462 if (p.info.authority == null) { 7463 7464 /* There was another ContentProvider with this authority when 7465 * this app was installed so this authority is null, 7466 * Ignore it as we don't have to unregister the provider. 7467 */ 7468 continue; 7469 } 7470 String names[] = p.info.authority.split(";"); 7471 for (int j = 0; j < names.length; j++) { 7472 if (mProvidersByAuthority.get(names[j]) == p) { 7473 mProvidersByAuthority.remove(names[j]); 7474 if (DEBUG_REMOVE) { 7475 if (chatty) 7476 Log.d(TAG, "Unregistered content provider: " + names[j] 7477 + ", className = " + p.info.name + ", isSyncable = " 7478 + p.info.isSyncable); 7479 } 7480 } 7481 } 7482 if (DEBUG_REMOVE && chatty) { 7483 if (r == null) { 7484 r = new StringBuilder(256); 7485 } else { 7486 r.append(' '); 7487 } 7488 r.append(p.info.name); 7489 } 7490 } 7491 if (r != null) { 7492 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7493 } 7494 7495 N = pkg.services.size(); 7496 r = null; 7497 for (i=0; i<N; i++) { 7498 PackageParser.Service s = pkg.services.get(i); 7499 mServices.removeService(s); 7500 if (chatty) { 7501 if (r == null) { 7502 r = new StringBuilder(256); 7503 } else { 7504 r.append(' '); 7505 } 7506 r.append(s.info.name); 7507 } 7508 } 7509 if (r != null) { 7510 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7511 } 7512 7513 N = pkg.receivers.size(); 7514 r = null; 7515 for (i=0; i<N; i++) { 7516 PackageParser.Activity a = pkg.receivers.get(i); 7517 mReceivers.removeActivity(a, "receiver"); 7518 if (DEBUG_REMOVE && chatty) { 7519 if (r == null) { 7520 r = new StringBuilder(256); 7521 } else { 7522 r.append(' '); 7523 } 7524 r.append(a.info.name); 7525 } 7526 } 7527 if (r != null) { 7528 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7529 } 7530 7531 N = pkg.activities.size(); 7532 r = null; 7533 for (i=0; i<N; i++) { 7534 PackageParser.Activity a = pkg.activities.get(i); 7535 mActivities.removeActivity(a, "activity"); 7536 if (DEBUG_REMOVE && chatty) { 7537 if (r == null) { 7538 r = new StringBuilder(256); 7539 } else { 7540 r.append(' '); 7541 } 7542 r.append(a.info.name); 7543 } 7544 } 7545 if (r != null) { 7546 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7547 } 7548 7549 N = pkg.permissions.size(); 7550 r = null; 7551 for (i=0; i<N; i++) { 7552 PackageParser.Permission p = pkg.permissions.get(i); 7553 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7554 if (bp == null) { 7555 bp = mSettings.mPermissionTrees.get(p.info.name); 7556 } 7557 if (bp != null && bp.perm == p) { 7558 bp.perm = null; 7559 if (DEBUG_REMOVE && chatty) { 7560 if (r == null) { 7561 r = new StringBuilder(256); 7562 } else { 7563 r.append(' '); 7564 } 7565 r.append(p.info.name); 7566 } 7567 } 7568 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7569 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7570 if (appOpPerms != null) { 7571 appOpPerms.remove(pkg.packageName); 7572 } 7573 } 7574 } 7575 if (r != null) { 7576 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7577 } 7578 7579 N = pkg.requestedPermissions.size(); 7580 r = null; 7581 for (i=0; i<N; i++) { 7582 String perm = pkg.requestedPermissions.get(i); 7583 BasePermission bp = mSettings.mPermissions.get(perm); 7584 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7585 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7586 if (appOpPerms != null) { 7587 appOpPerms.remove(pkg.packageName); 7588 if (appOpPerms.isEmpty()) { 7589 mAppOpPermissionPackages.remove(perm); 7590 } 7591 } 7592 } 7593 } 7594 if (r != null) { 7595 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7596 } 7597 7598 N = pkg.instrumentation.size(); 7599 r = null; 7600 for (i=0; i<N; i++) { 7601 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7602 mInstrumentation.remove(a.getComponentName()); 7603 if (DEBUG_REMOVE && chatty) { 7604 if (r == null) { 7605 r = new StringBuilder(256); 7606 } else { 7607 r.append(' '); 7608 } 7609 r.append(a.info.name); 7610 } 7611 } 7612 if (r != null) { 7613 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7614 } 7615 7616 r = null; 7617 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7618 // Only system apps can hold shared libraries. 7619 if (pkg.libraryNames != null) { 7620 for (i=0; i<pkg.libraryNames.size(); i++) { 7621 String name = pkg.libraryNames.get(i); 7622 SharedLibraryEntry cur = mSharedLibraries.get(name); 7623 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7624 mSharedLibraries.remove(name); 7625 if (DEBUG_REMOVE && chatty) { 7626 if (r == null) { 7627 r = new StringBuilder(256); 7628 } else { 7629 r.append(' '); 7630 } 7631 r.append(name); 7632 } 7633 } 7634 } 7635 } 7636 } 7637 if (r != null) { 7638 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7639 } 7640 } 7641 7642 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7643 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7644 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7645 return true; 7646 } 7647 } 7648 return false; 7649 } 7650 7651 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7652 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7653 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7654 7655 private void updatePermissionsLPw(String changingPkg, 7656 PackageParser.Package pkgInfo, int flags) { 7657 // Make sure there are no dangling permission trees. 7658 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7659 while (it.hasNext()) { 7660 final BasePermission bp = it.next(); 7661 if (bp.packageSetting == null) { 7662 // We may not yet have parsed the package, so just see if 7663 // we still know about its settings. 7664 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7665 } 7666 if (bp.packageSetting == null) { 7667 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7668 + " from package " + bp.sourcePackage); 7669 it.remove(); 7670 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7671 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7672 Slog.i(TAG, "Removing old permission tree: " + bp.name 7673 + " from package " + bp.sourcePackage); 7674 flags |= UPDATE_PERMISSIONS_ALL; 7675 it.remove(); 7676 } 7677 } 7678 } 7679 7680 // Make sure all dynamic permissions have been assigned to a package, 7681 // and make sure there are no dangling permissions. 7682 it = mSettings.mPermissions.values().iterator(); 7683 while (it.hasNext()) { 7684 final BasePermission bp = it.next(); 7685 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7686 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7687 + bp.name + " pkg=" + bp.sourcePackage 7688 + " info=" + bp.pendingInfo); 7689 if (bp.packageSetting == null && bp.pendingInfo != null) { 7690 final BasePermission tree = findPermissionTreeLP(bp.name); 7691 if (tree != null && tree.perm != null) { 7692 bp.packageSetting = tree.packageSetting; 7693 bp.perm = new PackageParser.Permission(tree.perm.owner, 7694 new PermissionInfo(bp.pendingInfo)); 7695 bp.perm.info.packageName = tree.perm.info.packageName; 7696 bp.perm.info.name = bp.name; 7697 bp.uid = tree.uid; 7698 } 7699 } 7700 } 7701 if (bp.packageSetting == null) { 7702 // We may not yet have parsed the package, so just see if 7703 // we still know about its settings. 7704 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7705 } 7706 if (bp.packageSetting == null) { 7707 Slog.w(TAG, "Removing dangling permission: " + bp.name 7708 + " from package " + bp.sourcePackage); 7709 it.remove(); 7710 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7711 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7712 Slog.i(TAG, "Removing old permission: " + bp.name 7713 + " from package " + bp.sourcePackage); 7714 flags |= UPDATE_PERMISSIONS_ALL; 7715 it.remove(); 7716 } 7717 } 7718 } 7719 7720 // Now update the permissions for all packages, in particular 7721 // replace the granted permissions of the system packages. 7722 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7723 for (PackageParser.Package pkg : mPackages.values()) { 7724 if (pkg != pkgInfo) { 7725 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7726 changingPkg); 7727 } 7728 } 7729 } 7730 7731 if (pkgInfo != null) { 7732 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7733 } 7734 } 7735 7736 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7737 String packageOfInterest) { 7738 // IMPORTANT: There are two types of permissions: install and runtime. 7739 // Install time permissions are granted when the app is installed to 7740 // all device users and users added in the future. Runtime permissions 7741 // are granted at runtime explicitly to specific users. Normal and signature 7742 // protected permissions are install time permissions. Dangerous permissions 7743 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7744 // otherwise they are runtime permissions. This function does not manage 7745 // runtime permissions except for the case an app targeting Lollipop MR1 7746 // being upgraded to target a newer SDK, in which case dangerous permissions 7747 // are transformed from install time to runtime ones. 7748 7749 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7750 if (ps == null) { 7751 return; 7752 } 7753 7754 PermissionsState permissionsState = ps.getPermissionsState(); 7755 PermissionsState origPermissions = permissionsState; 7756 7757 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7758 7759 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7760 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7761 7762 boolean changedInstallPermission = false; 7763 7764 if (replace) { 7765 ps.installPermissionsFixed = false; 7766 if (!ps.isSharedUser()) { 7767 origPermissions = new PermissionsState(permissionsState); 7768 permissionsState.reset(); 7769 } 7770 } 7771 7772 permissionsState.setGlobalGids(mGlobalGids); 7773 7774 final int N = pkg.requestedPermissions.size(); 7775 for (int i=0; i<N; i++) { 7776 final String name = pkg.requestedPermissions.get(i); 7777 final BasePermission bp = mSettings.mPermissions.get(name); 7778 7779 if (DEBUG_INSTALL) { 7780 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7781 } 7782 7783 if (bp == null || bp.packageSetting == null) { 7784 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7785 Slog.w(TAG, "Unknown permission " + name 7786 + " in package " + pkg.packageName); 7787 } 7788 continue; 7789 } 7790 7791 final String perm = bp.name; 7792 boolean allowedSig = false; 7793 int grant = GRANT_DENIED; 7794 7795 // Keep track of app op permissions. 7796 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7797 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7798 if (pkgs == null) { 7799 pkgs = new ArraySet<>(); 7800 mAppOpPermissionPackages.put(bp.name, pkgs); 7801 } 7802 pkgs.add(pkg.packageName); 7803 } 7804 7805 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7806 switch (level) { 7807 case PermissionInfo.PROTECTION_NORMAL: { 7808 // For all apps normal permissions are install time ones. 7809 grant = GRANT_INSTALL; 7810 } break; 7811 7812 case PermissionInfo.PROTECTION_DANGEROUS: { 7813 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7814 // For legacy apps dangerous permissions are install time ones. 7815 grant = GRANT_INSTALL_LEGACY; 7816 } else if (ps.isSystem()) { 7817 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7818 if (origPermissions.hasInstallPermission(bp.name)) { 7819 // If a system app had an install permission, then the app was 7820 // upgraded and we grant the permissions as runtime to all users. 7821 grant = GRANT_UPGRADE; 7822 upgradeUserIds = currentUserIds; 7823 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7824 // If users changed since the last permissions update for a 7825 // system app, we grant the permission as runtime to the new users. 7826 grant = GRANT_UPGRADE; 7827 upgradeUserIds = currentUserIds; 7828 for (int userId : updatedUserIds) { 7829 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7830 } 7831 } else { 7832 // Otherwise, we grant the permission as runtime if the app 7833 // already had it, i.e. we preserve runtime permissions. 7834 grant = GRANT_RUNTIME; 7835 } 7836 } else if (origPermissions.hasInstallPermission(bp.name)) { 7837 // For legacy apps that became modern, install becomes runtime. 7838 grant = GRANT_UPGRADE; 7839 upgradeUserIds = currentUserIds; 7840 } else if (replace) { 7841 // For upgraded modern apps keep runtime permissions unchanged. 7842 grant = GRANT_RUNTIME; 7843 } 7844 } break; 7845 7846 case PermissionInfo.PROTECTION_SIGNATURE: { 7847 // For all apps signature permissions are install time ones. 7848 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7849 if (allowedSig) { 7850 grant = GRANT_INSTALL; 7851 } 7852 } break; 7853 } 7854 7855 if (DEBUG_INSTALL) { 7856 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7857 } 7858 7859 if (grant != GRANT_DENIED) { 7860 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7861 // If this is an existing, non-system package, then 7862 // we can't add any new permissions to it. 7863 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7864 // Except... if this is a permission that was added 7865 // to the platform (note: need to only do this when 7866 // updating the platform). 7867 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7868 grant = GRANT_DENIED; 7869 } 7870 } 7871 } 7872 7873 switch (grant) { 7874 case GRANT_INSTALL: { 7875 // Revoke this as runtime permission to handle the case of 7876 // a runtime permssion being downgraded to an install one. 7877 for (int userId : UserManagerService.getInstance().getUserIds()) { 7878 if (origPermissions.getRuntimePermissionState( 7879 bp.name, userId) != null) { 7880 // Revoke the runtime permission and clear the flags. 7881 origPermissions.revokeRuntimePermission(bp, userId); 7882 origPermissions.updatePermissionFlags(bp, userId, 7883 PackageManager.MASK_PERMISSION_FLAGS, 0); 7884 // If we revoked a permission permission, we have to write. 7885 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7886 changedRuntimePermissionUserIds, userId); 7887 } 7888 } 7889 // Grant an install permission. 7890 if (permissionsState.grantInstallPermission(bp) != 7891 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7892 changedInstallPermission = true; 7893 } 7894 } break; 7895 7896 case GRANT_INSTALL_LEGACY: { 7897 // Grant an install permission. 7898 if (permissionsState.grantInstallPermission(bp) != 7899 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7900 changedInstallPermission = true; 7901 } 7902 } break; 7903 7904 case GRANT_RUNTIME: { 7905 // Grant previously granted runtime permissions. 7906 for (int userId : UserManagerService.getInstance().getUserIds()) { 7907 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7908 PermissionState permissionState = origPermissions 7909 .getRuntimePermissionState(bp.name, userId); 7910 final int flags = permissionState.getFlags(); 7911 if (permissionsState.grantRuntimePermission(bp, userId) == 7912 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7913 // If we cannot put the permission as it was, we have to write. 7914 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7915 changedRuntimePermissionUserIds, userId); 7916 } else { 7917 // System components not only get the permissions but 7918 // they are also fixed, so nothing can change that. 7919 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7920 ? flags 7921 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7922 // Propagate the permission flags. 7923 permissionsState.updatePermissionFlags(bp, userId, 7924 newFlags, newFlags); 7925 } 7926 } 7927 } 7928 } break; 7929 7930 case GRANT_UPGRADE: { 7931 // Grant runtime permissions for a previously held install permission. 7932 PermissionState permissionState = origPermissions 7933 .getInstallPermissionState(bp.name); 7934 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7935 7936 origPermissions.revokeInstallPermission(bp); 7937 // We will be transferring the permission flags, so clear them. 7938 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7939 PackageManager.MASK_PERMISSION_FLAGS, 0); 7940 7941 // If the permission is not to be promoted to runtime we ignore it and 7942 // also its other flags as they are not applicable to install permissions. 7943 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7944 for (int userId : upgradeUserIds) { 7945 if (permissionsState.grantRuntimePermission(bp, userId) != 7946 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7947 // System components not only get the permissions but 7948 // they are also fixed so nothing can change that. 7949 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7950 ? flags 7951 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7952 // Transfer the permission flags. 7953 permissionsState.updatePermissionFlags(bp, userId, 7954 newFlags, newFlags); 7955 // If we granted the permission, we have to write. 7956 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7957 changedRuntimePermissionUserIds, userId); 7958 } 7959 } 7960 } 7961 } break; 7962 7963 default: { 7964 if (packageOfInterest == null 7965 || packageOfInterest.equals(pkg.packageName)) { 7966 Slog.w(TAG, "Not granting permission " + perm 7967 + " to package " + pkg.packageName 7968 + " because it was previously installed without"); 7969 } 7970 } break; 7971 } 7972 } else { 7973 if (permissionsState.revokeInstallPermission(bp) != 7974 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7975 // Also drop the permission flags. 7976 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7977 PackageManager.MASK_PERMISSION_FLAGS, 0); 7978 changedInstallPermission = true; 7979 Slog.i(TAG, "Un-granting permission " + perm 7980 + " from package " + pkg.packageName 7981 + " (protectionLevel=" + bp.protectionLevel 7982 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7983 + ")"); 7984 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7985 // Don't print warning for app op permissions, since it is fine for them 7986 // not to be granted, there is a UI for the user to decide. 7987 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7988 Slog.w(TAG, "Not granting permission " + perm 7989 + " to package " + pkg.packageName 7990 + " (protectionLevel=" + bp.protectionLevel 7991 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7992 + ")"); 7993 } 7994 } 7995 } 7996 } 7997 7998 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7999 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8000 // This is the first that we have heard about this package, so the 8001 // permissions we have now selected are fixed until explicitly 8002 // changed. 8003 ps.installPermissionsFixed = true; 8004 } 8005 8006 ps.setPermissionsUpdatedForUserIds(currentUserIds); 8007 8008 // Persist the runtime permissions state for users with changes. 8009 for (int userId : changedRuntimePermissionUserIds) { 8010 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 8011 } 8012 } 8013 8014 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8015 boolean allowed = false; 8016 final int NP = PackageParser.NEW_PERMISSIONS.length; 8017 for (int ip=0; ip<NP; ip++) { 8018 final PackageParser.NewPermissionInfo npi 8019 = PackageParser.NEW_PERMISSIONS[ip]; 8020 if (npi.name.equals(perm) 8021 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8022 allowed = true; 8023 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8024 + pkg.packageName); 8025 break; 8026 } 8027 } 8028 return allowed; 8029 } 8030 8031 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8032 BasePermission bp, PermissionsState origPermissions) { 8033 boolean allowed; 8034 allowed = (compareSignatures( 8035 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8036 == PackageManager.SIGNATURE_MATCH) 8037 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8038 == PackageManager.SIGNATURE_MATCH); 8039 if (!allowed && (bp.protectionLevel 8040 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8041 if (isSystemApp(pkg)) { 8042 // For updated system applications, a system permission 8043 // is granted only if it had been defined by the original application. 8044 if (pkg.isUpdatedSystemApp()) { 8045 final PackageSetting sysPs = mSettings 8046 .getDisabledSystemPkgLPr(pkg.packageName); 8047 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8048 // If the original was granted this permission, we take 8049 // that grant decision as read and propagate it to the 8050 // update. 8051 if (sysPs.isPrivileged()) { 8052 allowed = true; 8053 } 8054 } else { 8055 // The system apk may have been updated with an older 8056 // version of the one on the data partition, but which 8057 // granted a new system permission that it didn't have 8058 // before. In this case we do want to allow the app to 8059 // now get the new permission if the ancestral apk is 8060 // privileged to get it. 8061 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8062 for (int j=0; 8063 j<sysPs.pkg.requestedPermissions.size(); j++) { 8064 if (perm.equals( 8065 sysPs.pkg.requestedPermissions.get(j))) { 8066 allowed = true; 8067 break; 8068 } 8069 } 8070 } 8071 } 8072 } else { 8073 allowed = isPrivilegedApp(pkg); 8074 } 8075 } 8076 } 8077 if (!allowed && (bp.protectionLevel 8078 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8079 // For development permissions, a development permission 8080 // is granted only if it was already granted. 8081 allowed = origPermissions.hasInstallPermission(perm); 8082 } 8083 return allowed; 8084 } 8085 8086 final class ActivityIntentResolver 8087 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8088 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8089 boolean defaultOnly, int userId) { 8090 if (!sUserManager.exists(userId)) return null; 8091 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8092 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8093 } 8094 8095 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8096 int userId) { 8097 if (!sUserManager.exists(userId)) return null; 8098 mFlags = flags; 8099 return super.queryIntent(intent, resolvedType, 8100 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8101 } 8102 8103 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8104 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8105 if (!sUserManager.exists(userId)) return null; 8106 if (packageActivities == null) { 8107 return null; 8108 } 8109 mFlags = flags; 8110 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8111 final int N = packageActivities.size(); 8112 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8113 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8114 8115 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8116 for (int i = 0; i < N; ++i) { 8117 intentFilters = packageActivities.get(i).intents; 8118 if (intentFilters != null && intentFilters.size() > 0) { 8119 PackageParser.ActivityIntentInfo[] array = 8120 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8121 intentFilters.toArray(array); 8122 listCut.add(array); 8123 } 8124 } 8125 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8126 } 8127 8128 public final void addActivity(PackageParser.Activity a, String type) { 8129 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8130 mActivities.put(a.getComponentName(), a); 8131 if (DEBUG_SHOW_INFO) 8132 Log.v( 8133 TAG, " " + type + " " + 8134 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8135 if (DEBUG_SHOW_INFO) 8136 Log.v(TAG, " Class=" + a.info.name); 8137 final int NI = a.intents.size(); 8138 for (int j=0; j<NI; j++) { 8139 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8140 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8141 intent.setPriority(0); 8142 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8143 + a.className + " with priority > 0, forcing to 0"); 8144 } 8145 if (DEBUG_SHOW_INFO) { 8146 Log.v(TAG, " IntentFilter:"); 8147 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8148 } 8149 if (!intent.debugCheck()) { 8150 Log.w(TAG, "==> For Activity " + a.info.name); 8151 } 8152 addFilter(intent); 8153 } 8154 } 8155 8156 public final void removeActivity(PackageParser.Activity a, String type) { 8157 mActivities.remove(a.getComponentName()); 8158 if (DEBUG_SHOW_INFO) { 8159 Log.v(TAG, " " + type + " " 8160 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8161 : a.info.name) + ":"); 8162 Log.v(TAG, " Class=" + a.info.name); 8163 } 8164 final int NI = a.intents.size(); 8165 for (int j=0; j<NI; j++) { 8166 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8167 if (DEBUG_SHOW_INFO) { 8168 Log.v(TAG, " IntentFilter:"); 8169 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8170 } 8171 removeFilter(intent); 8172 } 8173 } 8174 8175 @Override 8176 protected boolean allowFilterResult( 8177 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8178 ActivityInfo filterAi = filter.activity.info; 8179 for (int i=dest.size()-1; i>=0; i--) { 8180 ActivityInfo destAi = dest.get(i).activityInfo; 8181 if (destAi.name == filterAi.name 8182 && destAi.packageName == filterAi.packageName) { 8183 return false; 8184 } 8185 } 8186 return true; 8187 } 8188 8189 @Override 8190 protected ActivityIntentInfo[] newArray(int size) { 8191 return new ActivityIntentInfo[size]; 8192 } 8193 8194 @Override 8195 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8196 if (!sUserManager.exists(userId)) return true; 8197 PackageParser.Package p = filter.activity.owner; 8198 if (p != null) { 8199 PackageSetting ps = (PackageSetting)p.mExtras; 8200 if (ps != null) { 8201 // System apps are never considered stopped for purposes of 8202 // filtering, because there may be no way for the user to 8203 // actually re-launch them. 8204 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8205 && ps.getStopped(userId); 8206 } 8207 } 8208 return false; 8209 } 8210 8211 @Override 8212 protected boolean isPackageForFilter(String packageName, 8213 PackageParser.ActivityIntentInfo info) { 8214 return packageName.equals(info.activity.owner.packageName); 8215 } 8216 8217 @Override 8218 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8219 int match, int userId) { 8220 if (!sUserManager.exists(userId)) return null; 8221 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8222 return null; 8223 } 8224 final PackageParser.Activity activity = info.activity; 8225 if (mSafeMode && (activity.info.applicationInfo.flags 8226 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8227 return null; 8228 } 8229 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8230 if (ps == null) { 8231 return null; 8232 } 8233 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8234 ps.readUserState(userId), userId); 8235 if (ai == null) { 8236 return null; 8237 } 8238 final ResolveInfo res = new ResolveInfo(); 8239 res.activityInfo = ai; 8240 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8241 res.filter = info; 8242 } 8243 if (info != null) { 8244 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8245 } 8246 res.priority = info.getPriority(); 8247 res.preferredOrder = activity.owner.mPreferredOrder; 8248 //System.out.println("Result: " + res.activityInfo.className + 8249 // " = " + res.priority); 8250 res.match = match; 8251 res.isDefault = info.hasDefault; 8252 res.labelRes = info.labelRes; 8253 res.nonLocalizedLabel = info.nonLocalizedLabel; 8254 if (userNeedsBadging(userId)) { 8255 res.noResourceId = true; 8256 } else { 8257 res.icon = info.icon; 8258 } 8259 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8260 return res; 8261 } 8262 8263 @Override 8264 protected void sortResults(List<ResolveInfo> results) { 8265 Collections.sort(results, mResolvePrioritySorter); 8266 } 8267 8268 @Override 8269 protected void dumpFilter(PrintWriter out, String prefix, 8270 PackageParser.ActivityIntentInfo filter) { 8271 out.print(prefix); out.print( 8272 Integer.toHexString(System.identityHashCode(filter.activity))); 8273 out.print(' '); 8274 filter.activity.printComponentShortName(out); 8275 out.print(" filter "); 8276 out.println(Integer.toHexString(System.identityHashCode(filter))); 8277 } 8278 8279 @Override 8280 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8281 return filter.activity; 8282 } 8283 8284 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8285 PackageParser.Activity activity = (PackageParser.Activity)label; 8286 out.print(prefix); out.print( 8287 Integer.toHexString(System.identityHashCode(activity))); 8288 out.print(' '); 8289 activity.printComponentShortName(out); 8290 if (count > 1) { 8291 out.print(" ("); out.print(count); out.print(" filters)"); 8292 } 8293 out.println(); 8294 } 8295 8296// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8297// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8298// final List<ResolveInfo> retList = Lists.newArrayList(); 8299// while (i.hasNext()) { 8300// final ResolveInfo resolveInfo = i.next(); 8301// if (isEnabledLP(resolveInfo.activityInfo)) { 8302// retList.add(resolveInfo); 8303// } 8304// } 8305// return retList; 8306// } 8307 8308 // Keys are String (activity class name), values are Activity. 8309 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8310 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8311 private int mFlags; 8312 } 8313 8314 private final class ServiceIntentResolver 8315 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8316 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8317 boolean defaultOnly, int userId) { 8318 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8319 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8320 } 8321 8322 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8323 int userId) { 8324 if (!sUserManager.exists(userId)) return null; 8325 mFlags = flags; 8326 return super.queryIntent(intent, resolvedType, 8327 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8328 } 8329 8330 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8331 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8332 if (!sUserManager.exists(userId)) return null; 8333 if (packageServices == null) { 8334 return null; 8335 } 8336 mFlags = flags; 8337 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8338 final int N = packageServices.size(); 8339 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8340 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8341 8342 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8343 for (int i = 0; i < N; ++i) { 8344 intentFilters = packageServices.get(i).intents; 8345 if (intentFilters != null && intentFilters.size() > 0) { 8346 PackageParser.ServiceIntentInfo[] array = 8347 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8348 intentFilters.toArray(array); 8349 listCut.add(array); 8350 } 8351 } 8352 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8353 } 8354 8355 public final void addService(PackageParser.Service s) { 8356 mServices.put(s.getComponentName(), s); 8357 if (DEBUG_SHOW_INFO) { 8358 Log.v(TAG, " " 8359 + (s.info.nonLocalizedLabel != null 8360 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8361 Log.v(TAG, " Class=" + s.info.name); 8362 } 8363 final int NI = s.intents.size(); 8364 int j; 8365 for (j=0; j<NI; j++) { 8366 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8367 if (DEBUG_SHOW_INFO) { 8368 Log.v(TAG, " IntentFilter:"); 8369 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8370 } 8371 if (!intent.debugCheck()) { 8372 Log.w(TAG, "==> For Service " + s.info.name); 8373 } 8374 addFilter(intent); 8375 } 8376 } 8377 8378 public final void removeService(PackageParser.Service s) { 8379 mServices.remove(s.getComponentName()); 8380 if (DEBUG_SHOW_INFO) { 8381 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8382 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8383 Log.v(TAG, " Class=" + s.info.name); 8384 } 8385 final int NI = s.intents.size(); 8386 int j; 8387 for (j=0; j<NI; j++) { 8388 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8389 if (DEBUG_SHOW_INFO) { 8390 Log.v(TAG, " IntentFilter:"); 8391 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8392 } 8393 removeFilter(intent); 8394 } 8395 } 8396 8397 @Override 8398 protected boolean allowFilterResult( 8399 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8400 ServiceInfo filterSi = filter.service.info; 8401 for (int i=dest.size()-1; i>=0; i--) { 8402 ServiceInfo destAi = dest.get(i).serviceInfo; 8403 if (destAi.name == filterSi.name 8404 && destAi.packageName == filterSi.packageName) { 8405 return false; 8406 } 8407 } 8408 return true; 8409 } 8410 8411 @Override 8412 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8413 return new PackageParser.ServiceIntentInfo[size]; 8414 } 8415 8416 @Override 8417 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8418 if (!sUserManager.exists(userId)) return true; 8419 PackageParser.Package p = filter.service.owner; 8420 if (p != null) { 8421 PackageSetting ps = (PackageSetting)p.mExtras; 8422 if (ps != null) { 8423 // System apps are never considered stopped for purposes of 8424 // filtering, because there may be no way for the user to 8425 // actually re-launch them. 8426 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8427 && ps.getStopped(userId); 8428 } 8429 } 8430 return false; 8431 } 8432 8433 @Override 8434 protected boolean isPackageForFilter(String packageName, 8435 PackageParser.ServiceIntentInfo info) { 8436 return packageName.equals(info.service.owner.packageName); 8437 } 8438 8439 @Override 8440 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8441 int match, int userId) { 8442 if (!sUserManager.exists(userId)) return null; 8443 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8444 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8445 return null; 8446 } 8447 final PackageParser.Service service = info.service; 8448 if (mSafeMode && (service.info.applicationInfo.flags 8449 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8450 return null; 8451 } 8452 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8453 if (ps == null) { 8454 return null; 8455 } 8456 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8457 ps.readUserState(userId), userId); 8458 if (si == null) { 8459 return null; 8460 } 8461 final ResolveInfo res = new ResolveInfo(); 8462 res.serviceInfo = si; 8463 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8464 res.filter = filter; 8465 } 8466 res.priority = info.getPriority(); 8467 res.preferredOrder = service.owner.mPreferredOrder; 8468 res.match = match; 8469 res.isDefault = info.hasDefault; 8470 res.labelRes = info.labelRes; 8471 res.nonLocalizedLabel = info.nonLocalizedLabel; 8472 res.icon = info.icon; 8473 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8474 return res; 8475 } 8476 8477 @Override 8478 protected void sortResults(List<ResolveInfo> results) { 8479 Collections.sort(results, mResolvePrioritySorter); 8480 } 8481 8482 @Override 8483 protected void dumpFilter(PrintWriter out, String prefix, 8484 PackageParser.ServiceIntentInfo filter) { 8485 out.print(prefix); out.print( 8486 Integer.toHexString(System.identityHashCode(filter.service))); 8487 out.print(' '); 8488 filter.service.printComponentShortName(out); 8489 out.print(" filter "); 8490 out.println(Integer.toHexString(System.identityHashCode(filter))); 8491 } 8492 8493 @Override 8494 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8495 return filter.service; 8496 } 8497 8498 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8499 PackageParser.Service service = (PackageParser.Service)label; 8500 out.print(prefix); out.print( 8501 Integer.toHexString(System.identityHashCode(service))); 8502 out.print(' '); 8503 service.printComponentShortName(out); 8504 if (count > 1) { 8505 out.print(" ("); out.print(count); out.print(" filters)"); 8506 } 8507 out.println(); 8508 } 8509 8510// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8511// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8512// final List<ResolveInfo> retList = Lists.newArrayList(); 8513// while (i.hasNext()) { 8514// final ResolveInfo resolveInfo = (ResolveInfo) i; 8515// if (isEnabledLP(resolveInfo.serviceInfo)) { 8516// retList.add(resolveInfo); 8517// } 8518// } 8519// return retList; 8520// } 8521 8522 // Keys are String (activity class name), values are Activity. 8523 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8524 = new ArrayMap<ComponentName, PackageParser.Service>(); 8525 private int mFlags; 8526 }; 8527 8528 private final class ProviderIntentResolver 8529 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8530 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8531 boolean defaultOnly, int userId) { 8532 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8533 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8534 } 8535 8536 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8537 int userId) { 8538 if (!sUserManager.exists(userId)) 8539 return null; 8540 mFlags = flags; 8541 return super.queryIntent(intent, resolvedType, 8542 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8543 } 8544 8545 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8546 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8547 if (!sUserManager.exists(userId)) 8548 return null; 8549 if (packageProviders == null) { 8550 return null; 8551 } 8552 mFlags = flags; 8553 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8554 final int N = packageProviders.size(); 8555 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8556 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8557 8558 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8559 for (int i = 0; i < N; ++i) { 8560 intentFilters = packageProviders.get(i).intents; 8561 if (intentFilters != null && intentFilters.size() > 0) { 8562 PackageParser.ProviderIntentInfo[] array = 8563 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8564 intentFilters.toArray(array); 8565 listCut.add(array); 8566 } 8567 } 8568 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8569 } 8570 8571 public final void addProvider(PackageParser.Provider p) { 8572 if (mProviders.containsKey(p.getComponentName())) { 8573 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8574 return; 8575 } 8576 8577 mProviders.put(p.getComponentName(), p); 8578 if (DEBUG_SHOW_INFO) { 8579 Log.v(TAG, " " 8580 + (p.info.nonLocalizedLabel != null 8581 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8582 Log.v(TAG, " Class=" + p.info.name); 8583 } 8584 final int NI = p.intents.size(); 8585 int j; 8586 for (j = 0; j < NI; j++) { 8587 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8588 if (DEBUG_SHOW_INFO) { 8589 Log.v(TAG, " IntentFilter:"); 8590 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8591 } 8592 if (!intent.debugCheck()) { 8593 Log.w(TAG, "==> For Provider " + p.info.name); 8594 } 8595 addFilter(intent); 8596 } 8597 } 8598 8599 public final void removeProvider(PackageParser.Provider p) { 8600 mProviders.remove(p.getComponentName()); 8601 if (DEBUG_SHOW_INFO) { 8602 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8603 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8604 Log.v(TAG, " Class=" + p.info.name); 8605 } 8606 final int NI = p.intents.size(); 8607 int j; 8608 for (j = 0; j < NI; j++) { 8609 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8610 if (DEBUG_SHOW_INFO) { 8611 Log.v(TAG, " IntentFilter:"); 8612 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8613 } 8614 removeFilter(intent); 8615 } 8616 } 8617 8618 @Override 8619 protected boolean allowFilterResult( 8620 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8621 ProviderInfo filterPi = filter.provider.info; 8622 for (int i = dest.size() - 1; i >= 0; i--) { 8623 ProviderInfo destPi = dest.get(i).providerInfo; 8624 if (destPi.name == filterPi.name 8625 && destPi.packageName == filterPi.packageName) { 8626 return false; 8627 } 8628 } 8629 return true; 8630 } 8631 8632 @Override 8633 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8634 return new PackageParser.ProviderIntentInfo[size]; 8635 } 8636 8637 @Override 8638 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8639 if (!sUserManager.exists(userId)) 8640 return true; 8641 PackageParser.Package p = filter.provider.owner; 8642 if (p != null) { 8643 PackageSetting ps = (PackageSetting) p.mExtras; 8644 if (ps != null) { 8645 // System apps are never considered stopped for purposes of 8646 // filtering, because there may be no way for the user to 8647 // actually re-launch them. 8648 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8649 && ps.getStopped(userId); 8650 } 8651 } 8652 return false; 8653 } 8654 8655 @Override 8656 protected boolean isPackageForFilter(String packageName, 8657 PackageParser.ProviderIntentInfo info) { 8658 return packageName.equals(info.provider.owner.packageName); 8659 } 8660 8661 @Override 8662 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8663 int match, int userId) { 8664 if (!sUserManager.exists(userId)) 8665 return null; 8666 final PackageParser.ProviderIntentInfo info = filter; 8667 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8668 return null; 8669 } 8670 final PackageParser.Provider provider = info.provider; 8671 if (mSafeMode && (provider.info.applicationInfo.flags 8672 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8673 return null; 8674 } 8675 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8676 if (ps == null) { 8677 return null; 8678 } 8679 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8680 ps.readUserState(userId), userId); 8681 if (pi == null) { 8682 return null; 8683 } 8684 final ResolveInfo res = new ResolveInfo(); 8685 res.providerInfo = pi; 8686 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8687 res.filter = filter; 8688 } 8689 res.priority = info.getPriority(); 8690 res.preferredOrder = provider.owner.mPreferredOrder; 8691 res.match = match; 8692 res.isDefault = info.hasDefault; 8693 res.labelRes = info.labelRes; 8694 res.nonLocalizedLabel = info.nonLocalizedLabel; 8695 res.icon = info.icon; 8696 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8697 return res; 8698 } 8699 8700 @Override 8701 protected void sortResults(List<ResolveInfo> results) { 8702 Collections.sort(results, mResolvePrioritySorter); 8703 } 8704 8705 @Override 8706 protected void dumpFilter(PrintWriter out, String prefix, 8707 PackageParser.ProviderIntentInfo filter) { 8708 out.print(prefix); 8709 out.print( 8710 Integer.toHexString(System.identityHashCode(filter.provider))); 8711 out.print(' '); 8712 filter.provider.printComponentShortName(out); 8713 out.print(" filter "); 8714 out.println(Integer.toHexString(System.identityHashCode(filter))); 8715 } 8716 8717 @Override 8718 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8719 return filter.provider; 8720 } 8721 8722 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8723 PackageParser.Provider provider = (PackageParser.Provider)label; 8724 out.print(prefix); out.print( 8725 Integer.toHexString(System.identityHashCode(provider))); 8726 out.print(' '); 8727 provider.printComponentShortName(out); 8728 if (count > 1) { 8729 out.print(" ("); out.print(count); out.print(" filters)"); 8730 } 8731 out.println(); 8732 } 8733 8734 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8735 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8736 private int mFlags; 8737 }; 8738 8739 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8740 new Comparator<ResolveInfo>() { 8741 public int compare(ResolveInfo r1, ResolveInfo r2) { 8742 int v1 = r1.priority; 8743 int v2 = r2.priority; 8744 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8745 if (v1 != v2) { 8746 return (v1 > v2) ? -1 : 1; 8747 } 8748 v1 = r1.preferredOrder; 8749 v2 = r2.preferredOrder; 8750 if (v1 != v2) { 8751 return (v1 > v2) ? -1 : 1; 8752 } 8753 if (r1.isDefault != r2.isDefault) { 8754 return r1.isDefault ? -1 : 1; 8755 } 8756 v1 = r1.match; 8757 v2 = r2.match; 8758 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8759 if (v1 != v2) { 8760 return (v1 > v2) ? -1 : 1; 8761 } 8762 if (r1.system != r2.system) { 8763 return r1.system ? -1 : 1; 8764 } 8765 return 0; 8766 } 8767 }; 8768 8769 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8770 new Comparator<ProviderInfo>() { 8771 public int compare(ProviderInfo p1, ProviderInfo p2) { 8772 final int v1 = p1.initOrder; 8773 final int v2 = p2.initOrder; 8774 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8775 } 8776 }; 8777 8778 final void sendPackageBroadcast(final String action, final String pkg, 8779 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8780 final int[] userIds) { 8781 mHandler.post(new Runnable() { 8782 @Override 8783 public void run() { 8784 try { 8785 final IActivityManager am = ActivityManagerNative.getDefault(); 8786 if (am == null) return; 8787 final int[] resolvedUserIds; 8788 if (userIds == null) { 8789 resolvedUserIds = am.getRunningUserIds(); 8790 } else { 8791 resolvedUserIds = userIds; 8792 } 8793 for (int id : resolvedUserIds) { 8794 final Intent intent = new Intent(action, 8795 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8796 if (extras != null) { 8797 intent.putExtras(extras); 8798 } 8799 if (targetPkg != null) { 8800 intent.setPackage(targetPkg); 8801 } 8802 // Modify the UID when posting to other users 8803 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8804 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8805 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8806 intent.putExtra(Intent.EXTRA_UID, uid); 8807 } 8808 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8809 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8810 if (DEBUG_BROADCASTS) { 8811 RuntimeException here = new RuntimeException("here"); 8812 here.fillInStackTrace(); 8813 Slog.d(TAG, "Sending to user " + id + ": " 8814 + intent.toShortString(false, true, false, false) 8815 + " " + intent.getExtras(), here); 8816 } 8817 am.broadcastIntent(null, intent, null, finishedReceiver, 8818 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8819 finishedReceiver != null, false, id); 8820 } 8821 } catch (RemoteException ex) { 8822 } 8823 } 8824 }); 8825 } 8826 8827 /** 8828 * Check if the external storage media is available. This is true if there 8829 * is a mounted external storage medium or if the external storage is 8830 * emulated. 8831 */ 8832 private boolean isExternalMediaAvailable() { 8833 return mMediaMounted || Environment.isExternalStorageEmulated(); 8834 } 8835 8836 @Override 8837 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8838 // writer 8839 synchronized (mPackages) { 8840 if (!isExternalMediaAvailable()) { 8841 // If the external storage is no longer mounted at this point, 8842 // the caller may not have been able to delete all of this 8843 // packages files and can not delete any more. Bail. 8844 return null; 8845 } 8846 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8847 if (lastPackage != null) { 8848 pkgs.remove(lastPackage); 8849 } 8850 if (pkgs.size() > 0) { 8851 return pkgs.get(0); 8852 } 8853 } 8854 return null; 8855 } 8856 8857 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8858 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8859 userId, andCode ? 1 : 0, packageName); 8860 if (mSystemReady) { 8861 msg.sendToTarget(); 8862 } else { 8863 if (mPostSystemReadyMessages == null) { 8864 mPostSystemReadyMessages = new ArrayList<>(); 8865 } 8866 mPostSystemReadyMessages.add(msg); 8867 } 8868 } 8869 8870 void startCleaningPackages() { 8871 // reader 8872 synchronized (mPackages) { 8873 if (!isExternalMediaAvailable()) { 8874 return; 8875 } 8876 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8877 return; 8878 } 8879 } 8880 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8881 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8882 IActivityManager am = ActivityManagerNative.getDefault(); 8883 if (am != null) { 8884 try { 8885 am.startService(null, intent, null, UserHandle.USER_OWNER); 8886 } catch (RemoteException e) { 8887 } 8888 } 8889 } 8890 8891 @Override 8892 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8893 int installFlags, String installerPackageName, VerificationParams verificationParams, 8894 String packageAbiOverride) { 8895 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8896 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8897 } 8898 8899 @Override 8900 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8901 int installFlags, String installerPackageName, VerificationParams verificationParams, 8902 String packageAbiOverride, int userId) { 8903 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8904 8905 final int callingUid = Binder.getCallingUid(); 8906 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8907 8908 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8909 try { 8910 if (observer != null) { 8911 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8912 } 8913 } catch (RemoteException re) { 8914 } 8915 return; 8916 } 8917 8918 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8919 installFlags |= PackageManager.INSTALL_FROM_ADB; 8920 8921 } else { 8922 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8923 // about installerPackageName. 8924 8925 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8926 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8927 } 8928 8929 UserHandle user; 8930 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8931 user = UserHandle.ALL; 8932 } else { 8933 user = new UserHandle(userId); 8934 } 8935 8936 // Only system components can circumvent runtime permissions when installing. 8937 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8938 && mContext.checkCallingOrSelfPermission(Manifest.permission 8939 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8940 throw new SecurityException("You need the " 8941 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8942 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8943 } 8944 8945 verificationParams.setInstallerUid(callingUid); 8946 8947 final File originFile = new File(originPath); 8948 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8949 8950 final Message msg = mHandler.obtainMessage(INIT_COPY); 8951 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8952 null, verificationParams, user, packageAbiOverride); 8953 mHandler.sendMessage(msg); 8954 } 8955 8956 void installStage(String packageName, File stagedDir, String stagedCid, 8957 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8958 String installerPackageName, int installerUid, UserHandle user) { 8959 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8960 params.referrerUri, installerUid, null); 8961 8962 final OriginInfo origin; 8963 if (stagedDir != null) { 8964 origin = OriginInfo.fromStagedFile(stagedDir); 8965 } else { 8966 origin = OriginInfo.fromStagedContainer(stagedCid); 8967 } 8968 8969 final Message msg = mHandler.obtainMessage(INIT_COPY); 8970 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8971 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8972 mHandler.sendMessage(msg); 8973 } 8974 8975 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8976 Bundle extras = new Bundle(1); 8977 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8978 8979 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8980 packageName, extras, null, null, new int[] {userId}); 8981 try { 8982 IActivityManager am = ActivityManagerNative.getDefault(); 8983 final boolean isSystem = 8984 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8985 if (isSystem && am.isUserRunning(userId, false)) { 8986 // The just-installed/enabled app is bundled on the system, so presumed 8987 // to be able to run automatically without needing an explicit launch. 8988 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8989 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8990 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8991 .setPackage(packageName); 8992 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8993 android.app.AppOpsManager.OP_NONE, false, false, userId); 8994 } 8995 } catch (RemoteException e) { 8996 // shouldn't happen 8997 Slog.w(TAG, "Unable to bootstrap installed package", e); 8998 } 8999 } 9000 9001 @Override 9002 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9003 int userId) { 9004 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9005 PackageSetting pkgSetting; 9006 final int uid = Binder.getCallingUid(); 9007 enforceCrossUserPermission(uid, userId, true, true, 9008 "setApplicationHiddenSetting for user " + userId); 9009 9010 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9011 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9012 return false; 9013 } 9014 9015 long callingId = Binder.clearCallingIdentity(); 9016 try { 9017 boolean sendAdded = false; 9018 boolean sendRemoved = false; 9019 // writer 9020 synchronized (mPackages) { 9021 pkgSetting = mSettings.mPackages.get(packageName); 9022 if (pkgSetting == null) { 9023 return false; 9024 } 9025 if (pkgSetting.getHidden(userId) != hidden) { 9026 pkgSetting.setHidden(hidden, userId); 9027 mSettings.writePackageRestrictionsLPr(userId); 9028 if (hidden) { 9029 sendRemoved = true; 9030 } else { 9031 sendAdded = true; 9032 } 9033 } 9034 } 9035 if (sendAdded) { 9036 sendPackageAddedForUser(packageName, pkgSetting, userId); 9037 return true; 9038 } 9039 if (sendRemoved) { 9040 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9041 "hiding pkg"); 9042 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9043 } 9044 } finally { 9045 Binder.restoreCallingIdentity(callingId); 9046 } 9047 return false; 9048 } 9049 9050 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9051 int userId) { 9052 final PackageRemovedInfo info = new PackageRemovedInfo(); 9053 info.removedPackage = packageName; 9054 info.removedUsers = new int[] {userId}; 9055 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9056 info.sendBroadcast(false, false, false); 9057 } 9058 9059 /** 9060 * Returns true if application is not found or there was an error. Otherwise it returns 9061 * the hidden state of the package for the given user. 9062 */ 9063 @Override 9064 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9065 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9066 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9067 false, "getApplicationHidden for user " + userId); 9068 PackageSetting pkgSetting; 9069 long callingId = Binder.clearCallingIdentity(); 9070 try { 9071 // writer 9072 synchronized (mPackages) { 9073 pkgSetting = mSettings.mPackages.get(packageName); 9074 if (pkgSetting == null) { 9075 return true; 9076 } 9077 return pkgSetting.getHidden(userId); 9078 } 9079 } finally { 9080 Binder.restoreCallingIdentity(callingId); 9081 } 9082 } 9083 9084 /** 9085 * @hide 9086 */ 9087 @Override 9088 public int installExistingPackageAsUser(String packageName, int userId) { 9089 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9090 null); 9091 PackageSetting pkgSetting; 9092 final int uid = Binder.getCallingUid(); 9093 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9094 + userId); 9095 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9096 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9097 } 9098 9099 long callingId = Binder.clearCallingIdentity(); 9100 try { 9101 boolean sendAdded = false; 9102 9103 // writer 9104 synchronized (mPackages) { 9105 pkgSetting = mSettings.mPackages.get(packageName); 9106 if (pkgSetting == null) { 9107 return PackageManager.INSTALL_FAILED_INVALID_URI; 9108 } 9109 if (!pkgSetting.getInstalled(userId)) { 9110 pkgSetting.setInstalled(true, userId); 9111 pkgSetting.setHidden(false, userId); 9112 mSettings.writePackageRestrictionsLPr(userId); 9113 sendAdded = true; 9114 } 9115 } 9116 9117 if (sendAdded) { 9118 sendPackageAddedForUser(packageName, pkgSetting, userId); 9119 } 9120 } finally { 9121 Binder.restoreCallingIdentity(callingId); 9122 } 9123 9124 return PackageManager.INSTALL_SUCCEEDED; 9125 } 9126 9127 boolean isUserRestricted(int userId, String restrictionKey) { 9128 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9129 if (restrictions.getBoolean(restrictionKey, false)) { 9130 Log.w(TAG, "User is restricted: " + restrictionKey); 9131 return true; 9132 } 9133 return false; 9134 } 9135 9136 @Override 9137 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9138 mContext.enforceCallingOrSelfPermission( 9139 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9140 "Only package verification agents can verify applications"); 9141 9142 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9143 final PackageVerificationResponse response = new PackageVerificationResponse( 9144 verificationCode, Binder.getCallingUid()); 9145 msg.arg1 = id; 9146 msg.obj = response; 9147 mHandler.sendMessage(msg); 9148 } 9149 9150 @Override 9151 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9152 long millisecondsToDelay) { 9153 mContext.enforceCallingOrSelfPermission( 9154 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9155 "Only package verification agents can extend verification timeouts"); 9156 9157 final PackageVerificationState state = mPendingVerification.get(id); 9158 final PackageVerificationResponse response = new PackageVerificationResponse( 9159 verificationCodeAtTimeout, Binder.getCallingUid()); 9160 9161 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9162 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9163 } 9164 if (millisecondsToDelay < 0) { 9165 millisecondsToDelay = 0; 9166 } 9167 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9168 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9169 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9170 } 9171 9172 if ((state != null) && !state.timeoutExtended()) { 9173 state.extendTimeout(); 9174 9175 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9176 msg.arg1 = id; 9177 msg.obj = response; 9178 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9179 } 9180 } 9181 9182 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9183 int verificationCode, UserHandle user) { 9184 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9185 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9186 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9187 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9188 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9189 9190 mContext.sendBroadcastAsUser(intent, user, 9191 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9192 } 9193 9194 private ComponentName matchComponentForVerifier(String packageName, 9195 List<ResolveInfo> receivers) { 9196 ActivityInfo targetReceiver = null; 9197 9198 final int NR = receivers.size(); 9199 for (int i = 0; i < NR; i++) { 9200 final ResolveInfo info = receivers.get(i); 9201 if (info.activityInfo == null) { 9202 continue; 9203 } 9204 9205 if (packageName.equals(info.activityInfo.packageName)) { 9206 targetReceiver = info.activityInfo; 9207 break; 9208 } 9209 } 9210 9211 if (targetReceiver == null) { 9212 return null; 9213 } 9214 9215 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9216 } 9217 9218 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9219 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9220 if (pkgInfo.verifiers.length == 0) { 9221 return null; 9222 } 9223 9224 final int N = pkgInfo.verifiers.length; 9225 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9226 for (int i = 0; i < N; i++) { 9227 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9228 9229 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9230 receivers); 9231 if (comp == null) { 9232 continue; 9233 } 9234 9235 final int verifierUid = getUidForVerifier(verifierInfo); 9236 if (verifierUid == -1) { 9237 continue; 9238 } 9239 9240 if (DEBUG_VERIFY) { 9241 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9242 + " with the correct signature"); 9243 } 9244 sufficientVerifiers.add(comp); 9245 verificationState.addSufficientVerifier(verifierUid); 9246 } 9247 9248 return sufficientVerifiers; 9249 } 9250 9251 private int getUidForVerifier(VerifierInfo verifierInfo) { 9252 synchronized (mPackages) { 9253 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9254 if (pkg == null) { 9255 return -1; 9256 } else if (pkg.mSignatures.length != 1) { 9257 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9258 + " has more than one signature; ignoring"); 9259 return -1; 9260 } 9261 9262 /* 9263 * If the public key of the package's signature does not match 9264 * our expected public key, then this is a different package and 9265 * we should skip. 9266 */ 9267 9268 final byte[] expectedPublicKey; 9269 try { 9270 final Signature verifierSig = pkg.mSignatures[0]; 9271 final PublicKey publicKey = verifierSig.getPublicKey(); 9272 expectedPublicKey = publicKey.getEncoded(); 9273 } catch (CertificateException e) { 9274 return -1; 9275 } 9276 9277 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9278 9279 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9280 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9281 + " does not have the expected public key; ignoring"); 9282 return -1; 9283 } 9284 9285 return pkg.applicationInfo.uid; 9286 } 9287 } 9288 9289 @Override 9290 public void finishPackageInstall(int token) { 9291 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9292 9293 if (DEBUG_INSTALL) { 9294 Slog.v(TAG, "BM finishing package install for " + token); 9295 } 9296 9297 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9298 mHandler.sendMessage(msg); 9299 } 9300 9301 /** 9302 * Get the verification agent timeout. 9303 * 9304 * @return verification timeout in milliseconds 9305 */ 9306 private long getVerificationTimeout() { 9307 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9308 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9309 DEFAULT_VERIFICATION_TIMEOUT); 9310 } 9311 9312 /** 9313 * Get the default verification agent response code. 9314 * 9315 * @return default verification response code 9316 */ 9317 private int getDefaultVerificationResponse() { 9318 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9319 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9320 DEFAULT_VERIFICATION_RESPONSE); 9321 } 9322 9323 /** 9324 * Check whether or not package verification has been enabled. 9325 * 9326 * @return true if verification should be performed 9327 */ 9328 private boolean isVerificationEnabled(int userId, int installFlags) { 9329 if (!DEFAULT_VERIFY_ENABLE) { 9330 return false; 9331 } 9332 9333 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9334 9335 // Check if installing from ADB 9336 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9337 // Do not run verification in a test harness environment 9338 if (ActivityManager.isRunningInTestHarness()) { 9339 return false; 9340 } 9341 if (ensureVerifyAppsEnabled) { 9342 return true; 9343 } 9344 // Check if the developer does not want package verification for ADB installs 9345 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9346 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9347 return false; 9348 } 9349 } 9350 9351 if (ensureVerifyAppsEnabled) { 9352 return true; 9353 } 9354 9355 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9356 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9357 } 9358 9359 @Override 9360 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9361 throws RemoteException { 9362 mContext.enforceCallingOrSelfPermission( 9363 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9364 "Only intentfilter verification agents can verify applications"); 9365 9366 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9367 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9368 Binder.getCallingUid(), verificationCode, failedDomains); 9369 msg.arg1 = id; 9370 msg.obj = response; 9371 mHandler.sendMessage(msg); 9372 } 9373 9374 @Override 9375 public int getIntentVerificationStatus(String packageName, int userId) { 9376 synchronized (mPackages) { 9377 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9378 } 9379 } 9380 9381 @Override 9382 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9383 boolean result = false; 9384 synchronized (mPackages) { 9385 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9386 } 9387 if (result) { 9388 scheduleWritePackageRestrictionsLocked(userId); 9389 } 9390 return result; 9391 } 9392 9393 @Override 9394 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9395 synchronized (mPackages) { 9396 return mSettings.getIntentFilterVerificationsLPr(packageName); 9397 } 9398 } 9399 9400 @Override 9401 public List<IntentFilter> getAllIntentFilters(String packageName) { 9402 if (TextUtils.isEmpty(packageName)) { 9403 return Collections.<IntentFilter>emptyList(); 9404 } 9405 synchronized (mPackages) { 9406 PackageParser.Package pkg = mPackages.get(packageName); 9407 if (pkg == null || pkg.activities == null) { 9408 return Collections.<IntentFilter>emptyList(); 9409 } 9410 final int count = pkg.activities.size(); 9411 ArrayList<IntentFilter> result = new ArrayList<>(); 9412 for (int n=0; n<count; n++) { 9413 PackageParser.Activity activity = pkg.activities.get(n); 9414 if (activity.intents != null || activity.intents.size() > 0) { 9415 result.addAll(activity.intents); 9416 } 9417 } 9418 return result; 9419 } 9420 } 9421 9422 @Override 9423 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9424 synchronized (mPackages) { 9425 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9426 if (packageName != null) { 9427 result |= updateIntentVerificationStatus(packageName, 9428 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9429 UserHandle.myUserId()); 9430 } 9431 return result; 9432 } 9433 } 9434 9435 @Override 9436 public String getDefaultBrowserPackageName(int userId) { 9437 synchronized (mPackages) { 9438 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9439 } 9440 } 9441 9442 /** 9443 * Get the "allow unknown sources" setting. 9444 * 9445 * @return the current "allow unknown sources" setting 9446 */ 9447 private int getUnknownSourcesSettings() { 9448 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9449 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9450 -1); 9451 } 9452 9453 @Override 9454 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9455 final int uid = Binder.getCallingUid(); 9456 // writer 9457 synchronized (mPackages) { 9458 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9459 if (targetPackageSetting == null) { 9460 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9461 } 9462 9463 PackageSetting installerPackageSetting; 9464 if (installerPackageName != null) { 9465 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9466 if (installerPackageSetting == null) { 9467 throw new IllegalArgumentException("Unknown installer package: " 9468 + installerPackageName); 9469 } 9470 } else { 9471 installerPackageSetting = null; 9472 } 9473 9474 Signature[] callerSignature; 9475 Object obj = mSettings.getUserIdLPr(uid); 9476 if (obj != null) { 9477 if (obj instanceof SharedUserSetting) { 9478 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9479 } else if (obj instanceof PackageSetting) { 9480 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9481 } else { 9482 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9483 } 9484 } else { 9485 throw new SecurityException("Unknown calling uid " + uid); 9486 } 9487 9488 // Verify: can't set installerPackageName to a package that is 9489 // not signed with the same cert as the caller. 9490 if (installerPackageSetting != null) { 9491 if (compareSignatures(callerSignature, 9492 installerPackageSetting.signatures.mSignatures) 9493 != PackageManager.SIGNATURE_MATCH) { 9494 throw new SecurityException( 9495 "Caller does not have same cert as new installer package " 9496 + installerPackageName); 9497 } 9498 } 9499 9500 // Verify: if target already has an installer package, it must 9501 // be signed with the same cert as the caller. 9502 if (targetPackageSetting.installerPackageName != null) { 9503 PackageSetting setting = mSettings.mPackages.get( 9504 targetPackageSetting.installerPackageName); 9505 // If the currently set package isn't valid, then it's always 9506 // okay to change it. 9507 if (setting != null) { 9508 if (compareSignatures(callerSignature, 9509 setting.signatures.mSignatures) 9510 != PackageManager.SIGNATURE_MATCH) { 9511 throw new SecurityException( 9512 "Caller does not have same cert as old installer package " 9513 + targetPackageSetting.installerPackageName); 9514 } 9515 } 9516 } 9517 9518 // Okay! 9519 targetPackageSetting.installerPackageName = installerPackageName; 9520 scheduleWriteSettingsLocked(); 9521 } 9522 } 9523 9524 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9525 // Queue up an async operation since the package installation may take a little while. 9526 mHandler.post(new Runnable() { 9527 public void run() { 9528 mHandler.removeCallbacks(this); 9529 // Result object to be returned 9530 PackageInstalledInfo res = new PackageInstalledInfo(); 9531 res.returnCode = currentStatus; 9532 res.uid = -1; 9533 res.pkg = null; 9534 res.removedInfo = new PackageRemovedInfo(); 9535 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9536 args.doPreInstall(res.returnCode); 9537 synchronized (mInstallLock) { 9538 installPackageLI(args, res); 9539 } 9540 args.doPostInstall(res.returnCode, res.uid); 9541 } 9542 9543 // A restore should be performed at this point if (a) the install 9544 // succeeded, (b) the operation is not an update, and (c) the new 9545 // package has not opted out of backup participation. 9546 final boolean update = res.removedInfo.removedPackage != null; 9547 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9548 boolean doRestore = !update 9549 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9550 9551 // Set up the post-install work request bookkeeping. This will be used 9552 // and cleaned up by the post-install event handling regardless of whether 9553 // there's a restore pass performed. Token values are >= 1. 9554 int token; 9555 if (mNextInstallToken < 0) mNextInstallToken = 1; 9556 token = mNextInstallToken++; 9557 9558 PostInstallData data = new PostInstallData(args, res); 9559 mRunningInstalls.put(token, data); 9560 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9561 9562 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9563 // Pass responsibility to the Backup Manager. It will perform a 9564 // restore if appropriate, then pass responsibility back to the 9565 // Package Manager to run the post-install observer callbacks 9566 // and broadcasts. 9567 IBackupManager bm = IBackupManager.Stub.asInterface( 9568 ServiceManager.getService(Context.BACKUP_SERVICE)); 9569 if (bm != null) { 9570 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9571 + " to BM for possible restore"); 9572 try { 9573 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9574 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9575 } else { 9576 doRestore = false; 9577 } 9578 } catch (RemoteException e) { 9579 // can't happen; the backup manager is local 9580 } catch (Exception e) { 9581 Slog.e(TAG, "Exception trying to enqueue restore", e); 9582 doRestore = false; 9583 } 9584 } else { 9585 Slog.e(TAG, "Backup Manager not found!"); 9586 doRestore = false; 9587 } 9588 } 9589 9590 if (!doRestore) { 9591 // No restore possible, or the Backup Manager was mysteriously not 9592 // available -- just fire the post-install work request directly. 9593 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9594 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9595 mHandler.sendMessage(msg); 9596 } 9597 } 9598 }); 9599 } 9600 9601 private abstract class HandlerParams { 9602 private static final int MAX_RETRIES = 4; 9603 9604 /** 9605 * Number of times startCopy() has been attempted and had a non-fatal 9606 * error. 9607 */ 9608 private int mRetries = 0; 9609 9610 /** User handle for the user requesting the information or installation. */ 9611 private final UserHandle mUser; 9612 9613 HandlerParams(UserHandle user) { 9614 mUser = user; 9615 } 9616 9617 UserHandle getUser() { 9618 return mUser; 9619 } 9620 9621 final boolean startCopy() { 9622 boolean res; 9623 try { 9624 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9625 9626 if (++mRetries > MAX_RETRIES) { 9627 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9628 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9629 handleServiceError(); 9630 return false; 9631 } else { 9632 handleStartCopy(); 9633 res = true; 9634 } 9635 } catch (RemoteException e) { 9636 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9637 mHandler.sendEmptyMessage(MCS_RECONNECT); 9638 res = false; 9639 } 9640 handleReturnCode(); 9641 return res; 9642 } 9643 9644 final void serviceError() { 9645 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9646 handleServiceError(); 9647 handleReturnCode(); 9648 } 9649 9650 abstract void handleStartCopy() throws RemoteException; 9651 abstract void handleServiceError(); 9652 abstract void handleReturnCode(); 9653 } 9654 9655 class MeasureParams extends HandlerParams { 9656 private final PackageStats mStats; 9657 private boolean mSuccess; 9658 9659 private final IPackageStatsObserver mObserver; 9660 9661 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9662 super(new UserHandle(stats.userHandle)); 9663 mObserver = observer; 9664 mStats = stats; 9665 } 9666 9667 @Override 9668 public String toString() { 9669 return "MeasureParams{" 9670 + Integer.toHexString(System.identityHashCode(this)) 9671 + " " + mStats.packageName + "}"; 9672 } 9673 9674 @Override 9675 void handleStartCopy() throws RemoteException { 9676 synchronized (mInstallLock) { 9677 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9678 } 9679 9680 if (mSuccess) { 9681 final boolean mounted; 9682 if (Environment.isExternalStorageEmulated()) { 9683 mounted = true; 9684 } else { 9685 final String status = Environment.getExternalStorageState(); 9686 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9687 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9688 } 9689 9690 if (mounted) { 9691 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9692 9693 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9694 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9695 9696 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9697 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9698 9699 // Always subtract cache size, since it's a subdirectory 9700 mStats.externalDataSize -= mStats.externalCacheSize; 9701 9702 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9703 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9704 9705 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9706 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9707 } 9708 } 9709 } 9710 9711 @Override 9712 void handleReturnCode() { 9713 if (mObserver != null) { 9714 try { 9715 mObserver.onGetStatsCompleted(mStats, mSuccess); 9716 } catch (RemoteException e) { 9717 Slog.i(TAG, "Observer no longer exists."); 9718 } 9719 } 9720 } 9721 9722 @Override 9723 void handleServiceError() { 9724 Slog.e(TAG, "Could not measure application " + mStats.packageName 9725 + " external storage"); 9726 } 9727 } 9728 9729 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9730 throws RemoteException { 9731 long result = 0; 9732 for (File path : paths) { 9733 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9734 } 9735 return result; 9736 } 9737 9738 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9739 for (File path : paths) { 9740 try { 9741 mcs.clearDirectory(path.getAbsolutePath()); 9742 } catch (RemoteException e) { 9743 } 9744 } 9745 } 9746 9747 static class OriginInfo { 9748 /** 9749 * Location where install is coming from, before it has been 9750 * copied/renamed into place. This could be a single monolithic APK 9751 * file, or a cluster directory. This location may be untrusted. 9752 */ 9753 final File file; 9754 final String cid; 9755 9756 /** 9757 * Flag indicating that {@link #file} or {@link #cid} has already been 9758 * staged, meaning downstream users don't need to defensively copy the 9759 * contents. 9760 */ 9761 final boolean staged; 9762 9763 /** 9764 * Flag indicating that {@link #file} or {@link #cid} is an already 9765 * installed app that is being moved. 9766 */ 9767 final boolean existing; 9768 9769 final String resolvedPath; 9770 final File resolvedFile; 9771 9772 static OriginInfo fromNothing() { 9773 return new OriginInfo(null, null, false, false); 9774 } 9775 9776 static OriginInfo fromUntrustedFile(File file) { 9777 return new OriginInfo(file, null, false, false); 9778 } 9779 9780 static OriginInfo fromExistingFile(File file) { 9781 return new OriginInfo(file, null, false, true); 9782 } 9783 9784 static OriginInfo fromStagedFile(File file) { 9785 return new OriginInfo(file, null, true, false); 9786 } 9787 9788 static OriginInfo fromStagedContainer(String cid) { 9789 return new OriginInfo(null, cid, true, false); 9790 } 9791 9792 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9793 this.file = file; 9794 this.cid = cid; 9795 this.staged = staged; 9796 this.existing = existing; 9797 9798 if (cid != null) { 9799 resolvedPath = PackageHelper.getSdDir(cid); 9800 resolvedFile = new File(resolvedPath); 9801 } else if (file != null) { 9802 resolvedPath = file.getAbsolutePath(); 9803 resolvedFile = file; 9804 } else { 9805 resolvedPath = null; 9806 resolvedFile = null; 9807 } 9808 } 9809 } 9810 9811 class MoveInfo { 9812 final int moveId; 9813 final String fromUuid; 9814 final String toUuid; 9815 final String packageName; 9816 final String dataAppName; 9817 final int appId; 9818 final String seinfo; 9819 9820 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9821 String dataAppName, int appId, String seinfo) { 9822 this.moveId = moveId; 9823 this.fromUuid = fromUuid; 9824 this.toUuid = toUuid; 9825 this.packageName = packageName; 9826 this.dataAppName = dataAppName; 9827 this.appId = appId; 9828 this.seinfo = seinfo; 9829 } 9830 } 9831 9832 class InstallParams extends HandlerParams { 9833 final OriginInfo origin; 9834 final MoveInfo move; 9835 final IPackageInstallObserver2 observer; 9836 int installFlags; 9837 final String installerPackageName; 9838 final String volumeUuid; 9839 final VerificationParams verificationParams; 9840 private InstallArgs mArgs; 9841 private int mRet; 9842 final String packageAbiOverride; 9843 9844 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9845 int installFlags, String installerPackageName, String volumeUuid, 9846 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9847 super(user); 9848 this.origin = origin; 9849 this.move = move; 9850 this.observer = observer; 9851 this.installFlags = installFlags; 9852 this.installerPackageName = installerPackageName; 9853 this.volumeUuid = volumeUuid; 9854 this.verificationParams = verificationParams; 9855 this.packageAbiOverride = packageAbiOverride; 9856 } 9857 9858 @Override 9859 public String toString() { 9860 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9861 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9862 } 9863 9864 public ManifestDigest getManifestDigest() { 9865 if (verificationParams == null) { 9866 return null; 9867 } 9868 return verificationParams.getManifestDigest(); 9869 } 9870 9871 private int installLocationPolicy(PackageInfoLite pkgLite) { 9872 String packageName = pkgLite.packageName; 9873 int installLocation = pkgLite.installLocation; 9874 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9875 // reader 9876 synchronized (mPackages) { 9877 PackageParser.Package pkg = mPackages.get(packageName); 9878 if (pkg != null) { 9879 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9880 // Check for downgrading. 9881 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9882 try { 9883 checkDowngrade(pkg, pkgLite); 9884 } catch (PackageManagerException e) { 9885 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9886 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9887 } 9888 } 9889 // Check for updated system application. 9890 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9891 if (onSd) { 9892 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9893 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9894 } 9895 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9896 } else { 9897 if (onSd) { 9898 // Install flag overrides everything. 9899 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9900 } 9901 // If current upgrade specifies particular preference 9902 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9903 // Application explicitly specified internal. 9904 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9905 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9906 // App explictly prefers external. Let policy decide 9907 } else { 9908 // Prefer previous location 9909 if (isExternal(pkg)) { 9910 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9911 } 9912 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9913 } 9914 } 9915 } else { 9916 // Invalid install. Return error code 9917 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9918 } 9919 } 9920 } 9921 // All the special cases have been taken care of. 9922 // Return result based on recommended install location. 9923 if (onSd) { 9924 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9925 } 9926 return pkgLite.recommendedInstallLocation; 9927 } 9928 9929 /* 9930 * Invoke remote method to get package information and install 9931 * location values. Override install location based on default 9932 * policy if needed and then create install arguments based 9933 * on the install location. 9934 */ 9935 public void handleStartCopy() throws RemoteException { 9936 int ret = PackageManager.INSTALL_SUCCEEDED; 9937 9938 // If we're already staged, we've firmly committed to an install location 9939 if (origin.staged) { 9940 if (origin.file != null) { 9941 installFlags |= PackageManager.INSTALL_INTERNAL; 9942 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9943 } else if (origin.cid != null) { 9944 installFlags |= PackageManager.INSTALL_EXTERNAL; 9945 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9946 } else { 9947 throw new IllegalStateException("Invalid stage location"); 9948 } 9949 } 9950 9951 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9952 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9953 9954 PackageInfoLite pkgLite = null; 9955 9956 if (onInt && onSd) { 9957 // Check if both bits are set. 9958 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9959 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9960 } else { 9961 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9962 packageAbiOverride); 9963 9964 /* 9965 * If we have too little free space, try to free cache 9966 * before giving up. 9967 */ 9968 if (!origin.staged && pkgLite.recommendedInstallLocation 9969 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9970 // TODO: focus freeing disk space on the target device 9971 final StorageManager storage = StorageManager.from(mContext); 9972 final long lowThreshold = storage.getStorageLowBytes( 9973 Environment.getDataDirectory()); 9974 9975 final long sizeBytes = mContainerService.calculateInstalledSize( 9976 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9977 9978 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9979 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9980 installFlags, packageAbiOverride); 9981 } 9982 9983 /* 9984 * The cache free must have deleted the file we 9985 * downloaded to install. 9986 * 9987 * TODO: fix the "freeCache" call to not delete 9988 * the file we care about. 9989 */ 9990 if (pkgLite.recommendedInstallLocation 9991 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9992 pkgLite.recommendedInstallLocation 9993 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9994 } 9995 } 9996 } 9997 9998 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9999 int loc = pkgLite.recommendedInstallLocation; 10000 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10001 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10002 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10003 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10004 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10005 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10006 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10007 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10008 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10009 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10010 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10011 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10012 } else { 10013 // Override with defaults if needed. 10014 loc = installLocationPolicy(pkgLite); 10015 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10016 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10017 } else if (!onSd && !onInt) { 10018 // Override install location with flags 10019 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10020 // Set the flag to install on external media. 10021 installFlags |= PackageManager.INSTALL_EXTERNAL; 10022 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10023 } else { 10024 // Make sure the flag for installing on external 10025 // media is unset 10026 installFlags |= PackageManager.INSTALL_INTERNAL; 10027 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10028 } 10029 } 10030 } 10031 } 10032 10033 final InstallArgs args = createInstallArgs(this); 10034 mArgs = args; 10035 10036 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10037 /* 10038 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10039 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10040 */ 10041 int userIdentifier = getUser().getIdentifier(); 10042 if (userIdentifier == UserHandle.USER_ALL 10043 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10044 userIdentifier = UserHandle.USER_OWNER; 10045 } 10046 10047 /* 10048 * Determine if we have any installed package verifiers. If we 10049 * do, then we'll defer to them to verify the packages. 10050 */ 10051 final int requiredUid = mRequiredVerifierPackage == null ? -1 10052 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10053 if (!origin.existing && requiredUid != -1 10054 && isVerificationEnabled(userIdentifier, installFlags)) { 10055 final Intent verification = new Intent( 10056 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10057 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10058 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10059 PACKAGE_MIME_TYPE); 10060 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10061 10062 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10063 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10064 0 /* TODO: Which userId? */); 10065 10066 if (DEBUG_VERIFY) { 10067 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10068 + verification.toString() + " with " + pkgLite.verifiers.length 10069 + " optional verifiers"); 10070 } 10071 10072 final int verificationId = mPendingVerificationToken++; 10073 10074 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10075 10076 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10077 installerPackageName); 10078 10079 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10080 installFlags); 10081 10082 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10083 pkgLite.packageName); 10084 10085 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10086 pkgLite.versionCode); 10087 10088 if (verificationParams != null) { 10089 if (verificationParams.getVerificationURI() != null) { 10090 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10091 verificationParams.getVerificationURI()); 10092 } 10093 if (verificationParams.getOriginatingURI() != null) { 10094 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10095 verificationParams.getOriginatingURI()); 10096 } 10097 if (verificationParams.getReferrer() != null) { 10098 verification.putExtra(Intent.EXTRA_REFERRER, 10099 verificationParams.getReferrer()); 10100 } 10101 if (verificationParams.getOriginatingUid() >= 0) { 10102 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10103 verificationParams.getOriginatingUid()); 10104 } 10105 if (verificationParams.getInstallerUid() >= 0) { 10106 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10107 verificationParams.getInstallerUid()); 10108 } 10109 } 10110 10111 final PackageVerificationState verificationState = new PackageVerificationState( 10112 requiredUid, args); 10113 10114 mPendingVerification.append(verificationId, verificationState); 10115 10116 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10117 receivers, verificationState); 10118 10119 /* 10120 * If any sufficient verifiers were listed in the package 10121 * manifest, attempt to ask them. 10122 */ 10123 if (sufficientVerifiers != null) { 10124 final int N = sufficientVerifiers.size(); 10125 if (N == 0) { 10126 Slog.i(TAG, "Additional verifiers required, but none installed."); 10127 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10128 } else { 10129 for (int i = 0; i < N; i++) { 10130 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10131 10132 final Intent sufficientIntent = new Intent(verification); 10133 sufficientIntent.setComponent(verifierComponent); 10134 10135 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10136 } 10137 } 10138 } 10139 10140 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10141 mRequiredVerifierPackage, receivers); 10142 if (ret == PackageManager.INSTALL_SUCCEEDED 10143 && mRequiredVerifierPackage != null) { 10144 /* 10145 * Send the intent to the required verification agent, 10146 * but only start the verification timeout after the 10147 * target BroadcastReceivers have run. 10148 */ 10149 verification.setComponent(requiredVerifierComponent); 10150 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10151 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10152 new BroadcastReceiver() { 10153 @Override 10154 public void onReceive(Context context, Intent intent) { 10155 final Message msg = mHandler 10156 .obtainMessage(CHECK_PENDING_VERIFICATION); 10157 msg.arg1 = verificationId; 10158 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10159 } 10160 }, null, 0, null, null); 10161 10162 /* 10163 * We don't want the copy to proceed until verification 10164 * succeeds, so null out this field. 10165 */ 10166 mArgs = null; 10167 } 10168 } else { 10169 /* 10170 * No package verification is enabled, so immediately start 10171 * the remote call to initiate copy using temporary file. 10172 */ 10173 ret = args.copyApk(mContainerService, true); 10174 } 10175 } 10176 10177 mRet = ret; 10178 } 10179 10180 @Override 10181 void handleReturnCode() { 10182 // If mArgs is null, then MCS couldn't be reached. When it 10183 // reconnects, it will try again to install. At that point, this 10184 // will succeed. 10185 if (mArgs != null) { 10186 processPendingInstall(mArgs, mRet); 10187 } 10188 } 10189 10190 @Override 10191 void handleServiceError() { 10192 mArgs = createInstallArgs(this); 10193 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10194 } 10195 10196 public boolean isForwardLocked() { 10197 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10198 } 10199 } 10200 10201 /** 10202 * Used during creation of InstallArgs 10203 * 10204 * @param installFlags package installation flags 10205 * @return true if should be installed on external storage 10206 */ 10207 private static boolean installOnExternalAsec(int installFlags) { 10208 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10209 return false; 10210 } 10211 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10212 return true; 10213 } 10214 return false; 10215 } 10216 10217 /** 10218 * Used during creation of InstallArgs 10219 * 10220 * @param installFlags package installation flags 10221 * @return true if should be installed as forward locked 10222 */ 10223 private static boolean installForwardLocked(int installFlags) { 10224 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10225 } 10226 10227 private InstallArgs createInstallArgs(InstallParams params) { 10228 if (params.move != null) { 10229 return new MoveInstallArgs(params); 10230 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10231 return new AsecInstallArgs(params); 10232 } else { 10233 return new FileInstallArgs(params); 10234 } 10235 } 10236 10237 /** 10238 * Create args that describe an existing installed package. Typically used 10239 * when cleaning up old installs, or used as a move source. 10240 */ 10241 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10242 String resourcePath, String[] instructionSets) { 10243 final boolean isInAsec; 10244 if (installOnExternalAsec(installFlags)) { 10245 /* Apps on SD card are always in ASEC containers. */ 10246 isInAsec = true; 10247 } else if (installForwardLocked(installFlags) 10248 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10249 /* 10250 * Forward-locked apps are only in ASEC containers if they're the 10251 * new style 10252 */ 10253 isInAsec = true; 10254 } else { 10255 isInAsec = false; 10256 } 10257 10258 if (isInAsec) { 10259 return new AsecInstallArgs(codePath, instructionSets, 10260 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10261 } else { 10262 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10263 } 10264 } 10265 10266 static abstract class InstallArgs { 10267 /** @see InstallParams#origin */ 10268 final OriginInfo origin; 10269 /** @see InstallParams#move */ 10270 final MoveInfo move; 10271 10272 final IPackageInstallObserver2 observer; 10273 // Always refers to PackageManager flags only 10274 final int installFlags; 10275 final String installerPackageName; 10276 final String volumeUuid; 10277 final ManifestDigest manifestDigest; 10278 final UserHandle user; 10279 final String abiOverride; 10280 10281 // The list of instruction sets supported by this app. This is currently 10282 // only used during the rmdex() phase to clean up resources. We can get rid of this 10283 // if we move dex files under the common app path. 10284 /* nullable */ String[] instructionSets; 10285 10286 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10287 int installFlags, String installerPackageName, String volumeUuid, 10288 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10289 String abiOverride) { 10290 this.origin = origin; 10291 this.move = move; 10292 this.installFlags = installFlags; 10293 this.observer = observer; 10294 this.installerPackageName = installerPackageName; 10295 this.volumeUuid = volumeUuid; 10296 this.manifestDigest = manifestDigest; 10297 this.user = user; 10298 this.instructionSets = instructionSets; 10299 this.abiOverride = abiOverride; 10300 } 10301 10302 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10303 abstract int doPreInstall(int status); 10304 10305 /** 10306 * Rename package into final resting place. All paths on the given 10307 * scanned package should be updated to reflect the rename. 10308 */ 10309 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10310 abstract int doPostInstall(int status, int uid); 10311 10312 /** @see PackageSettingBase#codePathString */ 10313 abstract String getCodePath(); 10314 /** @see PackageSettingBase#resourcePathString */ 10315 abstract String getResourcePath(); 10316 10317 // Need installer lock especially for dex file removal. 10318 abstract void cleanUpResourcesLI(); 10319 abstract boolean doPostDeleteLI(boolean delete); 10320 10321 /** 10322 * Called before the source arguments are copied. This is used mostly 10323 * for MoveParams when it needs to read the source file to put it in the 10324 * destination. 10325 */ 10326 int doPreCopy() { 10327 return PackageManager.INSTALL_SUCCEEDED; 10328 } 10329 10330 /** 10331 * Called after the source arguments are copied. This is used mostly for 10332 * MoveParams when it needs to read the source file to put it in the 10333 * destination. 10334 * 10335 * @return 10336 */ 10337 int doPostCopy(int uid) { 10338 return PackageManager.INSTALL_SUCCEEDED; 10339 } 10340 10341 protected boolean isFwdLocked() { 10342 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10343 } 10344 10345 protected boolean isExternalAsec() { 10346 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10347 } 10348 10349 UserHandle getUser() { 10350 return user; 10351 } 10352 } 10353 10354 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10355 if (!allCodePaths.isEmpty()) { 10356 if (instructionSets == null) { 10357 throw new IllegalStateException("instructionSet == null"); 10358 } 10359 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10360 for (String codePath : allCodePaths) { 10361 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10362 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10363 if (retCode < 0) { 10364 Slog.w(TAG, "Couldn't remove dex file for package: " 10365 + " at location " + codePath + ", retcode=" + retCode); 10366 // we don't consider this to be a failure of the core package deletion 10367 } 10368 } 10369 } 10370 } 10371 } 10372 10373 /** 10374 * Logic to handle installation of non-ASEC applications, including copying 10375 * and renaming logic. 10376 */ 10377 class FileInstallArgs extends InstallArgs { 10378 private File codeFile; 10379 private File resourceFile; 10380 10381 // Example topology: 10382 // /data/app/com.example/base.apk 10383 // /data/app/com.example/split_foo.apk 10384 // /data/app/com.example/lib/arm/libfoo.so 10385 // /data/app/com.example/lib/arm64/libfoo.so 10386 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10387 10388 /** New install */ 10389 FileInstallArgs(InstallParams params) { 10390 super(params.origin, params.move, params.observer, params.installFlags, 10391 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10392 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10393 if (isFwdLocked()) { 10394 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10395 } 10396 } 10397 10398 /** Existing install */ 10399 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10400 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10401 null); 10402 this.codeFile = (codePath != null) ? new File(codePath) : null; 10403 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10404 } 10405 10406 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10407 if (origin.staged) { 10408 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10409 codeFile = origin.file; 10410 resourceFile = origin.file; 10411 return PackageManager.INSTALL_SUCCEEDED; 10412 } 10413 10414 try { 10415 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10416 codeFile = tempDir; 10417 resourceFile = tempDir; 10418 } catch (IOException e) { 10419 Slog.w(TAG, "Failed to create copy file: " + e); 10420 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10421 } 10422 10423 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10424 @Override 10425 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10426 if (!FileUtils.isValidExtFilename(name)) { 10427 throw new IllegalArgumentException("Invalid filename: " + name); 10428 } 10429 try { 10430 final File file = new File(codeFile, name); 10431 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10432 O_RDWR | O_CREAT, 0644); 10433 Os.chmod(file.getAbsolutePath(), 0644); 10434 return new ParcelFileDescriptor(fd); 10435 } catch (ErrnoException e) { 10436 throw new RemoteException("Failed to open: " + e.getMessage()); 10437 } 10438 } 10439 }; 10440 10441 int ret = PackageManager.INSTALL_SUCCEEDED; 10442 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10443 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10444 Slog.e(TAG, "Failed to copy package"); 10445 return ret; 10446 } 10447 10448 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10449 NativeLibraryHelper.Handle handle = null; 10450 try { 10451 handle = NativeLibraryHelper.Handle.create(codeFile); 10452 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10453 abiOverride); 10454 } catch (IOException e) { 10455 Slog.e(TAG, "Copying native libraries failed", e); 10456 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10457 } finally { 10458 IoUtils.closeQuietly(handle); 10459 } 10460 10461 return ret; 10462 } 10463 10464 int doPreInstall(int status) { 10465 if (status != PackageManager.INSTALL_SUCCEEDED) { 10466 cleanUp(); 10467 } 10468 return status; 10469 } 10470 10471 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10472 if (status != PackageManager.INSTALL_SUCCEEDED) { 10473 cleanUp(); 10474 return false; 10475 } 10476 10477 final File targetDir = codeFile.getParentFile(); 10478 final File beforeCodeFile = codeFile; 10479 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10480 10481 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10482 try { 10483 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10484 } catch (ErrnoException e) { 10485 Slog.w(TAG, "Failed to rename", e); 10486 return false; 10487 } 10488 10489 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10490 Slog.w(TAG, "Failed to restorecon"); 10491 return false; 10492 } 10493 10494 // Reflect the rename internally 10495 codeFile = afterCodeFile; 10496 resourceFile = afterCodeFile; 10497 10498 // Reflect the rename in scanned details 10499 pkg.codePath = afterCodeFile.getAbsolutePath(); 10500 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10501 pkg.baseCodePath); 10502 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10503 pkg.splitCodePaths); 10504 10505 // Reflect the rename in app info 10506 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10507 pkg.applicationInfo.setCodePath(pkg.codePath); 10508 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10509 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10510 pkg.applicationInfo.setResourcePath(pkg.codePath); 10511 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10512 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10513 10514 return true; 10515 } 10516 10517 int doPostInstall(int status, int uid) { 10518 if (status != PackageManager.INSTALL_SUCCEEDED) { 10519 cleanUp(); 10520 } 10521 return status; 10522 } 10523 10524 @Override 10525 String getCodePath() { 10526 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10527 } 10528 10529 @Override 10530 String getResourcePath() { 10531 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10532 } 10533 10534 private boolean cleanUp() { 10535 if (codeFile == null || !codeFile.exists()) { 10536 return false; 10537 } 10538 10539 if (codeFile.isDirectory()) { 10540 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10541 } else { 10542 codeFile.delete(); 10543 } 10544 10545 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10546 resourceFile.delete(); 10547 } 10548 10549 return true; 10550 } 10551 10552 void cleanUpResourcesLI() { 10553 // Try enumerating all code paths before deleting 10554 List<String> allCodePaths = Collections.EMPTY_LIST; 10555 if (codeFile != null && codeFile.exists()) { 10556 try { 10557 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10558 allCodePaths = pkg.getAllCodePaths(); 10559 } catch (PackageParserException e) { 10560 // Ignored; we tried our best 10561 } 10562 } 10563 10564 cleanUp(); 10565 removeDexFiles(allCodePaths, instructionSets); 10566 } 10567 10568 boolean doPostDeleteLI(boolean delete) { 10569 // XXX err, shouldn't we respect the delete flag? 10570 cleanUpResourcesLI(); 10571 return true; 10572 } 10573 } 10574 10575 private boolean isAsecExternal(String cid) { 10576 final String asecPath = PackageHelper.getSdFilesystem(cid); 10577 return !asecPath.startsWith(mAsecInternalPath); 10578 } 10579 10580 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10581 PackageManagerException { 10582 if (copyRet < 0) { 10583 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10584 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10585 throw new PackageManagerException(copyRet, message); 10586 } 10587 } 10588 } 10589 10590 /** 10591 * Extract the MountService "container ID" from the full code path of an 10592 * .apk. 10593 */ 10594 static String cidFromCodePath(String fullCodePath) { 10595 int eidx = fullCodePath.lastIndexOf("/"); 10596 String subStr1 = fullCodePath.substring(0, eidx); 10597 int sidx = subStr1.lastIndexOf("/"); 10598 return subStr1.substring(sidx+1, eidx); 10599 } 10600 10601 /** 10602 * Logic to handle installation of ASEC applications, including copying and 10603 * renaming logic. 10604 */ 10605 class AsecInstallArgs extends InstallArgs { 10606 static final String RES_FILE_NAME = "pkg.apk"; 10607 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10608 10609 String cid; 10610 String packagePath; 10611 String resourcePath; 10612 10613 /** New install */ 10614 AsecInstallArgs(InstallParams params) { 10615 super(params.origin, params.move, params.observer, params.installFlags, 10616 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10617 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10618 } 10619 10620 /** Existing install */ 10621 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10622 boolean isExternal, boolean isForwardLocked) { 10623 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10624 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10625 instructionSets, null); 10626 // Hackily pretend we're still looking at a full code path 10627 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10628 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10629 } 10630 10631 // Extract cid from fullCodePath 10632 int eidx = fullCodePath.lastIndexOf("/"); 10633 String subStr1 = fullCodePath.substring(0, eidx); 10634 int sidx = subStr1.lastIndexOf("/"); 10635 cid = subStr1.substring(sidx+1, eidx); 10636 setMountPath(subStr1); 10637 } 10638 10639 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10640 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10641 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10642 instructionSets, null); 10643 this.cid = cid; 10644 setMountPath(PackageHelper.getSdDir(cid)); 10645 } 10646 10647 void createCopyFile() { 10648 cid = mInstallerService.allocateExternalStageCidLegacy(); 10649 } 10650 10651 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10652 if (origin.staged) { 10653 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10654 cid = origin.cid; 10655 setMountPath(PackageHelper.getSdDir(cid)); 10656 return PackageManager.INSTALL_SUCCEEDED; 10657 } 10658 10659 if (temp) { 10660 createCopyFile(); 10661 } else { 10662 /* 10663 * Pre-emptively destroy the container since it's destroyed if 10664 * copying fails due to it existing anyway. 10665 */ 10666 PackageHelper.destroySdDir(cid); 10667 } 10668 10669 final String newMountPath = imcs.copyPackageToContainer( 10670 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10671 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10672 10673 if (newMountPath != null) { 10674 setMountPath(newMountPath); 10675 return PackageManager.INSTALL_SUCCEEDED; 10676 } else { 10677 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10678 } 10679 } 10680 10681 @Override 10682 String getCodePath() { 10683 return packagePath; 10684 } 10685 10686 @Override 10687 String getResourcePath() { 10688 return resourcePath; 10689 } 10690 10691 int doPreInstall(int status) { 10692 if (status != PackageManager.INSTALL_SUCCEEDED) { 10693 // Destroy container 10694 PackageHelper.destroySdDir(cid); 10695 } else { 10696 boolean mounted = PackageHelper.isContainerMounted(cid); 10697 if (!mounted) { 10698 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10699 Process.SYSTEM_UID); 10700 if (newMountPath != null) { 10701 setMountPath(newMountPath); 10702 } else { 10703 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10704 } 10705 } 10706 } 10707 return status; 10708 } 10709 10710 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10711 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10712 String newMountPath = null; 10713 if (PackageHelper.isContainerMounted(cid)) { 10714 // Unmount the container 10715 if (!PackageHelper.unMountSdDir(cid)) { 10716 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10717 return false; 10718 } 10719 } 10720 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10721 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10722 " which might be stale. Will try to clean up."); 10723 // Clean up the stale container and proceed to recreate. 10724 if (!PackageHelper.destroySdDir(newCacheId)) { 10725 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10726 return false; 10727 } 10728 // Successfully cleaned up stale container. Try to rename again. 10729 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10730 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10731 + " inspite of cleaning it up."); 10732 return false; 10733 } 10734 } 10735 if (!PackageHelper.isContainerMounted(newCacheId)) { 10736 Slog.w(TAG, "Mounting container " + newCacheId); 10737 newMountPath = PackageHelper.mountSdDir(newCacheId, 10738 getEncryptKey(), Process.SYSTEM_UID); 10739 } else { 10740 newMountPath = PackageHelper.getSdDir(newCacheId); 10741 } 10742 if (newMountPath == null) { 10743 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10744 return false; 10745 } 10746 Log.i(TAG, "Succesfully renamed " + cid + 10747 " to " + newCacheId + 10748 " at new path: " + newMountPath); 10749 cid = newCacheId; 10750 10751 final File beforeCodeFile = new File(packagePath); 10752 setMountPath(newMountPath); 10753 final File afterCodeFile = new File(packagePath); 10754 10755 // Reflect the rename in scanned details 10756 pkg.codePath = afterCodeFile.getAbsolutePath(); 10757 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10758 pkg.baseCodePath); 10759 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10760 pkg.splitCodePaths); 10761 10762 // Reflect the rename in app info 10763 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10764 pkg.applicationInfo.setCodePath(pkg.codePath); 10765 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10766 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10767 pkg.applicationInfo.setResourcePath(pkg.codePath); 10768 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10769 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10770 10771 return true; 10772 } 10773 10774 private void setMountPath(String mountPath) { 10775 final File mountFile = new File(mountPath); 10776 10777 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10778 if (monolithicFile.exists()) { 10779 packagePath = monolithicFile.getAbsolutePath(); 10780 if (isFwdLocked()) { 10781 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10782 } else { 10783 resourcePath = packagePath; 10784 } 10785 } else { 10786 packagePath = mountFile.getAbsolutePath(); 10787 resourcePath = packagePath; 10788 } 10789 } 10790 10791 int doPostInstall(int status, int uid) { 10792 if (status != PackageManager.INSTALL_SUCCEEDED) { 10793 cleanUp(); 10794 } else { 10795 final int groupOwner; 10796 final String protectedFile; 10797 if (isFwdLocked()) { 10798 groupOwner = UserHandle.getSharedAppGid(uid); 10799 protectedFile = RES_FILE_NAME; 10800 } else { 10801 groupOwner = -1; 10802 protectedFile = null; 10803 } 10804 10805 if (uid < Process.FIRST_APPLICATION_UID 10806 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10807 Slog.e(TAG, "Failed to finalize " + cid); 10808 PackageHelper.destroySdDir(cid); 10809 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10810 } 10811 10812 boolean mounted = PackageHelper.isContainerMounted(cid); 10813 if (!mounted) { 10814 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10815 } 10816 } 10817 return status; 10818 } 10819 10820 private void cleanUp() { 10821 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10822 10823 // Destroy secure container 10824 PackageHelper.destroySdDir(cid); 10825 } 10826 10827 private List<String> getAllCodePaths() { 10828 final File codeFile = new File(getCodePath()); 10829 if (codeFile != null && codeFile.exists()) { 10830 try { 10831 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10832 return pkg.getAllCodePaths(); 10833 } catch (PackageParserException e) { 10834 // Ignored; we tried our best 10835 } 10836 } 10837 return Collections.EMPTY_LIST; 10838 } 10839 10840 void cleanUpResourcesLI() { 10841 // Enumerate all code paths before deleting 10842 cleanUpResourcesLI(getAllCodePaths()); 10843 } 10844 10845 private void cleanUpResourcesLI(List<String> allCodePaths) { 10846 cleanUp(); 10847 removeDexFiles(allCodePaths, instructionSets); 10848 } 10849 10850 String getPackageName() { 10851 return getAsecPackageName(cid); 10852 } 10853 10854 boolean doPostDeleteLI(boolean delete) { 10855 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10856 final List<String> allCodePaths = getAllCodePaths(); 10857 boolean mounted = PackageHelper.isContainerMounted(cid); 10858 if (mounted) { 10859 // Unmount first 10860 if (PackageHelper.unMountSdDir(cid)) { 10861 mounted = false; 10862 } 10863 } 10864 if (!mounted && delete) { 10865 cleanUpResourcesLI(allCodePaths); 10866 } 10867 return !mounted; 10868 } 10869 10870 @Override 10871 int doPreCopy() { 10872 if (isFwdLocked()) { 10873 if (!PackageHelper.fixSdPermissions(cid, 10874 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10875 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10876 } 10877 } 10878 10879 return PackageManager.INSTALL_SUCCEEDED; 10880 } 10881 10882 @Override 10883 int doPostCopy(int uid) { 10884 if (isFwdLocked()) { 10885 if (uid < Process.FIRST_APPLICATION_UID 10886 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10887 RES_FILE_NAME)) { 10888 Slog.e(TAG, "Failed to finalize " + cid); 10889 PackageHelper.destroySdDir(cid); 10890 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10891 } 10892 } 10893 10894 return PackageManager.INSTALL_SUCCEEDED; 10895 } 10896 } 10897 10898 /** 10899 * Logic to handle movement of existing installed applications. 10900 */ 10901 class MoveInstallArgs extends InstallArgs { 10902 private File codeFile; 10903 private File resourceFile; 10904 10905 /** New install */ 10906 MoveInstallArgs(InstallParams params) { 10907 super(params.origin, params.move, params.observer, params.installFlags, 10908 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10909 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10910 } 10911 10912 int copyApk(IMediaContainerService imcs, boolean temp) { 10913 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10914 + move.fromUuid + " to " + move.toUuid); 10915 synchronized (mInstaller) { 10916 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10917 move.dataAppName, move.appId, move.seinfo) != 0) { 10918 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10919 } 10920 } 10921 10922 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10923 resourceFile = codeFile; 10924 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10925 10926 return PackageManager.INSTALL_SUCCEEDED; 10927 } 10928 10929 int doPreInstall(int status) { 10930 if (status != PackageManager.INSTALL_SUCCEEDED) { 10931 cleanUp(); 10932 } 10933 return status; 10934 } 10935 10936 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10937 if (status != PackageManager.INSTALL_SUCCEEDED) { 10938 cleanUp(); 10939 return false; 10940 } 10941 10942 // Reflect the move in app info 10943 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10944 pkg.applicationInfo.setCodePath(pkg.codePath); 10945 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10946 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10947 pkg.applicationInfo.setResourcePath(pkg.codePath); 10948 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10949 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10950 10951 return true; 10952 } 10953 10954 int doPostInstall(int status, int uid) { 10955 if (status != PackageManager.INSTALL_SUCCEEDED) { 10956 cleanUp(); 10957 } 10958 return status; 10959 } 10960 10961 @Override 10962 String getCodePath() { 10963 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10964 } 10965 10966 @Override 10967 String getResourcePath() { 10968 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10969 } 10970 10971 private boolean cleanUp() { 10972 if (codeFile == null || !codeFile.exists()) { 10973 return false; 10974 } 10975 10976 if (codeFile.isDirectory()) { 10977 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10978 } else { 10979 codeFile.delete(); 10980 } 10981 10982 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10983 resourceFile.delete(); 10984 } 10985 10986 return true; 10987 } 10988 10989 void cleanUpResourcesLI() { 10990 cleanUp(); 10991 } 10992 10993 boolean doPostDeleteLI(boolean delete) { 10994 // XXX err, shouldn't we respect the delete flag? 10995 cleanUpResourcesLI(); 10996 return true; 10997 } 10998 } 10999 11000 static String getAsecPackageName(String packageCid) { 11001 int idx = packageCid.lastIndexOf("-"); 11002 if (idx == -1) { 11003 return packageCid; 11004 } 11005 return packageCid.substring(0, idx); 11006 } 11007 11008 // Utility method used to create code paths based on package name and available index. 11009 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11010 String idxStr = ""; 11011 int idx = 1; 11012 // Fall back to default value of idx=1 if prefix is not 11013 // part of oldCodePath 11014 if (oldCodePath != null) { 11015 String subStr = oldCodePath; 11016 // Drop the suffix right away 11017 if (suffix != null && subStr.endsWith(suffix)) { 11018 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11019 } 11020 // If oldCodePath already contains prefix find out the 11021 // ending index to either increment or decrement. 11022 int sidx = subStr.lastIndexOf(prefix); 11023 if (sidx != -1) { 11024 subStr = subStr.substring(sidx + prefix.length()); 11025 if (subStr != null) { 11026 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11027 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11028 } 11029 try { 11030 idx = Integer.parseInt(subStr); 11031 if (idx <= 1) { 11032 idx++; 11033 } else { 11034 idx--; 11035 } 11036 } catch(NumberFormatException e) { 11037 } 11038 } 11039 } 11040 } 11041 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11042 return prefix + idxStr; 11043 } 11044 11045 private File getNextCodePath(File targetDir, String packageName) { 11046 int suffix = 1; 11047 File result; 11048 do { 11049 result = new File(targetDir, packageName + "-" + suffix); 11050 suffix++; 11051 } while (result.exists()); 11052 return result; 11053 } 11054 11055 // Utility method that returns the relative package path with respect 11056 // to the installation directory. Like say for /data/data/com.test-1.apk 11057 // string com.test-1 is returned. 11058 static String deriveCodePathName(String codePath) { 11059 if (codePath == null) { 11060 return null; 11061 } 11062 final File codeFile = new File(codePath); 11063 final String name = codeFile.getName(); 11064 if (codeFile.isDirectory()) { 11065 return name; 11066 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11067 final int lastDot = name.lastIndexOf('.'); 11068 return name.substring(0, lastDot); 11069 } else { 11070 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11071 return null; 11072 } 11073 } 11074 11075 class PackageInstalledInfo { 11076 String name; 11077 int uid; 11078 // The set of users that originally had this package installed. 11079 int[] origUsers; 11080 // The set of users that now have this package installed. 11081 int[] newUsers; 11082 PackageParser.Package pkg; 11083 int returnCode; 11084 String returnMsg; 11085 PackageRemovedInfo removedInfo; 11086 11087 public void setError(int code, String msg) { 11088 returnCode = code; 11089 returnMsg = msg; 11090 Slog.w(TAG, msg); 11091 } 11092 11093 public void setError(String msg, PackageParserException e) { 11094 returnCode = e.error; 11095 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11096 Slog.w(TAG, msg, e); 11097 } 11098 11099 public void setError(String msg, PackageManagerException e) { 11100 returnCode = e.error; 11101 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11102 Slog.w(TAG, msg, e); 11103 } 11104 11105 // In some error cases we want to convey more info back to the observer 11106 String origPackage; 11107 String origPermission; 11108 } 11109 11110 /* 11111 * Install a non-existing package. 11112 */ 11113 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11114 UserHandle user, String installerPackageName, String volumeUuid, 11115 PackageInstalledInfo res) { 11116 // Remember this for later, in case we need to rollback this install 11117 String pkgName = pkg.packageName; 11118 11119 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11120 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11121 UserHandle.USER_OWNER).exists(); 11122 synchronized(mPackages) { 11123 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11124 // A package with the same name is already installed, though 11125 // it has been renamed to an older name. The package we 11126 // are trying to install should be installed as an update to 11127 // the existing one, but that has not been requested, so bail. 11128 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11129 + " without first uninstalling package running as " 11130 + mSettings.mRenamedPackages.get(pkgName)); 11131 return; 11132 } 11133 if (mPackages.containsKey(pkgName)) { 11134 // Don't allow installation over an existing package with the same name. 11135 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11136 + " without first uninstalling."); 11137 return; 11138 } 11139 } 11140 11141 try { 11142 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11143 System.currentTimeMillis(), user); 11144 11145 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11146 // delete the partially installed application. the data directory will have to be 11147 // restored if it was already existing 11148 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11149 // remove package from internal structures. Note that we want deletePackageX to 11150 // delete the package data and cache directories that it created in 11151 // scanPackageLocked, unless those directories existed before we even tried to 11152 // install. 11153 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11154 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11155 res.removedInfo, true); 11156 } 11157 11158 } catch (PackageManagerException e) { 11159 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11160 } 11161 } 11162 11163 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11164 // Can't rotate keys during boot or if sharedUser. 11165 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11166 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11167 return false; 11168 } 11169 // app is using upgradeKeySets; make sure all are valid 11170 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11171 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11172 for (int i = 0; i < upgradeKeySets.length; i++) { 11173 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11174 Slog.wtf(TAG, "Package " 11175 + (oldPs.name != null ? oldPs.name : "<null>") 11176 + " contains upgrade-key-set reference to unknown key-set: " 11177 + upgradeKeySets[i] 11178 + " reverting to signatures check."); 11179 return false; 11180 } 11181 } 11182 return true; 11183 } 11184 11185 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11186 // Upgrade keysets are being used. Determine if new package has a superset of the 11187 // required keys. 11188 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11189 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11190 for (int i = 0; i < upgradeKeySets.length; i++) { 11191 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11192 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11193 return true; 11194 } 11195 } 11196 return false; 11197 } 11198 11199 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11200 UserHandle user, String installerPackageName, String volumeUuid, 11201 PackageInstalledInfo res) { 11202 final PackageParser.Package oldPackage; 11203 final String pkgName = pkg.packageName; 11204 final int[] allUsers; 11205 final boolean[] perUserInstalled; 11206 final boolean weFroze; 11207 11208 // First find the old package info and check signatures 11209 synchronized(mPackages) { 11210 oldPackage = mPackages.get(pkgName); 11211 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11212 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11213 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11214 if(!checkUpgradeKeySetLP(ps, pkg)) { 11215 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11216 "New package not signed by keys specified by upgrade-keysets: " 11217 + pkgName); 11218 return; 11219 } 11220 } else { 11221 // default to original signature matching 11222 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11223 != PackageManager.SIGNATURE_MATCH) { 11224 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11225 "New package has a different signature: " + pkgName); 11226 return; 11227 } 11228 } 11229 11230 // In case of rollback, remember per-user/profile install state 11231 allUsers = sUserManager.getUserIds(); 11232 perUserInstalled = new boolean[allUsers.length]; 11233 for (int i = 0; i < allUsers.length; i++) { 11234 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11235 } 11236 11237 // Mark the app as frozen to prevent launching during the upgrade 11238 // process, and then kill all running instances 11239 if (!ps.frozen) { 11240 ps.frozen = true; 11241 weFroze = true; 11242 } else { 11243 weFroze = false; 11244 } 11245 } 11246 11247 // Now that we're guarded by frozen state, kill app during upgrade 11248 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11249 11250 try { 11251 boolean sysPkg = (isSystemApp(oldPackage)); 11252 if (sysPkg) { 11253 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11254 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11255 } else { 11256 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11257 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11258 } 11259 } finally { 11260 // Regardless of success or failure of upgrade steps above, always 11261 // unfreeze the package if we froze it 11262 if (weFroze) { 11263 unfreezePackage(pkgName); 11264 } 11265 } 11266 } 11267 11268 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11269 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11270 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11271 String volumeUuid, PackageInstalledInfo res) { 11272 String pkgName = deletedPackage.packageName; 11273 boolean deletedPkg = true; 11274 boolean updatedSettings = false; 11275 11276 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11277 + deletedPackage); 11278 long origUpdateTime; 11279 if (pkg.mExtras != null) { 11280 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11281 } else { 11282 origUpdateTime = 0; 11283 } 11284 11285 // First delete the existing package while retaining the data directory 11286 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11287 res.removedInfo, true)) { 11288 // If the existing package wasn't successfully deleted 11289 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11290 deletedPkg = false; 11291 } else { 11292 // Successfully deleted the old package; proceed with replace. 11293 11294 // If deleted package lived in a container, give users a chance to 11295 // relinquish resources before killing. 11296 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11297 if (DEBUG_INSTALL) { 11298 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11299 } 11300 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11301 final ArrayList<String> pkgList = new ArrayList<String>(1); 11302 pkgList.add(deletedPackage.applicationInfo.packageName); 11303 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11304 } 11305 11306 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11307 try { 11308 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11309 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11310 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11311 perUserInstalled, res, user); 11312 updatedSettings = true; 11313 } catch (PackageManagerException e) { 11314 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11315 } 11316 } 11317 11318 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11319 // remove package from internal structures. Note that we want deletePackageX to 11320 // delete the package data and cache directories that it created in 11321 // scanPackageLocked, unless those directories existed before we even tried to 11322 // install. 11323 if(updatedSettings) { 11324 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11325 deletePackageLI( 11326 pkgName, null, true, allUsers, perUserInstalled, 11327 PackageManager.DELETE_KEEP_DATA, 11328 res.removedInfo, true); 11329 } 11330 // Since we failed to install the new package we need to restore the old 11331 // package that we deleted. 11332 if (deletedPkg) { 11333 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11334 File restoreFile = new File(deletedPackage.codePath); 11335 // Parse old package 11336 boolean oldExternal = isExternal(deletedPackage); 11337 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11338 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11339 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11340 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11341 try { 11342 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11343 } catch (PackageManagerException e) { 11344 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11345 + e.getMessage()); 11346 return; 11347 } 11348 // Restore of old package succeeded. Update permissions. 11349 // writer 11350 synchronized (mPackages) { 11351 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11352 UPDATE_PERMISSIONS_ALL); 11353 // can downgrade to reader 11354 mSettings.writeLPr(); 11355 } 11356 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11357 } 11358 } 11359 } 11360 11361 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11362 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11363 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11364 String volumeUuid, PackageInstalledInfo res) { 11365 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11366 + ", old=" + deletedPackage); 11367 boolean disabledSystem = false; 11368 boolean updatedSettings = false; 11369 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11370 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11371 != 0) { 11372 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11373 } 11374 String packageName = deletedPackage.packageName; 11375 if (packageName == null) { 11376 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11377 "Attempt to delete null packageName."); 11378 return; 11379 } 11380 PackageParser.Package oldPkg; 11381 PackageSetting oldPkgSetting; 11382 // reader 11383 synchronized (mPackages) { 11384 oldPkg = mPackages.get(packageName); 11385 oldPkgSetting = mSettings.mPackages.get(packageName); 11386 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11387 (oldPkgSetting == null)) { 11388 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11389 "Couldn't find package:" + packageName + " information"); 11390 return; 11391 } 11392 } 11393 11394 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11395 res.removedInfo.removedPackage = packageName; 11396 // Remove existing system package 11397 removePackageLI(oldPkgSetting, true); 11398 // writer 11399 synchronized (mPackages) { 11400 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11401 if (!disabledSystem && deletedPackage != null) { 11402 // We didn't need to disable the .apk as a current system package, 11403 // which means we are replacing another update that is already 11404 // installed. We need to make sure to delete the older one's .apk. 11405 res.removedInfo.args = createInstallArgsForExisting(0, 11406 deletedPackage.applicationInfo.getCodePath(), 11407 deletedPackage.applicationInfo.getResourcePath(), 11408 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11409 } else { 11410 res.removedInfo.args = null; 11411 } 11412 } 11413 11414 // Successfully disabled the old package. Now proceed with re-installation 11415 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11416 11417 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11418 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11419 11420 PackageParser.Package newPackage = null; 11421 try { 11422 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11423 if (newPackage.mExtras != null) { 11424 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11425 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11426 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11427 11428 // is the update attempting to change shared user? that isn't going to work... 11429 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11430 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11431 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11432 + " to " + newPkgSetting.sharedUser); 11433 updatedSettings = true; 11434 } 11435 } 11436 11437 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11438 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11439 perUserInstalled, res, user); 11440 updatedSettings = true; 11441 } 11442 11443 } catch (PackageManagerException e) { 11444 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11445 } 11446 11447 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11448 // Re installation failed. Restore old information 11449 // Remove new pkg information 11450 if (newPackage != null) { 11451 removeInstalledPackageLI(newPackage, true); 11452 } 11453 // Add back the old system package 11454 try { 11455 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11456 } catch (PackageManagerException e) { 11457 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11458 } 11459 // Restore the old system information in Settings 11460 synchronized (mPackages) { 11461 if (disabledSystem) { 11462 mSettings.enableSystemPackageLPw(packageName); 11463 } 11464 if (updatedSettings) { 11465 mSettings.setInstallerPackageName(packageName, 11466 oldPkgSetting.installerPackageName); 11467 } 11468 mSettings.writeLPr(); 11469 } 11470 } 11471 } 11472 11473 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11474 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11475 UserHandle user) { 11476 String pkgName = newPackage.packageName; 11477 synchronized (mPackages) { 11478 //write settings. the installStatus will be incomplete at this stage. 11479 //note that the new package setting would have already been 11480 //added to mPackages. It hasn't been persisted yet. 11481 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11482 mSettings.writeLPr(); 11483 } 11484 11485 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11486 11487 synchronized (mPackages) { 11488 updatePermissionsLPw(newPackage.packageName, newPackage, 11489 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11490 ? UPDATE_PERMISSIONS_ALL : 0)); 11491 // For system-bundled packages, we assume that installing an upgraded version 11492 // of the package implies that the user actually wants to run that new code, 11493 // so we enable the package. 11494 PackageSetting ps = mSettings.mPackages.get(pkgName); 11495 if (ps != null) { 11496 if (isSystemApp(newPackage)) { 11497 // NB: implicit assumption that system package upgrades apply to all users 11498 if (DEBUG_INSTALL) { 11499 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11500 } 11501 if (res.origUsers != null) { 11502 for (int userHandle : res.origUsers) { 11503 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11504 userHandle, installerPackageName); 11505 } 11506 } 11507 // Also convey the prior install/uninstall state 11508 if (allUsers != null && perUserInstalled != null) { 11509 for (int i = 0; i < allUsers.length; i++) { 11510 if (DEBUG_INSTALL) { 11511 Slog.d(TAG, " user " + allUsers[i] 11512 + " => " + perUserInstalled[i]); 11513 } 11514 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11515 } 11516 // these install state changes will be persisted in the 11517 // upcoming call to mSettings.writeLPr(). 11518 } 11519 } 11520 // It's implied that when a user requests installation, they want the app to be 11521 // installed and enabled. 11522 int userId = user.getIdentifier(); 11523 if (userId != UserHandle.USER_ALL) { 11524 ps.setInstalled(true, userId); 11525 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11526 } 11527 } 11528 res.name = pkgName; 11529 res.uid = newPackage.applicationInfo.uid; 11530 res.pkg = newPackage; 11531 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11532 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11533 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11534 //to update install status 11535 mSettings.writeLPr(); 11536 } 11537 } 11538 11539 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11540 final int installFlags = args.installFlags; 11541 final String installerPackageName = args.installerPackageName; 11542 final String volumeUuid = args.volumeUuid; 11543 final File tmpPackageFile = new File(args.getCodePath()); 11544 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11545 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11546 || (args.volumeUuid != null)); 11547 boolean replace = false; 11548 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11549 // Result object to be returned 11550 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11551 11552 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11553 // Retrieve PackageSettings and parse package 11554 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11555 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11556 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11557 PackageParser pp = new PackageParser(); 11558 pp.setSeparateProcesses(mSeparateProcesses); 11559 pp.setDisplayMetrics(mMetrics); 11560 11561 final PackageParser.Package pkg; 11562 try { 11563 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11564 } catch (PackageParserException e) { 11565 res.setError("Failed parse during installPackageLI", e); 11566 return; 11567 } 11568 11569 // Mark that we have an install time CPU ABI override. 11570 pkg.cpuAbiOverride = args.abiOverride; 11571 11572 String pkgName = res.name = pkg.packageName; 11573 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11574 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11575 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11576 return; 11577 } 11578 } 11579 11580 try { 11581 pp.collectCertificates(pkg, parseFlags); 11582 pp.collectManifestDigest(pkg); 11583 } catch (PackageParserException e) { 11584 res.setError("Failed collect during installPackageLI", e); 11585 return; 11586 } 11587 11588 /* If the installer passed in a manifest digest, compare it now. */ 11589 if (args.manifestDigest != null) { 11590 if (DEBUG_INSTALL) { 11591 final String parsedManifest = pkg.manifestDigest == null ? "null" 11592 : pkg.manifestDigest.toString(); 11593 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11594 + parsedManifest); 11595 } 11596 11597 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11598 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11599 return; 11600 } 11601 } else if (DEBUG_INSTALL) { 11602 final String parsedManifest = pkg.manifestDigest == null 11603 ? "null" : pkg.manifestDigest.toString(); 11604 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11605 } 11606 11607 // Get rid of all references to package scan path via parser. 11608 pp = null; 11609 String oldCodePath = null; 11610 boolean systemApp = false; 11611 synchronized (mPackages) { 11612 // Check if installing already existing package 11613 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11614 String oldName = mSettings.mRenamedPackages.get(pkgName); 11615 if (pkg.mOriginalPackages != null 11616 && pkg.mOriginalPackages.contains(oldName) 11617 && mPackages.containsKey(oldName)) { 11618 // This package is derived from an original package, 11619 // and this device has been updating from that original 11620 // name. We must continue using the original name, so 11621 // rename the new package here. 11622 pkg.setPackageName(oldName); 11623 pkgName = pkg.packageName; 11624 replace = true; 11625 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11626 + oldName + " pkgName=" + pkgName); 11627 } else if (mPackages.containsKey(pkgName)) { 11628 // This package, under its official name, already exists 11629 // on the device; we should replace it. 11630 replace = true; 11631 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11632 } 11633 11634 // Prevent apps opting out from runtime permissions 11635 if (replace) { 11636 PackageParser.Package oldPackage = mPackages.get(pkgName); 11637 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11638 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11639 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11640 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11641 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11642 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11643 + " doesn't support runtime permissions but the old" 11644 + " target SDK " + oldTargetSdk + " does."); 11645 return; 11646 } 11647 } 11648 } 11649 11650 PackageSetting ps = mSettings.mPackages.get(pkgName); 11651 if (ps != null) { 11652 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11653 11654 // Quick sanity check that we're signed correctly if updating; 11655 // we'll check this again later when scanning, but we want to 11656 // bail early here before tripping over redefined permissions. 11657 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11658 if (!checkUpgradeKeySetLP(ps, pkg)) { 11659 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11660 + pkg.packageName + " upgrade keys do not match the " 11661 + "previously installed version"); 11662 return; 11663 } 11664 } else { 11665 try { 11666 verifySignaturesLP(ps, pkg); 11667 } catch (PackageManagerException e) { 11668 res.setError(e.error, e.getMessage()); 11669 return; 11670 } 11671 } 11672 11673 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11674 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11675 systemApp = (ps.pkg.applicationInfo.flags & 11676 ApplicationInfo.FLAG_SYSTEM) != 0; 11677 } 11678 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11679 } 11680 11681 // Check whether the newly-scanned package wants to define an already-defined perm 11682 int N = pkg.permissions.size(); 11683 for (int i = N-1; i >= 0; i--) { 11684 PackageParser.Permission perm = pkg.permissions.get(i); 11685 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11686 if (bp != null) { 11687 // If the defining package is signed with our cert, it's okay. This 11688 // also includes the "updating the same package" case, of course. 11689 // "updating same package" could also involve key-rotation. 11690 final boolean sigsOk; 11691 if (bp.sourcePackage.equals(pkg.packageName) 11692 && (bp.packageSetting instanceof PackageSetting) 11693 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11694 scanFlags))) { 11695 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11696 } else { 11697 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11698 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11699 } 11700 if (!sigsOk) { 11701 // If the owning package is the system itself, we log but allow 11702 // install to proceed; we fail the install on all other permission 11703 // redefinitions. 11704 if (!bp.sourcePackage.equals("android")) { 11705 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11706 + pkg.packageName + " attempting to redeclare permission " 11707 + perm.info.name + " already owned by " + bp.sourcePackage); 11708 res.origPermission = perm.info.name; 11709 res.origPackage = bp.sourcePackage; 11710 return; 11711 } else { 11712 Slog.w(TAG, "Package " + pkg.packageName 11713 + " attempting to redeclare system permission " 11714 + perm.info.name + "; ignoring new declaration"); 11715 pkg.permissions.remove(i); 11716 } 11717 } 11718 } 11719 } 11720 11721 } 11722 11723 if (systemApp && onExternal) { 11724 // Disable updates to system apps on sdcard 11725 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11726 "Cannot install updates to system apps on sdcard"); 11727 return; 11728 } 11729 11730 if (args.move != null) { 11731 // We did an in-place move, so dex is ready to roll 11732 scanFlags |= SCAN_NO_DEX; 11733 scanFlags |= SCAN_MOVE; 11734 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11735 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11736 scanFlags |= SCAN_NO_DEX; 11737 11738 try { 11739 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11740 true /* extract libs */); 11741 } catch (PackageManagerException pme) { 11742 Slog.e(TAG, "Error deriving application ABI", pme); 11743 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11744 return; 11745 } 11746 11747 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11748 int result = mPackageDexOptimizer 11749 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11750 false /* defer */, false /* inclDependencies */); 11751 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11752 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11753 return; 11754 } 11755 } 11756 11757 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11758 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11759 return; 11760 } 11761 11762 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11763 11764 if (replace) { 11765 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11766 installerPackageName, volumeUuid, res); 11767 } else { 11768 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11769 args.user, installerPackageName, volumeUuid, res); 11770 } 11771 synchronized (mPackages) { 11772 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11773 if (ps != null) { 11774 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11775 } 11776 } 11777 } 11778 11779 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11780 if (mIntentFilterVerifierComponent == null) { 11781 Slog.w(TAG, "No IntentFilter verification will not be done as " 11782 + "there is no IntentFilterVerifier available!"); 11783 return; 11784 } 11785 11786 final int verifierUid = getPackageUid( 11787 mIntentFilterVerifierComponent.getPackageName(), 11788 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11789 11790 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11791 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11792 msg.obj = pkg; 11793 msg.arg1 = userId; 11794 msg.arg2 = verifierUid; 11795 11796 mHandler.sendMessage(msg); 11797 } 11798 11799 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11800 PackageParser.Package pkg) { 11801 int size = pkg.activities.size(); 11802 if (size == 0) { 11803 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11804 "No activity, so no need to verify any IntentFilter!"); 11805 return; 11806 } 11807 11808 final boolean hasDomainURLs = hasDomainURLs(pkg); 11809 if (!hasDomainURLs) { 11810 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11811 "No domain URLs, so no need to verify any IntentFilter!"); 11812 return; 11813 } 11814 11815 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11816 + " if any IntentFilter from the " + size 11817 + " Activities needs verification ..."); 11818 11819 final int verificationId = mIntentFilterVerificationToken++; 11820 int count = 0; 11821 final String packageName = pkg.packageName; 11822 ArrayList<String> allHosts = new ArrayList<>(); 11823 11824 synchronized (mPackages) { 11825 for (PackageParser.Activity a : pkg.activities) { 11826 for (ActivityIntentInfo filter : a.intents) { 11827 boolean needsFilterVerification = filter.needsVerification(); 11828 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11829 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11830 "Verification needed for IntentFilter:" + filter.toString()); 11831 mIntentFilterVerifier.addOneIntentFilterVerification( 11832 verifierUid, userId, verificationId, filter, packageName); 11833 count++; 11834 } else if (!needsFilterVerification) { 11835 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11836 "No verification needed for IntentFilter:" + filter.toString()); 11837 if (hasValidDomains(filter)) { 11838 ArrayList<String> hosts = filter.getHostsList(); 11839 if (hosts.size() > 0) { 11840 allHosts.addAll(hosts); 11841 } else { 11842 if (allHosts.isEmpty()) { 11843 allHosts.add("*"); 11844 } 11845 } 11846 } 11847 } else { 11848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11849 "Verification already done for IntentFilter:" + filter.toString()); 11850 } 11851 } 11852 } 11853 } 11854 11855 if (count > 0) { 11856 mIntentFilterVerifier.startVerifications(userId); 11857 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Started " + count 11858 + " IntentFilter verification" + (count > 1 ? "s" : "") 11859 + " for userId:" + userId + "!"); 11860 } else { 11861 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11862 "No need to start any IntentFilter verification!"); 11863 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11864 packageName, allHosts) != null) { 11865 scheduleWriteSettingsLocked(); 11866 } 11867 } 11868 } 11869 11870 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11871 final ComponentName cn = filter.activity.getComponentName(); 11872 final String packageName = cn.getPackageName(); 11873 11874 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11875 packageName); 11876 if (ivi == null) { 11877 return true; 11878 } 11879 int status = ivi.getStatus(); 11880 switch (status) { 11881 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11882 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11883 return true; 11884 11885 default: 11886 // Nothing to do 11887 return false; 11888 } 11889 } 11890 11891 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11892 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11893 || ((pkg.applicationInfo.privateFlags 11894 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11895 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11896 } 11897 11898 private static boolean isMultiArch(PackageSetting ps) { 11899 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11900 } 11901 11902 private static boolean isMultiArch(ApplicationInfo info) { 11903 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11904 } 11905 11906 private static boolean isExternal(PackageParser.Package pkg) { 11907 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11908 } 11909 11910 private static boolean isExternal(PackageSetting ps) { 11911 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11912 } 11913 11914 private static boolean isExternal(ApplicationInfo info) { 11915 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11916 } 11917 11918 private static boolean isSystemApp(PackageParser.Package pkg) { 11919 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11920 } 11921 11922 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11923 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11924 } 11925 11926 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11927 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11928 } 11929 11930 private static boolean isSystemApp(PackageSetting ps) { 11931 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11932 } 11933 11934 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11935 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11936 } 11937 11938 private int packageFlagsToInstallFlags(PackageSetting ps) { 11939 int installFlags = 0; 11940 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11941 // This existing package was an external ASEC install when we have 11942 // the external flag without a UUID 11943 installFlags |= PackageManager.INSTALL_EXTERNAL; 11944 } 11945 if (ps.isForwardLocked()) { 11946 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11947 } 11948 return installFlags; 11949 } 11950 11951 private void deleteTempPackageFiles() { 11952 final FilenameFilter filter = new FilenameFilter() { 11953 public boolean accept(File dir, String name) { 11954 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11955 } 11956 }; 11957 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11958 file.delete(); 11959 } 11960 } 11961 11962 @Override 11963 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11964 int flags) { 11965 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11966 flags); 11967 } 11968 11969 @Override 11970 public void deletePackage(final String packageName, 11971 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11972 mContext.enforceCallingOrSelfPermission( 11973 android.Manifest.permission.DELETE_PACKAGES, null); 11974 final int uid = Binder.getCallingUid(); 11975 if (UserHandle.getUserId(uid) != userId) { 11976 mContext.enforceCallingPermission( 11977 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11978 "deletePackage for user " + userId); 11979 } 11980 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11981 try { 11982 observer.onPackageDeleted(packageName, 11983 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11984 } catch (RemoteException re) { 11985 } 11986 return; 11987 } 11988 11989 boolean uninstallBlocked = false; 11990 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11991 int[] users = sUserManager.getUserIds(); 11992 for (int i = 0; i < users.length; ++i) { 11993 if (getBlockUninstallForUser(packageName, users[i])) { 11994 uninstallBlocked = true; 11995 break; 11996 } 11997 } 11998 } else { 11999 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 12000 } 12001 if (uninstallBlocked) { 12002 try { 12003 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 12004 null); 12005 } catch (RemoteException re) { 12006 } 12007 return; 12008 } 12009 12010 if (DEBUG_REMOVE) { 12011 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12012 } 12013 // Queue up an async operation since the package deletion may take a little while. 12014 mHandler.post(new Runnable() { 12015 public void run() { 12016 mHandler.removeCallbacks(this); 12017 final int returnCode = deletePackageX(packageName, userId, flags); 12018 if (observer != null) { 12019 try { 12020 observer.onPackageDeleted(packageName, returnCode, null); 12021 } catch (RemoteException e) { 12022 Log.i(TAG, "Observer no longer exists."); 12023 } //end catch 12024 } //end if 12025 } //end run 12026 }); 12027 } 12028 12029 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12030 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12031 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12032 try { 12033 if (dpm != null) { 12034 if (dpm.isDeviceOwner(packageName)) { 12035 return true; 12036 } 12037 int[] users; 12038 if (userId == UserHandle.USER_ALL) { 12039 users = sUserManager.getUserIds(); 12040 } else { 12041 users = new int[]{userId}; 12042 } 12043 for (int i = 0; i < users.length; ++i) { 12044 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12045 return true; 12046 } 12047 } 12048 } 12049 } catch (RemoteException e) { 12050 } 12051 return false; 12052 } 12053 12054 /** 12055 * This method is an internal method that could be get invoked either 12056 * to delete an installed package or to clean up a failed installation. 12057 * After deleting an installed package, a broadcast is sent to notify any 12058 * listeners that the package has been installed. For cleaning up a failed 12059 * installation, the broadcast is not necessary since the package's 12060 * installation wouldn't have sent the initial broadcast either 12061 * The key steps in deleting a package are 12062 * deleting the package information in internal structures like mPackages, 12063 * deleting the packages base directories through installd 12064 * updating mSettings to reflect current status 12065 * persisting settings for later use 12066 * sending a broadcast if necessary 12067 */ 12068 private int deletePackageX(String packageName, int userId, int flags) { 12069 final PackageRemovedInfo info = new PackageRemovedInfo(); 12070 final boolean res; 12071 12072 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12073 ? UserHandle.ALL : new UserHandle(userId); 12074 12075 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12076 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12077 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12078 } 12079 12080 boolean removedForAllUsers = false; 12081 boolean systemUpdate = false; 12082 12083 // for the uninstall-updates case and restricted profiles, remember the per- 12084 // userhandle installed state 12085 int[] allUsers; 12086 boolean[] perUserInstalled; 12087 synchronized (mPackages) { 12088 PackageSetting ps = mSettings.mPackages.get(packageName); 12089 allUsers = sUserManager.getUserIds(); 12090 perUserInstalled = new boolean[allUsers.length]; 12091 for (int i = 0; i < allUsers.length; i++) { 12092 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12093 } 12094 } 12095 12096 synchronized (mInstallLock) { 12097 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12098 res = deletePackageLI(packageName, removeForUser, 12099 true, allUsers, perUserInstalled, 12100 flags | REMOVE_CHATTY, info, true); 12101 systemUpdate = info.isRemovedPackageSystemUpdate; 12102 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12103 removedForAllUsers = true; 12104 } 12105 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12106 + " removedForAllUsers=" + removedForAllUsers); 12107 } 12108 12109 if (res) { 12110 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12111 12112 // If the removed package was a system update, the old system package 12113 // was re-enabled; we need to broadcast this information 12114 if (systemUpdate) { 12115 Bundle extras = new Bundle(1); 12116 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12117 ? info.removedAppId : info.uid); 12118 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12119 12120 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12121 extras, null, null, null); 12122 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12123 extras, null, null, null); 12124 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12125 null, packageName, null, null); 12126 } 12127 } 12128 // Force a gc here. 12129 Runtime.getRuntime().gc(); 12130 // Delete the resources here after sending the broadcast to let 12131 // other processes clean up before deleting resources. 12132 if (info.args != null) { 12133 synchronized (mInstallLock) { 12134 info.args.doPostDeleteLI(true); 12135 } 12136 } 12137 12138 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12139 } 12140 12141 class PackageRemovedInfo { 12142 String removedPackage; 12143 int uid = -1; 12144 int removedAppId = -1; 12145 int[] removedUsers = null; 12146 boolean isRemovedPackageSystemUpdate = false; 12147 // Clean up resources deleted packages. 12148 InstallArgs args = null; 12149 12150 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12151 Bundle extras = new Bundle(1); 12152 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12153 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12154 if (replacing) { 12155 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12156 } 12157 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12158 if (removedPackage != null) { 12159 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12160 extras, null, null, removedUsers); 12161 if (fullRemove && !replacing) { 12162 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12163 extras, null, null, removedUsers); 12164 } 12165 } 12166 if (removedAppId >= 0) { 12167 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12168 removedUsers); 12169 } 12170 } 12171 } 12172 12173 /* 12174 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12175 * flag is not set, the data directory is removed as well. 12176 * make sure this flag is set for partially installed apps. If not its meaningless to 12177 * delete a partially installed application. 12178 */ 12179 private void removePackageDataLI(PackageSetting ps, 12180 int[] allUserHandles, boolean[] perUserInstalled, 12181 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12182 String packageName = ps.name; 12183 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12184 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12185 // Retrieve object to delete permissions for shared user later on 12186 final PackageSetting deletedPs; 12187 // reader 12188 synchronized (mPackages) { 12189 deletedPs = mSettings.mPackages.get(packageName); 12190 if (outInfo != null) { 12191 outInfo.removedPackage = packageName; 12192 outInfo.removedUsers = deletedPs != null 12193 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12194 : null; 12195 } 12196 } 12197 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12198 removeDataDirsLI(ps.volumeUuid, packageName); 12199 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12200 } 12201 // writer 12202 synchronized (mPackages) { 12203 if (deletedPs != null) { 12204 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12205 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12206 clearDefaultBrowserIfNeeded(packageName); 12207 if (outInfo != null) { 12208 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12209 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12210 } 12211 updatePermissionsLPw(deletedPs.name, null, 0); 12212 if (deletedPs.sharedUser != null) { 12213 // Remove permissions associated with package. Since runtime 12214 // permissions are per user we have to kill the removed package 12215 // or packages running under the shared user of the removed 12216 // package if revoking the permissions requested only by the removed 12217 // package is successful and this causes a change in gids. 12218 for (int userId : UserManagerService.getInstance().getUserIds()) { 12219 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12220 userId); 12221 if (userIdToKill == UserHandle.USER_ALL 12222 || userIdToKill >= UserHandle.USER_OWNER) { 12223 // If gids changed for this user, kill all affected packages. 12224 mHandler.post(new Runnable() { 12225 @Override 12226 public void run() { 12227 // This has to happen with no lock held. 12228 killSettingPackagesForUser(deletedPs, userIdToKill, 12229 KILL_APP_REASON_GIDS_CHANGED); 12230 } 12231 }); 12232 break; 12233 } 12234 } 12235 } 12236 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12237 } 12238 // make sure to preserve per-user disabled state if this removal was just 12239 // a downgrade of a system app to the factory package 12240 if (allUserHandles != null && perUserInstalled != null) { 12241 if (DEBUG_REMOVE) { 12242 Slog.d(TAG, "Propagating install state across downgrade"); 12243 } 12244 for (int i = 0; i < allUserHandles.length; i++) { 12245 if (DEBUG_REMOVE) { 12246 Slog.d(TAG, " user " + allUserHandles[i] 12247 + " => " + perUserInstalled[i]); 12248 } 12249 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12250 } 12251 } 12252 } 12253 // can downgrade to reader 12254 if (writeSettings) { 12255 // Save settings now 12256 mSettings.writeLPr(); 12257 } 12258 } 12259 if (outInfo != null) { 12260 // A user ID was deleted here. Go through all users and remove it 12261 // from KeyStore. 12262 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12263 } 12264 } 12265 12266 static boolean locationIsPrivileged(File path) { 12267 try { 12268 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12269 .getCanonicalPath(); 12270 return path.getCanonicalPath().startsWith(privilegedAppDir); 12271 } catch (IOException e) { 12272 Slog.e(TAG, "Unable to access code path " + path); 12273 } 12274 return false; 12275 } 12276 12277 /* 12278 * Tries to delete system package. 12279 */ 12280 private boolean deleteSystemPackageLI(PackageSetting newPs, 12281 int[] allUserHandles, boolean[] perUserInstalled, 12282 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12283 final boolean applyUserRestrictions 12284 = (allUserHandles != null) && (perUserInstalled != null); 12285 PackageSetting disabledPs = null; 12286 // Confirm if the system package has been updated 12287 // An updated system app can be deleted. This will also have to restore 12288 // the system pkg from system partition 12289 // reader 12290 synchronized (mPackages) { 12291 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12292 } 12293 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12294 + " disabledPs=" + disabledPs); 12295 if (disabledPs == null) { 12296 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12297 return false; 12298 } else if (DEBUG_REMOVE) { 12299 Slog.d(TAG, "Deleting system pkg from data partition"); 12300 } 12301 if (DEBUG_REMOVE) { 12302 if (applyUserRestrictions) { 12303 Slog.d(TAG, "Remembering install states:"); 12304 for (int i = 0; i < allUserHandles.length; i++) { 12305 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12306 } 12307 } 12308 } 12309 // Delete the updated package 12310 outInfo.isRemovedPackageSystemUpdate = true; 12311 if (disabledPs.versionCode < newPs.versionCode) { 12312 // Delete data for downgrades 12313 flags &= ~PackageManager.DELETE_KEEP_DATA; 12314 } else { 12315 // Preserve data by setting flag 12316 flags |= PackageManager.DELETE_KEEP_DATA; 12317 } 12318 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12319 allUserHandles, perUserInstalled, outInfo, writeSettings); 12320 if (!ret) { 12321 return false; 12322 } 12323 // writer 12324 synchronized (mPackages) { 12325 // Reinstate the old system package 12326 mSettings.enableSystemPackageLPw(newPs.name); 12327 // Remove any native libraries from the upgraded package. 12328 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12329 } 12330 // Install the system package 12331 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12332 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12333 if (locationIsPrivileged(disabledPs.codePath)) { 12334 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12335 } 12336 12337 final PackageParser.Package newPkg; 12338 try { 12339 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12340 } catch (PackageManagerException e) { 12341 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12342 return false; 12343 } 12344 12345 // writer 12346 synchronized (mPackages) { 12347 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12348 updatePermissionsLPw(newPkg.packageName, newPkg, 12349 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12350 if (applyUserRestrictions) { 12351 if (DEBUG_REMOVE) { 12352 Slog.d(TAG, "Propagating install state across reinstall"); 12353 } 12354 for (int i = 0; i < allUserHandles.length; i++) { 12355 if (DEBUG_REMOVE) { 12356 Slog.d(TAG, " user " + allUserHandles[i] 12357 + " => " + perUserInstalled[i]); 12358 } 12359 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12360 } 12361 // Regardless of writeSettings we need to ensure that this restriction 12362 // state propagation is persisted 12363 mSettings.writeAllUsersPackageRestrictionsLPr(); 12364 } 12365 // can downgrade to reader here 12366 if (writeSettings) { 12367 mSettings.writeLPr(); 12368 } 12369 } 12370 return true; 12371 } 12372 12373 private boolean deleteInstalledPackageLI(PackageSetting ps, 12374 boolean deleteCodeAndResources, int flags, 12375 int[] allUserHandles, boolean[] perUserInstalled, 12376 PackageRemovedInfo outInfo, boolean writeSettings) { 12377 if (outInfo != null) { 12378 outInfo.uid = ps.appId; 12379 } 12380 12381 // Delete package data from internal structures and also remove data if flag is set 12382 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12383 12384 // Delete application code and resources 12385 if (deleteCodeAndResources && (outInfo != null)) { 12386 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12387 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12388 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12389 } 12390 return true; 12391 } 12392 12393 @Override 12394 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12395 int userId) { 12396 mContext.enforceCallingOrSelfPermission( 12397 android.Manifest.permission.DELETE_PACKAGES, null); 12398 synchronized (mPackages) { 12399 PackageSetting ps = mSettings.mPackages.get(packageName); 12400 if (ps == null) { 12401 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12402 return false; 12403 } 12404 if (!ps.getInstalled(userId)) { 12405 // Can't block uninstall for an app that is not installed or enabled. 12406 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12407 return false; 12408 } 12409 ps.setBlockUninstall(blockUninstall, userId); 12410 mSettings.writePackageRestrictionsLPr(userId); 12411 } 12412 return true; 12413 } 12414 12415 @Override 12416 public boolean getBlockUninstallForUser(String packageName, int userId) { 12417 synchronized (mPackages) { 12418 PackageSetting ps = mSettings.mPackages.get(packageName); 12419 if (ps == null) { 12420 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12421 return false; 12422 } 12423 return ps.getBlockUninstall(userId); 12424 } 12425 } 12426 12427 /* 12428 * This method handles package deletion in general 12429 */ 12430 private boolean deletePackageLI(String packageName, UserHandle user, 12431 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12432 int flags, PackageRemovedInfo outInfo, 12433 boolean writeSettings) { 12434 if (packageName == null) { 12435 Slog.w(TAG, "Attempt to delete null packageName."); 12436 return false; 12437 } 12438 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12439 PackageSetting ps; 12440 boolean dataOnly = false; 12441 int removeUser = -1; 12442 int appId = -1; 12443 synchronized (mPackages) { 12444 ps = mSettings.mPackages.get(packageName); 12445 if (ps == null) { 12446 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12447 return false; 12448 } 12449 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12450 && user.getIdentifier() != UserHandle.USER_ALL) { 12451 // The caller is asking that the package only be deleted for a single 12452 // user. To do this, we just mark its uninstalled state and delete 12453 // its data. If this is a system app, we only allow this to happen if 12454 // they have set the special DELETE_SYSTEM_APP which requests different 12455 // semantics than normal for uninstalling system apps. 12456 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12457 ps.setUserState(user.getIdentifier(), 12458 COMPONENT_ENABLED_STATE_DEFAULT, 12459 false, //installed 12460 true, //stopped 12461 true, //notLaunched 12462 false, //hidden 12463 null, null, null, 12464 false, // blockUninstall 12465 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12466 if (!isSystemApp(ps)) { 12467 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12468 // Other user still have this package installed, so all 12469 // we need to do is clear this user's data and save that 12470 // it is uninstalled. 12471 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12472 removeUser = user.getIdentifier(); 12473 appId = ps.appId; 12474 scheduleWritePackageRestrictionsLocked(removeUser); 12475 } else { 12476 // We need to set it back to 'installed' so the uninstall 12477 // broadcasts will be sent correctly. 12478 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12479 ps.setInstalled(true, user.getIdentifier()); 12480 } 12481 } else { 12482 // This is a system app, so we assume that the 12483 // other users still have this package installed, so all 12484 // we need to do is clear this user's data and save that 12485 // it is uninstalled. 12486 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12487 removeUser = user.getIdentifier(); 12488 appId = ps.appId; 12489 scheduleWritePackageRestrictionsLocked(removeUser); 12490 } 12491 } 12492 } 12493 12494 if (removeUser >= 0) { 12495 // From above, we determined that we are deleting this only 12496 // for a single user. Continue the work here. 12497 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12498 if (outInfo != null) { 12499 outInfo.removedPackage = packageName; 12500 outInfo.removedAppId = appId; 12501 outInfo.removedUsers = new int[] {removeUser}; 12502 } 12503 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12504 removeKeystoreDataIfNeeded(removeUser, appId); 12505 schedulePackageCleaning(packageName, removeUser, false); 12506 synchronized (mPackages) { 12507 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12508 scheduleWritePackageRestrictionsLocked(removeUser); 12509 } 12510 } 12511 return true; 12512 } 12513 12514 if (dataOnly) { 12515 // Delete application data first 12516 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12517 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12518 return true; 12519 } 12520 12521 boolean ret = false; 12522 if (isSystemApp(ps)) { 12523 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12524 // When an updated system application is deleted we delete the existing resources as well and 12525 // fall back to existing code in system partition 12526 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12527 flags, outInfo, writeSettings); 12528 } else { 12529 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12530 // Kill application pre-emptively especially for apps on sd. 12531 killApplication(packageName, ps.appId, "uninstall pkg"); 12532 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12533 allUserHandles, perUserInstalled, 12534 outInfo, writeSettings); 12535 } 12536 12537 return ret; 12538 } 12539 12540 private final class ClearStorageConnection implements ServiceConnection { 12541 IMediaContainerService mContainerService; 12542 12543 @Override 12544 public void onServiceConnected(ComponentName name, IBinder service) { 12545 synchronized (this) { 12546 mContainerService = IMediaContainerService.Stub.asInterface(service); 12547 notifyAll(); 12548 } 12549 } 12550 12551 @Override 12552 public void onServiceDisconnected(ComponentName name) { 12553 } 12554 } 12555 12556 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12557 final boolean mounted; 12558 if (Environment.isExternalStorageEmulated()) { 12559 mounted = true; 12560 } else { 12561 final String status = Environment.getExternalStorageState(); 12562 12563 mounted = status.equals(Environment.MEDIA_MOUNTED) 12564 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12565 } 12566 12567 if (!mounted) { 12568 return; 12569 } 12570 12571 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12572 int[] users; 12573 if (userId == UserHandle.USER_ALL) { 12574 users = sUserManager.getUserIds(); 12575 } else { 12576 users = new int[] { userId }; 12577 } 12578 final ClearStorageConnection conn = new ClearStorageConnection(); 12579 if (mContext.bindServiceAsUser( 12580 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12581 try { 12582 for (int curUser : users) { 12583 long timeout = SystemClock.uptimeMillis() + 5000; 12584 synchronized (conn) { 12585 long now = SystemClock.uptimeMillis(); 12586 while (conn.mContainerService == null && now < timeout) { 12587 try { 12588 conn.wait(timeout - now); 12589 } catch (InterruptedException e) { 12590 } 12591 } 12592 } 12593 if (conn.mContainerService == null) { 12594 return; 12595 } 12596 12597 final UserEnvironment userEnv = new UserEnvironment(curUser); 12598 clearDirectory(conn.mContainerService, 12599 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12600 if (allData) { 12601 clearDirectory(conn.mContainerService, 12602 userEnv.buildExternalStorageAppDataDirs(packageName)); 12603 clearDirectory(conn.mContainerService, 12604 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12605 } 12606 } 12607 } finally { 12608 mContext.unbindService(conn); 12609 } 12610 } 12611 } 12612 12613 @Override 12614 public void clearApplicationUserData(final String packageName, 12615 final IPackageDataObserver observer, final int userId) { 12616 mContext.enforceCallingOrSelfPermission( 12617 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12618 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12619 // Queue up an async operation since the package deletion may take a little while. 12620 mHandler.post(new Runnable() { 12621 public void run() { 12622 mHandler.removeCallbacks(this); 12623 final boolean succeeded; 12624 synchronized (mInstallLock) { 12625 succeeded = clearApplicationUserDataLI(packageName, userId); 12626 } 12627 clearExternalStorageDataSync(packageName, userId, true); 12628 if (succeeded) { 12629 // invoke DeviceStorageMonitor's update method to clear any notifications 12630 DeviceStorageMonitorInternal 12631 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12632 if (dsm != null) { 12633 dsm.checkMemory(); 12634 } 12635 } 12636 if(observer != null) { 12637 try { 12638 observer.onRemoveCompleted(packageName, succeeded); 12639 } catch (RemoteException e) { 12640 Log.i(TAG, "Observer no longer exists."); 12641 } 12642 } //end if observer 12643 } //end run 12644 }); 12645 } 12646 12647 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12648 if (packageName == null) { 12649 Slog.w(TAG, "Attempt to delete null packageName."); 12650 return false; 12651 } 12652 12653 // Try finding details about the requested package 12654 PackageParser.Package pkg; 12655 synchronized (mPackages) { 12656 pkg = mPackages.get(packageName); 12657 if (pkg == null) { 12658 final PackageSetting ps = mSettings.mPackages.get(packageName); 12659 if (ps != null) { 12660 pkg = ps.pkg; 12661 } 12662 } 12663 12664 if (pkg == null) { 12665 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12666 return false; 12667 } 12668 12669 PackageSetting ps = (PackageSetting) pkg.mExtras; 12670 PermissionsState permissionsState = ps.getPermissionsState(); 12671 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12672 } 12673 12674 // Always delete data directories for package, even if we found no other 12675 // record of app. This helps users recover from UID mismatches without 12676 // resorting to a full data wipe. 12677 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12678 if (retCode < 0) { 12679 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12680 return false; 12681 } 12682 12683 final int appId = pkg.applicationInfo.uid; 12684 removeKeystoreDataIfNeeded(userId, appId); 12685 12686 // Create a native library symlink only if we have native libraries 12687 // and if the native libraries are 32 bit libraries. We do not provide 12688 // this symlink for 64 bit libraries. 12689 if (pkg.applicationInfo.primaryCpuAbi != null && 12690 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12691 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12692 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12693 nativeLibPath, userId) < 0) { 12694 Slog.w(TAG, "Failed linking native library dir"); 12695 return false; 12696 } 12697 } 12698 12699 return true; 12700 } 12701 12702 12703 /** 12704 * Revokes granted runtime permissions and clears resettable flags 12705 * which are flags that can be set by a user interaction. 12706 * 12707 * @param permissionsState The permission state to reset. 12708 * @param userId The device user for which to do a reset. 12709 */ 12710 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12711 PermissionsState permissionsState, int userId) { 12712 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12713 | PackageManager.FLAG_PERMISSION_USER_FIXED 12714 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12715 12716 boolean needsWrite = false; 12717 12718 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12719 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12720 if (bp != null) { 12721 permissionsState.revokeRuntimePermission(bp, userId); 12722 permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0); 12723 needsWrite = true; 12724 } 12725 } 12726 12727 if (needsWrite) { 12728 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12729 } 12730 } 12731 12732 /** 12733 * Remove entries from the keystore daemon. Will only remove it if the 12734 * {@code appId} is valid. 12735 */ 12736 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12737 if (appId < 0) { 12738 return; 12739 } 12740 12741 final KeyStore keyStore = KeyStore.getInstance(); 12742 if (keyStore != null) { 12743 if (userId == UserHandle.USER_ALL) { 12744 for (final int individual : sUserManager.getUserIds()) { 12745 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12746 } 12747 } else { 12748 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12749 } 12750 } else { 12751 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12752 } 12753 } 12754 12755 @Override 12756 public void deleteApplicationCacheFiles(final String packageName, 12757 final IPackageDataObserver observer) { 12758 mContext.enforceCallingOrSelfPermission( 12759 android.Manifest.permission.DELETE_CACHE_FILES, null); 12760 // Queue up an async operation since the package deletion may take a little while. 12761 final int userId = UserHandle.getCallingUserId(); 12762 mHandler.post(new Runnable() { 12763 public void run() { 12764 mHandler.removeCallbacks(this); 12765 final boolean succeded; 12766 synchronized (mInstallLock) { 12767 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12768 } 12769 clearExternalStorageDataSync(packageName, userId, false); 12770 if (observer != null) { 12771 try { 12772 observer.onRemoveCompleted(packageName, succeded); 12773 } catch (RemoteException e) { 12774 Log.i(TAG, "Observer no longer exists."); 12775 } 12776 } //end if observer 12777 } //end run 12778 }); 12779 } 12780 12781 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12782 if (packageName == null) { 12783 Slog.w(TAG, "Attempt to delete null packageName."); 12784 return false; 12785 } 12786 PackageParser.Package p; 12787 synchronized (mPackages) { 12788 p = mPackages.get(packageName); 12789 } 12790 if (p == null) { 12791 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12792 return false; 12793 } 12794 final ApplicationInfo applicationInfo = p.applicationInfo; 12795 if (applicationInfo == null) { 12796 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12797 return false; 12798 } 12799 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12800 if (retCode < 0) { 12801 Slog.w(TAG, "Couldn't remove cache files for package: " 12802 + packageName + " u" + userId); 12803 return false; 12804 } 12805 return true; 12806 } 12807 12808 @Override 12809 public void getPackageSizeInfo(final String packageName, int userHandle, 12810 final IPackageStatsObserver observer) { 12811 mContext.enforceCallingOrSelfPermission( 12812 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12813 if (packageName == null) { 12814 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12815 } 12816 12817 PackageStats stats = new PackageStats(packageName, userHandle); 12818 12819 /* 12820 * Queue up an async operation since the package measurement may take a 12821 * little while. 12822 */ 12823 Message msg = mHandler.obtainMessage(INIT_COPY); 12824 msg.obj = new MeasureParams(stats, observer); 12825 mHandler.sendMessage(msg); 12826 } 12827 12828 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12829 PackageStats pStats) { 12830 if (packageName == null) { 12831 Slog.w(TAG, "Attempt to get size of null packageName."); 12832 return false; 12833 } 12834 PackageParser.Package p; 12835 boolean dataOnly = false; 12836 String libDirRoot = null; 12837 String asecPath = null; 12838 PackageSetting ps = null; 12839 synchronized (mPackages) { 12840 p = mPackages.get(packageName); 12841 ps = mSettings.mPackages.get(packageName); 12842 if(p == null) { 12843 dataOnly = true; 12844 if((ps == null) || (ps.pkg == null)) { 12845 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12846 return false; 12847 } 12848 p = ps.pkg; 12849 } 12850 if (ps != null) { 12851 libDirRoot = ps.legacyNativeLibraryPathString; 12852 } 12853 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12854 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12855 if (secureContainerId != null) { 12856 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12857 } 12858 } 12859 } 12860 String publicSrcDir = null; 12861 if(!dataOnly) { 12862 final ApplicationInfo applicationInfo = p.applicationInfo; 12863 if (applicationInfo == null) { 12864 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12865 return false; 12866 } 12867 if (p.isForwardLocked()) { 12868 publicSrcDir = applicationInfo.getBaseResourcePath(); 12869 } 12870 } 12871 // TODO: extend to measure size of split APKs 12872 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12873 // not just the first level. 12874 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12875 // just the primary. 12876 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12877 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12878 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12879 if (res < 0) { 12880 return false; 12881 } 12882 12883 // Fix-up for forward-locked applications in ASEC containers. 12884 if (!isExternal(p)) { 12885 pStats.codeSize += pStats.externalCodeSize; 12886 pStats.externalCodeSize = 0L; 12887 } 12888 12889 return true; 12890 } 12891 12892 12893 @Override 12894 public void addPackageToPreferred(String packageName) { 12895 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12896 } 12897 12898 @Override 12899 public void removePackageFromPreferred(String packageName) { 12900 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12901 } 12902 12903 @Override 12904 public List<PackageInfo> getPreferredPackages(int flags) { 12905 return new ArrayList<PackageInfo>(); 12906 } 12907 12908 private int getUidTargetSdkVersionLockedLPr(int uid) { 12909 Object obj = mSettings.getUserIdLPr(uid); 12910 if (obj instanceof SharedUserSetting) { 12911 final SharedUserSetting sus = (SharedUserSetting) obj; 12912 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12913 final Iterator<PackageSetting> it = sus.packages.iterator(); 12914 while (it.hasNext()) { 12915 final PackageSetting ps = it.next(); 12916 if (ps.pkg != null) { 12917 int v = ps.pkg.applicationInfo.targetSdkVersion; 12918 if (v < vers) vers = v; 12919 } 12920 } 12921 return vers; 12922 } else if (obj instanceof PackageSetting) { 12923 final PackageSetting ps = (PackageSetting) obj; 12924 if (ps.pkg != null) { 12925 return ps.pkg.applicationInfo.targetSdkVersion; 12926 } 12927 } 12928 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12929 } 12930 12931 @Override 12932 public void addPreferredActivity(IntentFilter filter, int match, 12933 ComponentName[] set, ComponentName activity, int userId) { 12934 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12935 "Adding preferred"); 12936 } 12937 12938 private void addPreferredActivityInternal(IntentFilter filter, int match, 12939 ComponentName[] set, ComponentName activity, boolean always, int userId, 12940 String opname) { 12941 // writer 12942 int callingUid = Binder.getCallingUid(); 12943 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12944 if (filter.countActions() == 0) { 12945 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12946 return; 12947 } 12948 synchronized (mPackages) { 12949 if (mContext.checkCallingOrSelfPermission( 12950 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12951 != PackageManager.PERMISSION_GRANTED) { 12952 if (getUidTargetSdkVersionLockedLPr(callingUid) 12953 < Build.VERSION_CODES.FROYO) { 12954 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12955 + callingUid); 12956 return; 12957 } 12958 mContext.enforceCallingOrSelfPermission( 12959 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12960 } 12961 12962 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12963 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12964 + userId + ":"); 12965 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12966 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12967 scheduleWritePackageRestrictionsLocked(userId); 12968 } 12969 } 12970 12971 @Override 12972 public void replacePreferredActivity(IntentFilter filter, int match, 12973 ComponentName[] set, ComponentName activity, int userId) { 12974 if (filter.countActions() != 1) { 12975 throw new IllegalArgumentException( 12976 "replacePreferredActivity expects filter to have only 1 action."); 12977 } 12978 if (filter.countDataAuthorities() != 0 12979 || filter.countDataPaths() != 0 12980 || filter.countDataSchemes() > 1 12981 || filter.countDataTypes() != 0) { 12982 throw new IllegalArgumentException( 12983 "replacePreferredActivity expects filter to have no data authorities, " + 12984 "paths, or types; and at most one scheme."); 12985 } 12986 12987 final int callingUid = Binder.getCallingUid(); 12988 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12989 synchronized (mPackages) { 12990 if (mContext.checkCallingOrSelfPermission( 12991 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12992 != PackageManager.PERMISSION_GRANTED) { 12993 if (getUidTargetSdkVersionLockedLPr(callingUid) 12994 < Build.VERSION_CODES.FROYO) { 12995 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12996 + Binder.getCallingUid()); 12997 return; 12998 } 12999 mContext.enforceCallingOrSelfPermission( 13000 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13001 } 13002 13003 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13004 if (pir != null) { 13005 // Get all of the existing entries that exactly match this filter. 13006 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 13007 if (existing != null && existing.size() == 1) { 13008 PreferredActivity cur = existing.get(0); 13009 if (DEBUG_PREFERRED) { 13010 Slog.i(TAG, "Checking replace of preferred:"); 13011 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13012 if (!cur.mPref.mAlways) { 13013 Slog.i(TAG, " -- CUR; not mAlways!"); 13014 } else { 13015 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13016 Slog.i(TAG, " -- CUR: mSet=" 13017 + Arrays.toString(cur.mPref.mSetComponents)); 13018 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13019 Slog.i(TAG, " -- NEW: mMatch=" 13020 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13021 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13022 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13023 } 13024 } 13025 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13026 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13027 && cur.mPref.sameSet(set)) { 13028 // Setting the preferred activity to what it happens to be already 13029 if (DEBUG_PREFERRED) { 13030 Slog.i(TAG, "Replacing with same preferred activity " 13031 + cur.mPref.mShortComponent + " for user " 13032 + userId + ":"); 13033 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13034 } 13035 return; 13036 } 13037 } 13038 13039 if (existing != null) { 13040 if (DEBUG_PREFERRED) { 13041 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13042 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13043 } 13044 for (int i = 0; i < existing.size(); i++) { 13045 PreferredActivity pa = existing.get(i); 13046 if (DEBUG_PREFERRED) { 13047 Slog.i(TAG, "Removing existing preferred activity " 13048 + pa.mPref.mComponent + ":"); 13049 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13050 } 13051 pir.removeFilter(pa); 13052 } 13053 } 13054 } 13055 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13056 "Replacing preferred"); 13057 } 13058 } 13059 13060 @Override 13061 public void clearPackagePreferredActivities(String packageName) { 13062 final int uid = Binder.getCallingUid(); 13063 // writer 13064 synchronized (mPackages) { 13065 PackageParser.Package pkg = mPackages.get(packageName); 13066 if (pkg == null || pkg.applicationInfo.uid != uid) { 13067 if (mContext.checkCallingOrSelfPermission( 13068 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13069 != PackageManager.PERMISSION_GRANTED) { 13070 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13071 < Build.VERSION_CODES.FROYO) { 13072 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13073 + Binder.getCallingUid()); 13074 return; 13075 } 13076 mContext.enforceCallingOrSelfPermission( 13077 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13078 } 13079 } 13080 13081 int user = UserHandle.getCallingUserId(); 13082 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13083 scheduleWritePackageRestrictionsLocked(user); 13084 } 13085 } 13086 } 13087 13088 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13089 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13090 ArrayList<PreferredActivity> removed = null; 13091 boolean changed = false; 13092 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13093 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13094 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13095 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13096 continue; 13097 } 13098 Iterator<PreferredActivity> it = pir.filterIterator(); 13099 while (it.hasNext()) { 13100 PreferredActivity pa = it.next(); 13101 // Mark entry for removal only if it matches the package name 13102 // and the entry is of type "always". 13103 if (packageName == null || 13104 (pa.mPref.mComponent.getPackageName().equals(packageName) 13105 && pa.mPref.mAlways)) { 13106 if (removed == null) { 13107 removed = new ArrayList<PreferredActivity>(); 13108 } 13109 removed.add(pa); 13110 } 13111 } 13112 if (removed != null) { 13113 for (int j=0; j<removed.size(); j++) { 13114 PreferredActivity pa = removed.get(j); 13115 pir.removeFilter(pa); 13116 } 13117 changed = true; 13118 } 13119 } 13120 return changed; 13121 } 13122 13123 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13124 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13125 if (userId == UserHandle.USER_ALL) { 13126 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13127 sUserManager.getUserIds())) { 13128 for (int oneUserId : sUserManager.getUserIds()) { 13129 scheduleWritePackageRestrictionsLocked(oneUserId); 13130 } 13131 } 13132 } else { 13133 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13134 scheduleWritePackageRestrictionsLocked(userId); 13135 } 13136 } 13137 } 13138 13139 13140 void clearDefaultBrowserIfNeeded(String packageName) { 13141 for (int oneUserId : sUserManager.getUserIds()) { 13142 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13143 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13144 if (packageName.equals(defaultBrowserPackageName)) { 13145 setDefaultBrowserPackageName(null, oneUserId); 13146 } 13147 } 13148 } 13149 13150 @Override 13151 public void resetPreferredActivities(int userId) { 13152 /* TODO: Actually use userId. Why is it being passed in? */ 13153 mContext.enforceCallingOrSelfPermission( 13154 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13155 // writer 13156 synchronized (mPackages) { 13157 int user = UserHandle.getCallingUserId(); 13158 clearPackagePreferredActivitiesLPw(null, user); 13159 mSettings.readDefaultPreferredAppsLPw(this, user); 13160 scheduleWritePackageRestrictionsLocked(user); 13161 } 13162 } 13163 13164 @Override 13165 public int getPreferredActivities(List<IntentFilter> outFilters, 13166 List<ComponentName> outActivities, String packageName) { 13167 13168 int num = 0; 13169 final int userId = UserHandle.getCallingUserId(); 13170 // reader 13171 synchronized (mPackages) { 13172 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13173 if (pir != null) { 13174 final Iterator<PreferredActivity> it = pir.filterIterator(); 13175 while (it.hasNext()) { 13176 final PreferredActivity pa = it.next(); 13177 if (packageName == null 13178 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13179 && pa.mPref.mAlways)) { 13180 if (outFilters != null) { 13181 outFilters.add(new IntentFilter(pa)); 13182 } 13183 if (outActivities != null) { 13184 outActivities.add(pa.mPref.mComponent); 13185 } 13186 } 13187 } 13188 } 13189 } 13190 13191 return num; 13192 } 13193 13194 @Override 13195 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13196 int userId) { 13197 int callingUid = Binder.getCallingUid(); 13198 if (callingUid != Process.SYSTEM_UID) { 13199 throw new SecurityException( 13200 "addPersistentPreferredActivity can only be run by the system"); 13201 } 13202 if (filter.countActions() == 0) { 13203 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13204 return; 13205 } 13206 synchronized (mPackages) { 13207 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13208 " :"); 13209 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13210 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13211 new PersistentPreferredActivity(filter, activity)); 13212 scheduleWritePackageRestrictionsLocked(userId); 13213 } 13214 } 13215 13216 @Override 13217 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13218 int callingUid = Binder.getCallingUid(); 13219 if (callingUid != Process.SYSTEM_UID) { 13220 throw new SecurityException( 13221 "clearPackagePersistentPreferredActivities can only be run by the system"); 13222 } 13223 ArrayList<PersistentPreferredActivity> removed = null; 13224 boolean changed = false; 13225 synchronized (mPackages) { 13226 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13227 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13228 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13229 .valueAt(i); 13230 if (userId != thisUserId) { 13231 continue; 13232 } 13233 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13234 while (it.hasNext()) { 13235 PersistentPreferredActivity ppa = it.next(); 13236 // Mark entry for removal only if it matches the package name. 13237 if (ppa.mComponent.getPackageName().equals(packageName)) { 13238 if (removed == null) { 13239 removed = new ArrayList<PersistentPreferredActivity>(); 13240 } 13241 removed.add(ppa); 13242 } 13243 } 13244 if (removed != null) { 13245 for (int j=0; j<removed.size(); j++) { 13246 PersistentPreferredActivity ppa = removed.get(j); 13247 ppir.removeFilter(ppa); 13248 } 13249 changed = true; 13250 } 13251 } 13252 13253 if (changed) { 13254 scheduleWritePackageRestrictionsLocked(userId); 13255 } 13256 } 13257 } 13258 13259 /** 13260 * Non-Binder method, support for the backup/restore mechanism: write the 13261 * full set of preferred activities in its canonical XML format. Returns true 13262 * on success; false otherwise. 13263 */ 13264 @Override 13265 public byte[] getPreferredActivityBackup(int userId) { 13266 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13267 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13268 } 13269 13270 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13271 try { 13272 final XmlSerializer serializer = new FastXmlSerializer(); 13273 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13274 serializer.startDocument(null, true); 13275 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13276 13277 synchronized (mPackages) { 13278 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13279 } 13280 13281 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13282 serializer.endDocument(); 13283 serializer.flush(); 13284 } catch (Exception e) { 13285 if (DEBUG_BACKUP) { 13286 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13287 } 13288 return null; 13289 } 13290 13291 return dataStream.toByteArray(); 13292 } 13293 13294 @Override 13295 public void restorePreferredActivities(byte[] backup, int userId) { 13296 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13297 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13298 } 13299 13300 try { 13301 final XmlPullParser parser = Xml.newPullParser(); 13302 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13303 13304 int type; 13305 while ((type = parser.next()) != XmlPullParser.START_TAG 13306 && type != XmlPullParser.END_DOCUMENT) { 13307 } 13308 if (type != XmlPullParser.START_TAG) { 13309 // oops didn't find a start tag?! 13310 if (DEBUG_BACKUP) { 13311 Slog.e(TAG, "Didn't find start tag during restore"); 13312 } 13313 return; 13314 } 13315 13316 // this is supposed to be TAG_PREFERRED_BACKUP 13317 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13318 if (DEBUG_BACKUP) { 13319 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13320 } 13321 return; 13322 } 13323 13324 // skip interfering stuff, then we're aligned with the backing implementation 13325 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13326 synchronized (mPackages) { 13327 mSettings.readPreferredActivitiesLPw(parser, userId); 13328 } 13329 } catch (Exception e) { 13330 if (DEBUG_BACKUP) { 13331 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13332 } 13333 } 13334 } 13335 13336 @Override 13337 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13338 int sourceUserId, int targetUserId, int flags) { 13339 mContext.enforceCallingOrSelfPermission( 13340 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13341 int callingUid = Binder.getCallingUid(); 13342 enforceOwnerRights(ownerPackage, callingUid); 13343 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13344 if (intentFilter.countActions() == 0) { 13345 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13346 return; 13347 } 13348 synchronized (mPackages) { 13349 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13350 ownerPackage, targetUserId, flags); 13351 CrossProfileIntentResolver resolver = 13352 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13353 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13354 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13355 if (existing != null) { 13356 int size = existing.size(); 13357 for (int i = 0; i < size; i++) { 13358 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13359 return; 13360 } 13361 } 13362 } 13363 resolver.addFilter(newFilter); 13364 scheduleWritePackageRestrictionsLocked(sourceUserId); 13365 } 13366 } 13367 13368 @Override 13369 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13370 mContext.enforceCallingOrSelfPermission( 13371 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13372 int callingUid = Binder.getCallingUid(); 13373 enforceOwnerRights(ownerPackage, callingUid); 13374 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13375 synchronized (mPackages) { 13376 CrossProfileIntentResolver resolver = 13377 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13378 ArraySet<CrossProfileIntentFilter> set = 13379 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13380 for (CrossProfileIntentFilter filter : set) { 13381 if (filter.getOwnerPackage().equals(ownerPackage)) { 13382 resolver.removeFilter(filter); 13383 } 13384 } 13385 scheduleWritePackageRestrictionsLocked(sourceUserId); 13386 } 13387 } 13388 13389 // Enforcing that callingUid is owning pkg on userId 13390 private void enforceOwnerRights(String pkg, int callingUid) { 13391 // The system owns everything. 13392 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13393 return; 13394 } 13395 int callingUserId = UserHandle.getUserId(callingUid); 13396 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13397 if (pi == null) { 13398 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13399 + callingUserId); 13400 } 13401 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13402 throw new SecurityException("Calling uid " + callingUid 13403 + " does not own package " + pkg); 13404 } 13405 } 13406 13407 @Override 13408 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13409 Intent intent = new Intent(Intent.ACTION_MAIN); 13410 intent.addCategory(Intent.CATEGORY_HOME); 13411 13412 final int callingUserId = UserHandle.getCallingUserId(); 13413 List<ResolveInfo> list = queryIntentActivities(intent, null, 13414 PackageManager.GET_META_DATA, callingUserId); 13415 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13416 true, false, false, callingUserId); 13417 13418 allHomeCandidates.clear(); 13419 if (list != null) { 13420 for (ResolveInfo ri : list) { 13421 allHomeCandidates.add(ri); 13422 } 13423 } 13424 return (preferred == null || preferred.activityInfo == null) 13425 ? null 13426 : new ComponentName(preferred.activityInfo.packageName, 13427 preferred.activityInfo.name); 13428 } 13429 13430 @Override 13431 public void setApplicationEnabledSetting(String appPackageName, 13432 int newState, int flags, int userId, String callingPackage) { 13433 if (!sUserManager.exists(userId)) return; 13434 if (callingPackage == null) { 13435 callingPackage = Integer.toString(Binder.getCallingUid()); 13436 } 13437 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13438 } 13439 13440 @Override 13441 public void setComponentEnabledSetting(ComponentName componentName, 13442 int newState, int flags, int userId) { 13443 if (!sUserManager.exists(userId)) return; 13444 setEnabledSetting(componentName.getPackageName(), 13445 componentName.getClassName(), newState, flags, userId, null); 13446 } 13447 13448 private void setEnabledSetting(final String packageName, String className, int newState, 13449 final int flags, int userId, String callingPackage) { 13450 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13451 || newState == COMPONENT_ENABLED_STATE_ENABLED 13452 || newState == COMPONENT_ENABLED_STATE_DISABLED 13453 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13454 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13455 throw new IllegalArgumentException("Invalid new component state: " 13456 + newState); 13457 } 13458 PackageSetting pkgSetting; 13459 final int uid = Binder.getCallingUid(); 13460 final int permission = mContext.checkCallingOrSelfPermission( 13461 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13462 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13463 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13464 boolean sendNow = false; 13465 boolean isApp = (className == null); 13466 String componentName = isApp ? packageName : className; 13467 int packageUid = -1; 13468 ArrayList<String> components; 13469 13470 // writer 13471 synchronized (mPackages) { 13472 pkgSetting = mSettings.mPackages.get(packageName); 13473 if (pkgSetting == null) { 13474 if (className == null) { 13475 throw new IllegalArgumentException( 13476 "Unknown package: " + packageName); 13477 } 13478 throw new IllegalArgumentException( 13479 "Unknown component: " + packageName 13480 + "/" + className); 13481 } 13482 // Allow root and verify that userId is not being specified by a different user 13483 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13484 throw new SecurityException( 13485 "Permission Denial: attempt to change component state from pid=" 13486 + Binder.getCallingPid() 13487 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13488 } 13489 if (className == null) { 13490 // We're dealing with an application/package level state change 13491 if (pkgSetting.getEnabled(userId) == newState) { 13492 // Nothing to do 13493 return; 13494 } 13495 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13496 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13497 // Don't care about who enables an app. 13498 callingPackage = null; 13499 } 13500 pkgSetting.setEnabled(newState, userId, callingPackage); 13501 // pkgSetting.pkg.mSetEnabled = newState; 13502 } else { 13503 // We're dealing with a component level state change 13504 // First, verify that this is a valid class name. 13505 PackageParser.Package pkg = pkgSetting.pkg; 13506 if (pkg == null || !pkg.hasComponentClassName(className)) { 13507 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13508 throw new IllegalArgumentException("Component class " + className 13509 + " does not exist in " + packageName); 13510 } else { 13511 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13512 + className + " does not exist in " + packageName); 13513 } 13514 } 13515 switch (newState) { 13516 case COMPONENT_ENABLED_STATE_ENABLED: 13517 if (!pkgSetting.enableComponentLPw(className, userId)) { 13518 return; 13519 } 13520 break; 13521 case COMPONENT_ENABLED_STATE_DISABLED: 13522 if (!pkgSetting.disableComponentLPw(className, userId)) { 13523 return; 13524 } 13525 break; 13526 case COMPONENT_ENABLED_STATE_DEFAULT: 13527 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13528 return; 13529 } 13530 break; 13531 default: 13532 Slog.e(TAG, "Invalid new component state: " + newState); 13533 return; 13534 } 13535 } 13536 scheduleWritePackageRestrictionsLocked(userId); 13537 components = mPendingBroadcasts.get(userId, packageName); 13538 final boolean newPackage = components == null; 13539 if (newPackage) { 13540 components = new ArrayList<String>(); 13541 } 13542 if (!components.contains(componentName)) { 13543 components.add(componentName); 13544 } 13545 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13546 sendNow = true; 13547 // Purge entry from pending broadcast list if another one exists already 13548 // since we are sending one right away. 13549 mPendingBroadcasts.remove(userId, packageName); 13550 } else { 13551 if (newPackage) { 13552 mPendingBroadcasts.put(userId, packageName, components); 13553 } 13554 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13555 // Schedule a message 13556 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13557 } 13558 } 13559 } 13560 13561 long callingId = Binder.clearCallingIdentity(); 13562 try { 13563 if (sendNow) { 13564 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13565 sendPackageChangedBroadcast(packageName, 13566 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13567 } 13568 } finally { 13569 Binder.restoreCallingIdentity(callingId); 13570 } 13571 } 13572 13573 private void sendPackageChangedBroadcast(String packageName, 13574 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13575 if (DEBUG_INSTALL) 13576 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13577 + componentNames); 13578 Bundle extras = new Bundle(4); 13579 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13580 String nameList[] = new String[componentNames.size()]; 13581 componentNames.toArray(nameList); 13582 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13583 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13584 extras.putInt(Intent.EXTRA_UID, packageUid); 13585 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13586 new int[] {UserHandle.getUserId(packageUid)}); 13587 } 13588 13589 @Override 13590 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13591 if (!sUserManager.exists(userId)) return; 13592 final int uid = Binder.getCallingUid(); 13593 final int permission = mContext.checkCallingOrSelfPermission( 13594 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13595 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13596 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13597 // writer 13598 synchronized (mPackages) { 13599 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13600 allowedByPermission, uid, userId)) { 13601 scheduleWritePackageRestrictionsLocked(userId); 13602 } 13603 } 13604 } 13605 13606 @Override 13607 public String getInstallerPackageName(String packageName) { 13608 // reader 13609 synchronized (mPackages) { 13610 return mSettings.getInstallerPackageNameLPr(packageName); 13611 } 13612 } 13613 13614 @Override 13615 public int getApplicationEnabledSetting(String packageName, int userId) { 13616 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13617 int uid = Binder.getCallingUid(); 13618 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13619 // reader 13620 synchronized (mPackages) { 13621 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13622 } 13623 } 13624 13625 @Override 13626 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13627 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13628 int uid = Binder.getCallingUid(); 13629 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13630 // reader 13631 synchronized (mPackages) { 13632 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13633 } 13634 } 13635 13636 @Override 13637 public void enterSafeMode() { 13638 enforceSystemOrRoot("Only the system can request entering safe mode"); 13639 13640 if (!mSystemReady) { 13641 mSafeMode = true; 13642 } 13643 } 13644 13645 @Override 13646 public void systemReady() { 13647 mSystemReady = true; 13648 13649 // Read the compatibilty setting when the system is ready. 13650 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13651 mContext.getContentResolver(), 13652 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13653 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13654 if (DEBUG_SETTINGS) { 13655 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13656 } 13657 13658 synchronized (mPackages) { 13659 // Verify that all of the preferred activity components actually 13660 // exist. It is possible for applications to be updated and at 13661 // that point remove a previously declared activity component that 13662 // had been set as a preferred activity. We try to clean this up 13663 // the next time we encounter that preferred activity, but it is 13664 // possible for the user flow to never be able to return to that 13665 // situation so here we do a sanity check to make sure we haven't 13666 // left any junk around. 13667 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13668 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13669 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13670 removed.clear(); 13671 for (PreferredActivity pa : pir.filterSet()) { 13672 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13673 removed.add(pa); 13674 } 13675 } 13676 if (removed.size() > 0) { 13677 for (int r=0; r<removed.size(); r++) { 13678 PreferredActivity pa = removed.get(r); 13679 Slog.w(TAG, "Removing dangling preferred activity: " 13680 + pa.mPref.mComponent); 13681 pir.removeFilter(pa); 13682 } 13683 mSettings.writePackageRestrictionsLPr( 13684 mSettings.mPreferredActivities.keyAt(i)); 13685 } 13686 } 13687 } 13688 sUserManager.systemReady(); 13689 13690 // Kick off any messages waiting for system ready 13691 if (mPostSystemReadyMessages != null) { 13692 for (Message msg : mPostSystemReadyMessages) { 13693 msg.sendToTarget(); 13694 } 13695 mPostSystemReadyMessages = null; 13696 } 13697 13698 // Watch for external volumes that come and go over time 13699 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13700 storage.registerListener(mStorageListener); 13701 13702 mInstallerService.systemReady(); 13703 mPackageDexOptimizer.systemReady(); 13704 } 13705 13706 @Override 13707 public boolean isSafeMode() { 13708 return mSafeMode; 13709 } 13710 13711 @Override 13712 public boolean hasSystemUidErrors() { 13713 return mHasSystemUidErrors; 13714 } 13715 13716 static String arrayToString(int[] array) { 13717 StringBuffer buf = new StringBuffer(128); 13718 buf.append('['); 13719 if (array != null) { 13720 for (int i=0; i<array.length; i++) { 13721 if (i > 0) buf.append(", "); 13722 buf.append(array[i]); 13723 } 13724 } 13725 buf.append(']'); 13726 return buf.toString(); 13727 } 13728 13729 static class DumpState { 13730 public static final int DUMP_LIBS = 1 << 0; 13731 public static final int DUMP_FEATURES = 1 << 1; 13732 public static final int DUMP_RESOLVERS = 1 << 2; 13733 public static final int DUMP_PERMISSIONS = 1 << 3; 13734 public static final int DUMP_PACKAGES = 1 << 4; 13735 public static final int DUMP_SHARED_USERS = 1 << 5; 13736 public static final int DUMP_MESSAGES = 1 << 6; 13737 public static final int DUMP_PROVIDERS = 1 << 7; 13738 public static final int DUMP_VERIFIERS = 1 << 8; 13739 public static final int DUMP_PREFERRED = 1 << 9; 13740 public static final int DUMP_PREFERRED_XML = 1 << 10; 13741 public static final int DUMP_KEYSETS = 1 << 11; 13742 public static final int DUMP_VERSION = 1 << 12; 13743 public static final int DUMP_INSTALLS = 1 << 13; 13744 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13745 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13746 13747 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13748 13749 private int mTypes; 13750 13751 private int mOptions; 13752 13753 private boolean mTitlePrinted; 13754 13755 private SharedUserSetting mSharedUser; 13756 13757 public boolean isDumping(int type) { 13758 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13759 return true; 13760 } 13761 13762 return (mTypes & type) != 0; 13763 } 13764 13765 public void setDump(int type) { 13766 mTypes |= type; 13767 } 13768 13769 public boolean isOptionEnabled(int option) { 13770 return (mOptions & option) != 0; 13771 } 13772 13773 public void setOptionEnabled(int option) { 13774 mOptions |= option; 13775 } 13776 13777 public boolean onTitlePrinted() { 13778 final boolean printed = mTitlePrinted; 13779 mTitlePrinted = true; 13780 return printed; 13781 } 13782 13783 public boolean getTitlePrinted() { 13784 return mTitlePrinted; 13785 } 13786 13787 public void setTitlePrinted(boolean enabled) { 13788 mTitlePrinted = enabled; 13789 } 13790 13791 public SharedUserSetting getSharedUser() { 13792 return mSharedUser; 13793 } 13794 13795 public void setSharedUser(SharedUserSetting user) { 13796 mSharedUser = user; 13797 } 13798 } 13799 13800 @Override 13801 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13802 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13803 != PackageManager.PERMISSION_GRANTED) { 13804 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13805 + Binder.getCallingPid() 13806 + ", uid=" + Binder.getCallingUid() 13807 + " without permission " 13808 + android.Manifest.permission.DUMP); 13809 return; 13810 } 13811 13812 DumpState dumpState = new DumpState(); 13813 boolean fullPreferred = false; 13814 boolean checkin = false; 13815 13816 String packageName = null; 13817 13818 int opti = 0; 13819 while (opti < args.length) { 13820 String opt = args[opti]; 13821 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13822 break; 13823 } 13824 opti++; 13825 13826 if ("-a".equals(opt)) { 13827 // Right now we only know how to print all. 13828 } else if ("-h".equals(opt)) { 13829 pw.println("Package manager dump options:"); 13830 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13831 pw.println(" --checkin: dump for a checkin"); 13832 pw.println(" -f: print details of intent filters"); 13833 pw.println(" -h: print this help"); 13834 pw.println(" cmd may be one of:"); 13835 pw.println(" l[ibraries]: list known shared libraries"); 13836 pw.println(" f[ibraries]: list device features"); 13837 pw.println(" k[eysets]: print known keysets"); 13838 pw.println(" r[esolvers]: dump intent resolvers"); 13839 pw.println(" perm[issions]: dump permissions"); 13840 pw.println(" pref[erred]: print preferred package settings"); 13841 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13842 pw.println(" prov[iders]: dump content providers"); 13843 pw.println(" p[ackages]: dump installed packages"); 13844 pw.println(" s[hared-users]: dump shared user IDs"); 13845 pw.println(" m[essages]: print collected runtime messages"); 13846 pw.println(" v[erifiers]: print package verifier info"); 13847 pw.println(" version: print database version info"); 13848 pw.println(" write: write current settings now"); 13849 pw.println(" <package.name>: info about given package"); 13850 pw.println(" installs: details about install sessions"); 13851 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13852 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13853 return; 13854 } else if ("--checkin".equals(opt)) { 13855 checkin = true; 13856 } else if ("-f".equals(opt)) { 13857 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13858 } else { 13859 pw.println("Unknown argument: " + opt + "; use -h for help"); 13860 } 13861 } 13862 13863 // Is the caller requesting to dump a particular piece of data? 13864 if (opti < args.length) { 13865 String cmd = args[opti]; 13866 opti++; 13867 // Is this a package name? 13868 if ("android".equals(cmd) || cmd.contains(".")) { 13869 packageName = cmd; 13870 // When dumping a single package, we always dump all of its 13871 // filter information since the amount of data will be reasonable. 13872 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13873 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13874 dumpState.setDump(DumpState.DUMP_LIBS); 13875 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13876 dumpState.setDump(DumpState.DUMP_FEATURES); 13877 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13878 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13879 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13880 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13881 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13882 dumpState.setDump(DumpState.DUMP_PREFERRED); 13883 } else if ("preferred-xml".equals(cmd)) { 13884 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13885 if (opti < args.length && "--full".equals(args[opti])) { 13886 fullPreferred = true; 13887 opti++; 13888 } 13889 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13890 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13891 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13892 dumpState.setDump(DumpState.DUMP_PACKAGES); 13893 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13894 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13895 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13896 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13897 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13898 dumpState.setDump(DumpState.DUMP_MESSAGES); 13899 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13900 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13901 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13902 || "intent-filter-verifiers".equals(cmd)) { 13903 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13904 } else if ("version".equals(cmd)) { 13905 dumpState.setDump(DumpState.DUMP_VERSION); 13906 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13907 dumpState.setDump(DumpState.DUMP_KEYSETS); 13908 } else if ("installs".equals(cmd)) { 13909 dumpState.setDump(DumpState.DUMP_INSTALLS); 13910 } else if ("write".equals(cmd)) { 13911 synchronized (mPackages) { 13912 mSettings.writeLPr(); 13913 pw.println("Settings written."); 13914 return; 13915 } 13916 } 13917 } 13918 13919 if (checkin) { 13920 pw.println("vers,1"); 13921 } 13922 13923 // reader 13924 synchronized (mPackages) { 13925 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13926 if (!checkin) { 13927 if (dumpState.onTitlePrinted()) 13928 pw.println(); 13929 pw.println("Database versions:"); 13930 pw.print(" SDK Version:"); 13931 pw.print(" internal="); 13932 pw.print(mSettings.mInternalSdkPlatform); 13933 pw.print(" external="); 13934 pw.println(mSettings.mExternalSdkPlatform); 13935 pw.print(" DB Version:"); 13936 pw.print(" internal="); 13937 pw.print(mSettings.mInternalDatabaseVersion); 13938 pw.print(" external="); 13939 pw.println(mSettings.mExternalDatabaseVersion); 13940 } 13941 } 13942 13943 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13944 if (!checkin) { 13945 if (dumpState.onTitlePrinted()) 13946 pw.println(); 13947 pw.println("Verifiers:"); 13948 pw.print(" Required: "); 13949 pw.print(mRequiredVerifierPackage); 13950 pw.print(" (uid="); 13951 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13952 pw.println(")"); 13953 } else if (mRequiredVerifierPackage != null) { 13954 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13955 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13956 } 13957 } 13958 13959 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13960 packageName == null) { 13961 if (mIntentFilterVerifierComponent != null) { 13962 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13963 if (!checkin) { 13964 if (dumpState.onTitlePrinted()) 13965 pw.println(); 13966 pw.println("Intent Filter Verifier:"); 13967 pw.print(" Using: "); 13968 pw.print(verifierPackageName); 13969 pw.print(" (uid="); 13970 pw.print(getPackageUid(verifierPackageName, 0)); 13971 pw.println(")"); 13972 } else if (verifierPackageName != null) { 13973 pw.print("ifv,"); pw.print(verifierPackageName); 13974 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13975 } 13976 } else { 13977 pw.println(); 13978 pw.println("No Intent Filter Verifier available!"); 13979 } 13980 } 13981 13982 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13983 boolean printedHeader = false; 13984 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13985 while (it.hasNext()) { 13986 String name = it.next(); 13987 SharedLibraryEntry ent = mSharedLibraries.get(name); 13988 if (!checkin) { 13989 if (!printedHeader) { 13990 if (dumpState.onTitlePrinted()) 13991 pw.println(); 13992 pw.println("Libraries:"); 13993 printedHeader = true; 13994 } 13995 pw.print(" "); 13996 } else { 13997 pw.print("lib,"); 13998 } 13999 pw.print(name); 14000 if (!checkin) { 14001 pw.print(" -> "); 14002 } 14003 if (ent.path != null) { 14004 if (!checkin) { 14005 pw.print("(jar) "); 14006 pw.print(ent.path); 14007 } else { 14008 pw.print(",jar,"); 14009 pw.print(ent.path); 14010 } 14011 } else { 14012 if (!checkin) { 14013 pw.print("(apk) "); 14014 pw.print(ent.apk); 14015 } else { 14016 pw.print(",apk,"); 14017 pw.print(ent.apk); 14018 } 14019 } 14020 pw.println(); 14021 } 14022 } 14023 14024 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14025 if (dumpState.onTitlePrinted()) 14026 pw.println(); 14027 if (!checkin) { 14028 pw.println("Features:"); 14029 } 14030 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14031 while (it.hasNext()) { 14032 String name = it.next(); 14033 if (!checkin) { 14034 pw.print(" "); 14035 } else { 14036 pw.print("feat,"); 14037 } 14038 pw.println(name); 14039 } 14040 } 14041 14042 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14043 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14044 : "Activity Resolver Table:", " ", packageName, 14045 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14046 dumpState.setTitlePrinted(true); 14047 } 14048 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14049 : "Receiver Resolver Table:", " ", packageName, 14050 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14051 dumpState.setTitlePrinted(true); 14052 } 14053 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14054 : "Service Resolver Table:", " ", packageName, 14055 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14056 dumpState.setTitlePrinted(true); 14057 } 14058 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14059 : "Provider Resolver Table:", " ", packageName, 14060 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14061 dumpState.setTitlePrinted(true); 14062 } 14063 } 14064 14065 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14066 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14067 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14068 int user = mSettings.mPreferredActivities.keyAt(i); 14069 if (pir.dump(pw, 14070 dumpState.getTitlePrinted() 14071 ? "\nPreferred Activities User " + user + ":" 14072 : "Preferred Activities User " + user + ":", " ", 14073 packageName, true, false)) { 14074 dumpState.setTitlePrinted(true); 14075 } 14076 } 14077 } 14078 14079 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14080 pw.flush(); 14081 FileOutputStream fout = new FileOutputStream(fd); 14082 BufferedOutputStream str = new BufferedOutputStream(fout); 14083 XmlSerializer serializer = new FastXmlSerializer(); 14084 try { 14085 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14086 serializer.startDocument(null, true); 14087 serializer.setFeature( 14088 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14089 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14090 serializer.endDocument(); 14091 serializer.flush(); 14092 } catch (IllegalArgumentException e) { 14093 pw.println("Failed writing: " + e); 14094 } catch (IllegalStateException e) { 14095 pw.println("Failed writing: " + e); 14096 } catch (IOException e) { 14097 pw.println("Failed writing: " + e); 14098 } 14099 } 14100 14101 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 14102 pw.println(); 14103 int count = mSettings.mPackages.size(); 14104 if (count == 0) { 14105 pw.println("No domain preferred apps!"); 14106 pw.println(); 14107 } else { 14108 final String prefix = " "; 14109 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14110 if (allPackageSettings.size() == 0) { 14111 pw.println("No domain preferred apps!"); 14112 pw.println(); 14113 } else { 14114 pw.println("Domain preferred apps status:"); 14115 pw.println(); 14116 count = 0; 14117 for (PackageSetting ps : allPackageSettings) { 14118 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14119 if (ivi == null || ivi.getPackageName() == null) continue; 14120 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14121 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14122 pw.println(prefix + "Status: " + ivi.getStatusString()); 14123 pw.println(); 14124 count++; 14125 } 14126 if (count == 0) { 14127 pw.println(prefix + "No domain preferred app status!"); 14128 pw.println(); 14129 } 14130 for (int userId : sUserManager.getUserIds()) { 14131 pw.println("Domain preferred apps for User " + userId + ":"); 14132 pw.println(); 14133 count = 0; 14134 for (PackageSetting ps : allPackageSettings) { 14135 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14136 if (ivi == null || ivi.getPackageName() == null) { 14137 continue; 14138 } 14139 final int status = ps.getDomainVerificationStatusForUser(userId); 14140 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14141 continue; 14142 } 14143 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14144 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14145 String statusStr = IntentFilterVerificationInfo. 14146 getStatusStringFromValue(status); 14147 pw.println(prefix + "Status: " + statusStr); 14148 pw.println(); 14149 count++; 14150 } 14151 if (count == 0) { 14152 pw.println(prefix + "No domain preferred apps!"); 14153 pw.println(); 14154 } 14155 } 14156 } 14157 } 14158 } 14159 14160 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14161 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14162 if (packageName == null) { 14163 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14164 if (iperm == 0) { 14165 if (dumpState.onTitlePrinted()) 14166 pw.println(); 14167 pw.println("AppOp Permissions:"); 14168 } 14169 pw.print(" AppOp Permission "); 14170 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14171 pw.println(":"); 14172 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14173 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14174 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14175 } 14176 } 14177 } 14178 } 14179 14180 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14181 boolean printedSomething = false; 14182 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14183 if (packageName != null && !packageName.equals(p.info.packageName)) { 14184 continue; 14185 } 14186 if (!printedSomething) { 14187 if (dumpState.onTitlePrinted()) 14188 pw.println(); 14189 pw.println("Registered ContentProviders:"); 14190 printedSomething = true; 14191 } 14192 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14193 pw.print(" "); pw.println(p.toString()); 14194 } 14195 printedSomething = false; 14196 for (Map.Entry<String, PackageParser.Provider> entry : 14197 mProvidersByAuthority.entrySet()) { 14198 PackageParser.Provider p = entry.getValue(); 14199 if (packageName != null && !packageName.equals(p.info.packageName)) { 14200 continue; 14201 } 14202 if (!printedSomething) { 14203 if (dumpState.onTitlePrinted()) 14204 pw.println(); 14205 pw.println("ContentProvider Authorities:"); 14206 printedSomething = true; 14207 } 14208 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14209 pw.print(" "); pw.println(p.toString()); 14210 if (p.info != null && p.info.applicationInfo != null) { 14211 final String appInfo = p.info.applicationInfo.toString(); 14212 pw.print(" applicationInfo="); pw.println(appInfo); 14213 } 14214 } 14215 } 14216 14217 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14218 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14219 } 14220 14221 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14222 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14223 } 14224 14225 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14226 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14227 } 14228 14229 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14230 // XXX should handle packageName != null by dumping only install data that 14231 // the given package is involved with. 14232 if (dumpState.onTitlePrinted()) pw.println(); 14233 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14234 } 14235 14236 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14237 if (dumpState.onTitlePrinted()) pw.println(); 14238 mSettings.dumpReadMessagesLPr(pw, dumpState); 14239 14240 pw.println(); 14241 pw.println("Package warning messages:"); 14242 BufferedReader in = null; 14243 String line = null; 14244 try { 14245 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14246 while ((line = in.readLine()) != null) { 14247 if (line.contains("ignored: updated version")) continue; 14248 pw.println(line); 14249 } 14250 } catch (IOException ignored) { 14251 } finally { 14252 IoUtils.closeQuietly(in); 14253 } 14254 } 14255 14256 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14257 BufferedReader in = null; 14258 String line = null; 14259 try { 14260 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14261 while ((line = in.readLine()) != null) { 14262 if (line.contains("ignored: updated version")) continue; 14263 pw.print("msg,"); 14264 pw.println(line); 14265 } 14266 } catch (IOException ignored) { 14267 } finally { 14268 IoUtils.closeQuietly(in); 14269 } 14270 } 14271 } 14272 } 14273 14274 // ------- apps on sdcard specific code ------- 14275 static final boolean DEBUG_SD_INSTALL = false; 14276 14277 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14278 14279 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14280 14281 private boolean mMediaMounted = false; 14282 14283 static String getEncryptKey() { 14284 try { 14285 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14286 SD_ENCRYPTION_KEYSTORE_NAME); 14287 if (sdEncKey == null) { 14288 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14289 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14290 if (sdEncKey == null) { 14291 Slog.e(TAG, "Failed to create encryption keys"); 14292 return null; 14293 } 14294 } 14295 return sdEncKey; 14296 } catch (NoSuchAlgorithmException nsae) { 14297 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14298 return null; 14299 } catch (IOException ioe) { 14300 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14301 return null; 14302 } 14303 } 14304 14305 /* 14306 * Update media status on PackageManager. 14307 */ 14308 @Override 14309 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14310 int callingUid = Binder.getCallingUid(); 14311 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14312 throw new SecurityException("Media status can only be updated by the system"); 14313 } 14314 // reader; this apparently protects mMediaMounted, but should probably 14315 // be a different lock in that case. 14316 synchronized (mPackages) { 14317 Log.i(TAG, "Updating external media status from " 14318 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14319 + (mediaStatus ? "mounted" : "unmounted")); 14320 if (DEBUG_SD_INSTALL) 14321 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14322 + ", mMediaMounted=" + mMediaMounted); 14323 if (mediaStatus == mMediaMounted) { 14324 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14325 : 0, -1); 14326 mHandler.sendMessage(msg); 14327 return; 14328 } 14329 mMediaMounted = mediaStatus; 14330 } 14331 // Queue up an async operation since the package installation may take a 14332 // little while. 14333 mHandler.post(new Runnable() { 14334 public void run() { 14335 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14336 } 14337 }); 14338 } 14339 14340 /** 14341 * Called by MountService when the initial ASECs to scan are available. 14342 * Should block until all the ASEC containers are finished being scanned. 14343 */ 14344 public void scanAvailableAsecs() { 14345 updateExternalMediaStatusInner(true, false, false); 14346 if (mShouldRestoreconData) { 14347 SELinuxMMAC.setRestoreconDone(); 14348 mShouldRestoreconData = false; 14349 } 14350 } 14351 14352 /* 14353 * Collect information of applications on external media, map them against 14354 * existing containers and update information based on current mount status. 14355 * Please note that we always have to report status if reportStatus has been 14356 * set to true especially when unloading packages. 14357 */ 14358 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14359 boolean externalStorage) { 14360 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14361 int[] uidArr = EmptyArray.INT; 14362 14363 final String[] list = PackageHelper.getSecureContainerList(); 14364 if (ArrayUtils.isEmpty(list)) { 14365 Log.i(TAG, "No secure containers found"); 14366 } else { 14367 // Process list of secure containers and categorize them 14368 // as active or stale based on their package internal state. 14369 14370 // reader 14371 synchronized (mPackages) { 14372 for (String cid : list) { 14373 // Leave stages untouched for now; installer service owns them 14374 if (PackageInstallerService.isStageName(cid)) continue; 14375 14376 if (DEBUG_SD_INSTALL) 14377 Log.i(TAG, "Processing container " + cid); 14378 String pkgName = getAsecPackageName(cid); 14379 if (pkgName == null) { 14380 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14381 continue; 14382 } 14383 if (DEBUG_SD_INSTALL) 14384 Log.i(TAG, "Looking for pkg : " + pkgName); 14385 14386 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14387 if (ps == null) { 14388 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14389 continue; 14390 } 14391 14392 /* 14393 * Skip packages that are not external if we're unmounting 14394 * external storage. 14395 */ 14396 if (externalStorage && !isMounted && !isExternal(ps)) { 14397 continue; 14398 } 14399 14400 final AsecInstallArgs args = new AsecInstallArgs(cid, 14401 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14402 // The package status is changed only if the code path 14403 // matches between settings and the container id. 14404 if (ps.codePathString != null 14405 && ps.codePathString.startsWith(args.getCodePath())) { 14406 if (DEBUG_SD_INSTALL) { 14407 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14408 + " at code path: " + ps.codePathString); 14409 } 14410 14411 // We do have a valid package installed on sdcard 14412 processCids.put(args, ps.codePathString); 14413 final int uid = ps.appId; 14414 if (uid != -1) { 14415 uidArr = ArrayUtils.appendInt(uidArr, uid); 14416 } 14417 } else { 14418 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14419 + ps.codePathString); 14420 } 14421 } 14422 } 14423 14424 Arrays.sort(uidArr); 14425 } 14426 14427 // Process packages with valid entries. 14428 if (isMounted) { 14429 if (DEBUG_SD_INSTALL) 14430 Log.i(TAG, "Loading packages"); 14431 loadMediaPackages(processCids, uidArr); 14432 startCleaningPackages(); 14433 mInstallerService.onSecureContainersAvailable(); 14434 } else { 14435 if (DEBUG_SD_INSTALL) 14436 Log.i(TAG, "Unloading packages"); 14437 unloadMediaPackages(processCids, uidArr, reportStatus); 14438 } 14439 } 14440 14441 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14442 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14443 final int size = infos.size(); 14444 final String[] packageNames = new String[size]; 14445 final int[] packageUids = new int[size]; 14446 for (int i = 0; i < size; i++) { 14447 final ApplicationInfo info = infos.get(i); 14448 packageNames[i] = info.packageName; 14449 packageUids[i] = info.uid; 14450 } 14451 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14452 finishedReceiver); 14453 } 14454 14455 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14456 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14457 sendResourcesChangedBroadcast(mediaStatus, replacing, 14458 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14459 } 14460 14461 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14462 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14463 int size = pkgList.length; 14464 if (size > 0) { 14465 // Send broadcasts here 14466 Bundle extras = new Bundle(); 14467 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14468 if (uidArr != null) { 14469 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14470 } 14471 if (replacing) { 14472 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14473 } 14474 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14475 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14476 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14477 } 14478 } 14479 14480 /* 14481 * Look at potentially valid container ids from processCids If package 14482 * information doesn't match the one on record or package scanning fails, 14483 * the cid is added to list of removeCids. We currently don't delete stale 14484 * containers. 14485 */ 14486 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14487 ArrayList<String> pkgList = new ArrayList<String>(); 14488 Set<AsecInstallArgs> keys = processCids.keySet(); 14489 14490 for (AsecInstallArgs args : keys) { 14491 String codePath = processCids.get(args); 14492 if (DEBUG_SD_INSTALL) 14493 Log.i(TAG, "Loading container : " + args.cid); 14494 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14495 try { 14496 // Make sure there are no container errors first. 14497 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14498 Slog.e(TAG, "Failed to mount cid : " + args.cid 14499 + " when installing from sdcard"); 14500 continue; 14501 } 14502 // Check code path here. 14503 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14504 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14505 + " does not match one in settings " + codePath); 14506 continue; 14507 } 14508 // Parse package 14509 int parseFlags = mDefParseFlags; 14510 if (args.isExternalAsec()) { 14511 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14512 } 14513 if (args.isFwdLocked()) { 14514 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14515 } 14516 14517 synchronized (mInstallLock) { 14518 PackageParser.Package pkg = null; 14519 try { 14520 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14521 } catch (PackageManagerException e) { 14522 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14523 } 14524 // Scan the package 14525 if (pkg != null) { 14526 /* 14527 * TODO why is the lock being held? doPostInstall is 14528 * called in other places without the lock. This needs 14529 * to be straightened out. 14530 */ 14531 // writer 14532 synchronized (mPackages) { 14533 retCode = PackageManager.INSTALL_SUCCEEDED; 14534 pkgList.add(pkg.packageName); 14535 // Post process args 14536 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14537 pkg.applicationInfo.uid); 14538 } 14539 } else { 14540 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14541 } 14542 } 14543 14544 } finally { 14545 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14546 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14547 } 14548 } 14549 } 14550 // writer 14551 synchronized (mPackages) { 14552 // If the platform SDK has changed since the last time we booted, 14553 // we need to re-grant app permission to catch any new ones that 14554 // appear. This is really a hack, and means that apps can in some 14555 // cases get permissions that the user didn't initially explicitly 14556 // allow... it would be nice to have some better way to handle 14557 // this situation. 14558 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14559 if (regrantPermissions) 14560 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14561 + mSdkVersion + "; regranting permissions for external storage"); 14562 mSettings.mExternalSdkPlatform = mSdkVersion; 14563 14564 // Make sure group IDs have been assigned, and any permission 14565 // changes in other apps are accounted for 14566 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14567 | (regrantPermissions 14568 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14569 : 0)); 14570 14571 mSettings.updateExternalDatabaseVersion(); 14572 14573 // can downgrade to reader 14574 // Persist settings 14575 mSettings.writeLPr(); 14576 } 14577 // Send a broadcast to let everyone know we are done processing 14578 if (pkgList.size() > 0) { 14579 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14580 } 14581 } 14582 14583 /* 14584 * Utility method to unload a list of specified containers 14585 */ 14586 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14587 // Just unmount all valid containers. 14588 for (AsecInstallArgs arg : cidArgs) { 14589 synchronized (mInstallLock) { 14590 arg.doPostDeleteLI(false); 14591 } 14592 } 14593 } 14594 14595 /* 14596 * Unload packages mounted on external media. This involves deleting package 14597 * data from internal structures, sending broadcasts about diabled packages, 14598 * gc'ing to free up references, unmounting all secure containers 14599 * corresponding to packages on external media, and posting a 14600 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14601 * that we always have to post this message if status has been requested no 14602 * matter what. 14603 */ 14604 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14605 final boolean reportStatus) { 14606 if (DEBUG_SD_INSTALL) 14607 Log.i(TAG, "unloading media packages"); 14608 ArrayList<String> pkgList = new ArrayList<String>(); 14609 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14610 final Set<AsecInstallArgs> keys = processCids.keySet(); 14611 for (AsecInstallArgs args : keys) { 14612 String pkgName = args.getPackageName(); 14613 if (DEBUG_SD_INSTALL) 14614 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14615 // Delete package internally 14616 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14617 synchronized (mInstallLock) { 14618 boolean res = deletePackageLI(pkgName, null, false, null, null, 14619 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14620 if (res) { 14621 pkgList.add(pkgName); 14622 } else { 14623 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14624 failedList.add(args); 14625 } 14626 } 14627 } 14628 14629 // reader 14630 synchronized (mPackages) { 14631 // We didn't update the settings after removing each package; 14632 // write them now for all packages. 14633 mSettings.writeLPr(); 14634 } 14635 14636 // We have to absolutely send UPDATED_MEDIA_STATUS only 14637 // after confirming that all the receivers processed the ordered 14638 // broadcast when packages get disabled, force a gc to clean things up. 14639 // and unload all the containers. 14640 if (pkgList.size() > 0) { 14641 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14642 new IIntentReceiver.Stub() { 14643 public void performReceive(Intent intent, int resultCode, String data, 14644 Bundle extras, boolean ordered, boolean sticky, 14645 int sendingUser) throws RemoteException { 14646 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14647 reportStatus ? 1 : 0, 1, keys); 14648 mHandler.sendMessage(msg); 14649 } 14650 }); 14651 } else { 14652 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14653 keys); 14654 mHandler.sendMessage(msg); 14655 } 14656 } 14657 14658 private void loadPrivatePackages(VolumeInfo vol) { 14659 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14660 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14661 synchronized (mInstallLock) { 14662 synchronized (mPackages) { 14663 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14664 for (PackageSetting ps : packages) { 14665 final PackageParser.Package pkg; 14666 try { 14667 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14668 loaded.add(pkg.applicationInfo); 14669 } catch (PackageManagerException e) { 14670 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14671 } 14672 } 14673 14674 // TODO: regrant any permissions that changed based since original install 14675 14676 mSettings.writeLPr(); 14677 } 14678 } 14679 14680 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14681 sendResourcesChangedBroadcast(true, false, loaded, null); 14682 } 14683 14684 private void unloadPrivatePackages(VolumeInfo vol) { 14685 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14686 synchronized (mInstallLock) { 14687 synchronized (mPackages) { 14688 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14689 for (PackageSetting ps : packages) { 14690 if (ps.pkg == null) continue; 14691 14692 final ApplicationInfo info = ps.pkg.applicationInfo; 14693 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14694 if (deletePackageLI(ps.name, null, false, null, null, 14695 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14696 unloaded.add(info); 14697 } else { 14698 Slog.w(TAG, "Failed to unload " + ps.codePath); 14699 } 14700 } 14701 14702 mSettings.writeLPr(); 14703 } 14704 } 14705 14706 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14707 sendResourcesChangedBroadcast(false, false, unloaded, null); 14708 } 14709 14710 private void unfreezePackage(String packageName) { 14711 synchronized (mPackages) { 14712 final PackageSetting ps = mSettings.mPackages.get(packageName); 14713 if (ps != null) { 14714 ps.frozen = false; 14715 } 14716 } 14717 } 14718 14719 @Override 14720 public int movePackage(final String packageName, final String volumeUuid) { 14721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14722 14723 final int moveId = mNextMoveId.getAndIncrement(); 14724 try { 14725 movePackageInternal(packageName, volumeUuid, moveId); 14726 } catch (PackageManagerException e) { 14727 Slog.w(TAG, "Failed to move " + packageName, e); 14728 mMoveCallbacks.notifyStatusChanged(moveId, 14729 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14730 } 14731 return moveId; 14732 } 14733 14734 private void movePackageInternal(final String packageName, final String volumeUuid, 14735 final int moveId) throws PackageManagerException { 14736 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14737 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14738 final PackageManager pm = mContext.getPackageManager(); 14739 14740 final boolean currentAsec; 14741 final String currentVolumeUuid; 14742 final File codeFile; 14743 final String installerPackageName; 14744 final String packageAbiOverride; 14745 final int appId; 14746 final String seinfo; 14747 final String label; 14748 14749 // reader 14750 synchronized (mPackages) { 14751 final PackageParser.Package pkg = mPackages.get(packageName); 14752 final PackageSetting ps = mSettings.mPackages.get(packageName); 14753 if (pkg == null || ps == null) { 14754 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14755 } 14756 14757 if (pkg.applicationInfo.isSystemApp()) { 14758 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14759 "Cannot move system application"); 14760 } 14761 14762 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14763 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14764 "Package already moved to " + volumeUuid); 14765 } 14766 14767 final File probe = new File(pkg.codePath); 14768 final File probeOat = new File(probe, "oat"); 14769 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14770 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14771 "Move only supported for modern cluster style installs"); 14772 } 14773 14774 if (ps.frozen) { 14775 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14776 "Failed to move already frozen package"); 14777 } 14778 ps.frozen = true; 14779 14780 currentAsec = pkg.applicationInfo.isForwardLocked() 14781 || pkg.applicationInfo.isExternalAsec(); 14782 currentVolumeUuid = ps.volumeUuid; 14783 codeFile = new File(pkg.codePath); 14784 installerPackageName = ps.installerPackageName; 14785 packageAbiOverride = ps.cpuAbiOverrideString; 14786 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14787 seinfo = pkg.applicationInfo.seinfo; 14788 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14789 } 14790 14791 // Now that we're guarded by frozen state, kill app during move 14792 killApplication(packageName, appId, "move pkg"); 14793 14794 final Bundle extras = new Bundle(); 14795 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14796 extras.putString(Intent.EXTRA_TITLE, label); 14797 mMoveCallbacks.notifyCreated(moveId, extras); 14798 14799 int installFlags; 14800 final boolean moveCompleteApp; 14801 final File measurePath; 14802 14803 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14804 installFlags = INSTALL_INTERNAL; 14805 moveCompleteApp = !currentAsec; 14806 measurePath = Environment.getDataAppDirectory(volumeUuid); 14807 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14808 installFlags = INSTALL_EXTERNAL; 14809 moveCompleteApp = false; 14810 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14811 } else { 14812 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14813 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14814 || !volume.isMountedWritable()) { 14815 unfreezePackage(packageName); 14816 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14817 "Move location not mounted private volume"); 14818 } 14819 14820 Preconditions.checkState(!currentAsec); 14821 14822 installFlags = INSTALL_INTERNAL; 14823 moveCompleteApp = true; 14824 measurePath = Environment.getDataAppDirectory(volumeUuid); 14825 } 14826 14827 final PackageStats stats = new PackageStats(null, -1); 14828 synchronized (mInstaller) { 14829 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14830 unfreezePackage(packageName); 14831 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14832 "Failed to measure package size"); 14833 } 14834 } 14835 14836 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14837 + stats.dataSize); 14838 14839 final long startFreeBytes = measurePath.getFreeSpace(); 14840 final long sizeBytes; 14841 if (moveCompleteApp) { 14842 sizeBytes = stats.codeSize + stats.dataSize; 14843 } else { 14844 sizeBytes = stats.codeSize; 14845 } 14846 14847 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14848 unfreezePackage(packageName); 14849 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14850 "Not enough free space to move"); 14851 } 14852 14853 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14854 14855 final CountDownLatch installedLatch = new CountDownLatch(1); 14856 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14857 @Override 14858 public void onUserActionRequired(Intent intent) throws RemoteException { 14859 throw new IllegalStateException(); 14860 } 14861 14862 @Override 14863 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14864 Bundle extras) throws RemoteException { 14865 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14866 + PackageManager.installStatusToString(returnCode, msg)); 14867 14868 installedLatch.countDown(); 14869 14870 // Regardless of success or failure of the move operation, 14871 // always unfreeze the package 14872 unfreezePackage(packageName); 14873 14874 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14875 switch (status) { 14876 case PackageInstaller.STATUS_SUCCESS: 14877 mMoveCallbacks.notifyStatusChanged(moveId, 14878 PackageManager.MOVE_SUCCEEDED); 14879 break; 14880 case PackageInstaller.STATUS_FAILURE_STORAGE: 14881 mMoveCallbacks.notifyStatusChanged(moveId, 14882 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14883 break; 14884 default: 14885 mMoveCallbacks.notifyStatusChanged(moveId, 14886 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14887 break; 14888 } 14889 } 14890 }; 14891 14892 final MoveInfo move; 14893 if (moveCompleteApp) { 14894 // Kick off a thread to report progress estimates 14895 new Thread() { 14896 @Override 14897 public void run() { 14898 while (true) { 14899 try { 14900 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14901 break; 14902 } 14903 } catch (InterruptedException ignored) { 14904 } 14905 14906 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14907 final int progress = 10 + (int) MathUtils.constrain( 14908 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14909 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14910 } 14911 } 14912 }.start(); 14913 14914 final String dataAppName = codeFile.getName(); 14915 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14916 dataAppName, appId, seinfo); 14917 } else { 14918 move = null; 14919 } 14920 14921 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14922 14923 final Message msg = mHandler.obtainMessage(INIT_COPY); 14924 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14925 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14926 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14927 mHandler.sendMessage(msg); 14928 } 14929 14930 @Override 14931 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14932 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14933 14934 final int realMoveId = mNextMoveId.getAndIncrement(); 14935 final Bundle extras = new Bundle(); 14936 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14937 mMoveCallbacks.notifyCreated(realMoveId, extras); 14938 14939 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14940 @Override 14941 public void onCreated(int moveId, Bundle extras) { 14942 // Ignored 14943 } 14944 14945 @Override 14946 public void onStatusChanged(int moveId, int status, long estMillis) { 14947 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14948 } 14949 }; 14950 14951 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14952 storage.setPrimaryStorageUuid(volumeUuid, callback); 14953 return realMoveId; 14954 } 14955 14956 @Override 14957 public int getMoveStatus(int moveId) { 14958 mContext.enforceCallingOrSelfPermission( 14959 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14960 return mMoveCallbacks.mLastStatus.get(moveId); 14961 } 14962 14963 @Override 14964 public void registerMoveCallback(IPackageMoveObserver callback) { 14965 mContext.enforceCallingOrSelfPermission( 14966 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14967 mMoveCallbacks.register(callback); 14968 } 14969 14970 @Override 14971 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14972 mContext.enforceCallingOrSelfPermission( 14973 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14974 mMoveCallbacks.unregister(callback); 14975 } 14976 14977 @Override 14978 public boolean setInstallLocation(int loc) { 14979 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14980 null); 14981 if (getInstallLocation() == loc) { 14982 return true; 14983 } 14984 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14985 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14986 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14987 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14988 return true; 14989 } 14990 return false; 14991 } 14992 14993 @Override 14994 public int getInstallLocation() { 14995 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14996 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14997 PackageHelper.APP_INSTALL_AUTO); 14998 } 14999 15000 /** Called by UserManagerService */ 15001 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 15002 mDirtyUsers.remove(userHandle); 15003 mSettings.removeUserLPw(userHandle); 15004 mPendingBroadcasts.remove(userHandle); 15005 if (mInstaller != null) { 15006 // Technically, we shouldn't be doing this with the package lock 15007 // held. However, this is very rare, and there is already so much 15008 // other disk I/O going on, that we'll let it slide for now. 15009 final StorageManager storage = StorageManager.from(mContext); 15010 final List<VolumeInfo> vols = storage.getVolumes(); 15011 for (VolumeInfo vol : vols) { 15012 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15013 final String volumeUuid = vol.getFsUuid(); 15014 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15015 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15016 } 15017 } 15018 } 15019 mUserNeedsBadging.delete(userHandle); 15020 removeUnusedPackagesLILPw(userManager, userHandle); 15021 } 15022 15023 /** 15024 * We're removing userHandle and would like to remove any downloaded packages 15025 * that are no longer in use by any other user. 15026 * @param userHandle the user being removed 15027 */ 15028 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15029 final boolean DEBUG_CLEAN_APKS = false; 15030 int [] users = userManager.getUserIdsLPr(); 15031 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15032 while (psit.hasNext()) { 15033 PackageSetting ps = psit.next(); 15034 if (ps.pkg == null) { 15035 continue; 15036 } 15037 final String packageName = ps.pkg.packageName; 15038 // Skip over if system app 15039 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15040 continue; 15041 } 15042 if (DEBUG_CLEAN_APKS) { 15043 Slog.i(TAG, "Checking package " + packageName); 15044 } 15045 boolean keep = false; 15046 for (int i = 0; i < users.length; i++) { 15047 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15048 keep = true; 15049 if (DEBUG_CLEAN_APKS) { 15050 Slog.i(TAG, " Keeping package " + packageName + " for user " 15051 + users[i]); 15052 } 15053 break; 15054 } 15055 } 15056 if (!keep) { 15057 if (DEBUG_CLEAN_APKS) { 15058 Slog.i(TAG, " Removing package " + packageName); 15059 } 15060 mHandler.post(new Runnable() { 15061 public void run() { 15062 deletePackageX(packageName, userHandle, 0); 15063 } //end run 15064 }); 15065 } 15066 } 15067 } 15068 15069 /** Called by UserManagerService */ 15070 void createNewUserLILPw(int userHandle, File path) { 15071 if (mInstaller != null) { 15072 mInstaller.createUserConfig(userHandle); 15073 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15074 } 15075 } 15076 15077 void newUserCreatedLILPw(int userHandle) { 15078 // Adding a user requires updating runtime permissions for system apps. 15079 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 15080 } 15081 15082 @Override 15083 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15084 mContext.enforceCallingOrSelfPermission( 15085 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15086 "Only package verification agents can read the verifier device identity"); 15087 15088 synchronized (mPackages) { 15089 return mSettings.getVerifierDeviceIdentityLPw(); 15090 } 15091 } 15092 15093 @Override 15094 public void setPermissionEnforced(String permission, boolean enforced) { 15095 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15096 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15097 synchronized (mPackages) { 15098 if (mSettings.mReadExternalStorageEnforced == null 15099 || mSettings.mReadExternalStorageEnforced != enforced) { 15100 mSettings.mReadExternalStorageEnforced = enforced; 15101 mSettings.writeLPr(); 15102 } 15103 } 15104 // kill any non-foreground processes so we restart them and 15105 // grant/revoke the GID. 15106 final IActivityManager am = ActivityManagerNative.getDefault(); 15107 if (am != null) { 15108 final long token = Binder.clearCallingIdentity(); 15109 try { 15110 am.killProcessesBelowForeground("setPermissionEnforcement"); 15111 } catch (RemoteException e) { 15112 } finally { 15113 Binder.restoreCallingIdentity(token); 15114 } 15115 } 15116 } else { 15117 throw new IllegalArgumentException("No selective enforcement for " + permission); 15118 } 15119 } 15120 15121 @Override 15122 @Deprecated 15123 public boolean isPermissionEnforced(String permission) { 15124 return true; 15125 } 15126 15127 @Override 15128 public boolean isStorageLow() { 15129 final long token = Binder.clearCallingIdentity(); 15130 try { 15131 final DeviceStorageMonitorInternal 15132 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15133 if (dsm != null) { 15134 return dsm.isMemoryLow(); 15135 } else { 15136 return false; 15137 } 15138 } finally { 15139 Binder.restoreCallingIdentity(token); 15140 } 15141 } 15142 15143 @Override 15144 public IPackageInstaller getPackageInstaller() { 15145 return mInstallerService; 15146 } 15147 15148 private boolean userNeedsBadging(int userId) { 15149 int index = mUserNeedsBadging.indexOfKey(userId); 15150 if (index < 0) { 15151 final UserInfo userInfo; 15152 final long token = Binder.clearCallingIdentity(); 15153 try { 15154 userInfo = sUserManager.getUserInfo(userId); 15155 } finally { 15156 Binder.restoreCallingIdentity(token); 15157 } 15158 final boolean b; 15159 if (userInfo != null && userInfo.isManagedProfile()) { 15160 b = true; 15161 } else { 15162 b = false; 15163 } 15164 mUserNeedsBadging.put(userId, b); 15165 return b; 15166 } 15167 return mUserNeedsBadging.valueAt(index); 15168 } 15169 15170 @Override 15171 public KeySet getKeySetByAlias(String packageName, String alias) { 15172 if (packageName == null || alias == null) { 15173 return null; 15174 } 15175 synchronized(mPackages) { 15176 final PackageParser.Package pkg = mPackages.get(packageName); 15177 if (pkg == null) { 15178 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15179 throw new IllegalArgumentException("Unknown package: " + packageName); 15180 } 15181 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15182 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15183 } 15184 } 15185 15186 @Override 15187 public KeySet getSigningKeySet(String packageName) { 15188 if (packageName == null) { 15189 return null; 15190 } 15191 synchronized(mPackages) { 15192 final PackageParser.Package pkg = mPackages.get(packageName); 15193 if (pkg == null) { 15194 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15195 throw new IllegalArgumentException("Unknown package: " + packageName); 15196 } 15197 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15198 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15199 throw new SecurityException("May not access signing KeySet of other apps."); 15200 } 15201 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15202 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15203 } 15204 } 15205 15206 @Override 15207 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15208 if (packageName == null || ks == null) { 15209 return false; 15210 } 15211 synchronized(mPackages) { 15212 final PackageParser.Package pkg = mPackages.get(packageName); 15213 if (pkg == null) { 15214 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15215 throw new IllegalArgumentException("Unknown package: " + packageName); 15216 } 15217 IBinder ksh = ks.getToken(); 15218 if (ksh instanceof KeySetHandle) { 15219 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15220 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15221 } 15222 return false; 15223 } 15224 } 15225 15226 @Override 15227 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15228 if (packageName == null || ks == null) { 15229 return false; 15230 } 15231 synchronized(mPackages) { 15232 final PackageParser.Package pkg = mPackages.get(packageName); 15233 if (pkg == null) { 15234 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15235 throw new IllegalArgumentException("Unknown package: " + packageName); 15236 } 15237 IBinder ksh = ks.getToken(); 15238 if (ksh instanceof KeySetHandle) { 15239 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15240 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15241 } 15242 return false; 15243 } 15244 } 15245 15246 public void getUsageStatsIfNoPackageUsageInfo() { 15247 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15248 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15249 if (usm == null) { 15250 throw new IllegalStateException("UsageStatsManager must be initialized"); 15251 } 15252 long now = System.currentTimeMillis(); 15253 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15254 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15255 String packageName = entry.getKey(); 15256 PackageParser.Package pkg = mPackages.get(packageName); 15257 if (pkg == null) { 15258 continue; 15259 } 15260 UsageStats usage = entry.getValue(); 15261 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15262 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15263 } 15264 } 15265 } 15266 15267 /** 15268 * Check and throw if the given before/after packages would be considered a 15269 * downgrade. 15270 */ 15271 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15272 throws PackageManagerException { 15273 if (after.versionCode < before.mVersionCode) { 15274 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15275 "Update version code " + after.versionCode + " is older than current " 15276 + before.mVersionCode); 15277 } else if (after.versionCode == before.mVersionCode) { 15278 if (after.baseRevisionCode < before.baseRevisionCode) { 15279 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15280 "Update base revision code " + after.baseRevisionCode 15281 + " is older than current " + before.baseRevisionCode); 15282 } 15283 15284 if (!ArrayUtils.isEmpty(after.splitNames)) { 15285 for (int i = 0; i < after.splitNames.length; i++) { 15286 final String splitName = after.splitNames[i]; 15287 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15288 if (j != -1) { 15289 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15290 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15291 "Update split " + splitName + " revision code " 15292 + after.splitRevisionCodes[i] + " is older than current " 15293 + before.splitRevisionCodes[j]); 15294 } 15295 } 15296 } 15297 } 15298 } 15299 } 15300 15301 private static class MoveCallbacks extends Handler { 15302 private static final int MSG_CREATED = 1; 15303 private static final int MSG_STATUS_CHANGED = 2; 15304 15305 private final RemoteCallbackList<IPackageMoveObserver> 15306 mCallbacks = new RemoteCallbackList<>(); 15307 15308 private final SparseIntArray mLastStatus = new SparseIntArray(); 15309 15310 public MoveCallbacks(Looper looper) { 15311 super(looper); 15312 } 15313 15314 public void register(IPackageMoveObserver callback) { 15315 mCallbacks.register(callback); 15316 } 15317 15318 public void unregister(IPackageMoveObserver callback) { 15319 mCallbacks.unregister(callback); 15320 } 15321 15322 @Override 15323 public void handleMessage(Message msg) { 15324 final SomeArgs args = (SomeArgs) msg.obj; 15325 final int n = mCallbacks.beginBroadcast(); 15326 for (int i = 0; i < n; i++) { 15327 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15328 try { 15329 invokeCallback(callback, msg.what, args); 15330 } catch (RemoteException ignored) { 15331 } 15332 } 15333 mCallbacks.finishBroadcast(); 15334 args.recycle(); 15335 } 15336 15337 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15338 throws RemoteException { 15339 switch (what) { 15340 case MSG_CREATED: { 15341 callback.onCreated(args.argi1, (Bundle) args.arg2); 15342 break; 15343 } 15344 case MSG_STATUS_CHANGED: { 15345 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15346 break; 15347 } 15348 } 15349 } 15350 15351 private void notifyCreated(int moveId, Bundle extras) { 15352 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15353 15354 final SomeArgs args = SomeArgs.obtain(); 15355 args.argi1 = moveId; 15356 args.arg2 = extras; 15357 obtainMessage(MSG_CREATED, args).sendToTarget(); 15358 } 15359 15360 private void notifyStatusChanged(int moveId, int status) { 15361 notifyStatusChanged(moveId, status, -1); 15362 } 15363 15364 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15365 Slog.v(TAG, "Move " + moveId + " status " + status); 15366 15367 final SomeArgs args = SomeArgs.obtain(); 15368 args.argi1 = moveId; 15369 args.argi2 = status; 15370 args.arg3 = estMillis; 15371 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15372 15373 synchronized (mLastStatus) { 15374 mLastStatus.put(moveId, status); 15375 } 15376 } 15377 } 15378 15379 private final class OnPermissionChangeListeners extends Handler { 15380 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15381 15382 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15383 new RemoteCallbackList<>(); 15384 15385 public OnPermissionChangeListeners(Looper looper) { 15386 super(looper); 15387 } 15388 15389 @Override 15390 public void handleMessage(Message msg) { 15391 switch (msg.what) { 15392 case MSG_ON_PERMISSIONS_CHANGED: { 15393 final int uid = msg.arg1; 15394 handleOnPermissionsChanged(uid); 15395 } break; 15396 } 15397 } 15398 15399 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15400 mPermissionListeners.register(listener); 15401 15402 } 15403 15404 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15405 mPermissionListeners.unregister(listener); 15406 } 15407 15408 public void onPermissionsChanged(int uid) { 15409 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15410 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15411 } 15412 } 15413 15414 private void handleOnPermissionsChanged(int uid) { 15415 final int count = mPermissionListeners.beginBroadcast(); 15416 try { 15417 for (int i = 0; i < count; i++) { 15418 IOnPermissionsChangeListener callback = mPermissionListeners 15419 .getBroadcastItem(i); 15420 try { 15421 callback.onPermissionsChanged(uid); 15422 } catch (RemoteException e) { 15423 Log.e(TAG, "Permission listener is dead", e); 15424 } 15425 } 15426 } finally { 15427 mPermissionListeners.finishBroadcast(); 15428 } 15429 } 15430 } 15431} 15432