PackageManagerService.java revision 75a0ee081fa31b75649e164a8bf79a23a3ebd060
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.RemoteCallback; 149import android.os.RemoteCallbackList; 150import android.os.RemoteException; 151import android.os.SELinux; 152import android.os.ServiceManager; 153import android.os.SystemClock; 154import android.os.SystemProperties; 155import android.os.UserHandle; 156import android.os.UserManager; 157import android.os.storage.IMountService; 158import android.os.storage.StorageEventListener; 159import android.os.storage.StorageManager; 160import android.os.storage.VolumeInfo; 161import android.os.storage.VolumeRecord; 162import android.security.KeyStore; 163import android.security.SystemKeyStore; 164import android.system.ErrnoException; 165import android.system.Os; 166import android.system.StructStat; 167import android.text.TextUtils; 168import android.text.format.DateUtils; 169import android.util.ArrayMap; 170import android.util.ArraySet; 171import android.util.AtomicFile; 172import android.util.DisplayMetrics; 173import android.util.EventLog; 174import android.util.ExceptionUtils; 175import android.util.Log; 176import android.util.LogPrinter; 177import android.util.MathUtils; 178import android.util.PrintStreamPrinter; 179import android.util.Slog; 180import android.util.SparseArray; 181import android.util.SparseBooleanArray; 182import android.util.SparseIntArray; 183import android.util.Xml; 184import android.view.Display; 185 186import dalvik.system.DexFile; 187import dalvik.system.VMRuntime; 188 189import libcore.io.IoUtils; 190import libcore.util.EmptyArray; 191 192import com.android.internal.R; 193import com.android.internal.app.IMediaContainerService; 194import com.android.internal.app.ResolverActivity; 195import com.android.internal.content.NativeLibraryHelper; 196import com.android.internal.content.PackageHelper; 197import com.android.internal.os.IParcelFileDescriptorFactory; 198import com.android.internal.os.SomeArgs; 199import com.android.internal.util.ArrayUtils; 200import com.android.internal.util.FastPrintWriter; 201import com.android.internal.util.FastXmlSerializer; 202import com.android.internal.util.IndentingPrintWriter; 203import com.android.internal.util.Preconditions; 204import com.android.server.EventLogTags; 205import com.android.server.FgThread; 206import com.android.server.IntentResolver; 207import com.android.server.LocalServices; 208import com.android.server.ServiceThread; 209import com.android.server.SystemConfig; 210import com.android.server.Watchdog; 211import com.android.server.pm.Settings.DatabaseVersion; 212import com.android.server.pm.PermissionsState.PermissionState; 213import com.android.server.storage.DeviceStorageMonitorInternal; 214 215import org.xmlpull.v1.XmlPullParser; 216import org.xmlpull.v1.XmlSerializer; 217 218import java.io.BufferedInputStream; 219import java.io.BufferedOutputStream; 220import java.io.BufferedReader; 221import java.io.ByteArrayInputStream; 222import java.io.ByteArrayOutputStream; 223import java.io.File; 224import java.io.FileDescriptor; 225import java.io.FileNotFoundException; 226import java.io.FileOutputStream; 227import java.io.FileReader; 228import java.io.FilenameFilter; 229import java.io.IOException; 230import java.io.InputStream; 231import java.io.PrintWriter; 232import java.nio.charset.StandardCharsets; 233import java.security.NoSuchAlgorithmException; 234import java.security.PublicKey; 235import java.security.cert.CertificateEncodingException; 236import java.security.cert.CertificateException; 237import java.text.SimpleDateFormat; 238import java.util.ArrayList; 239import java.util.Arrays; 240import java.util.Collection; 241import java.util.Collections; 242import java.util.Comparator; 243import java.util.Date; 244import java.util.Iterator; 245import java.util.List; 246import java.util.Map; 247import java.util.Objects; 248import java.util.Set; 249import java.util.concurrent.CountDownLatch; 250import java.util.concurrent.TimeUnit; 251import java.util.concurrent.atomic.AtomicBoolean; 252import java.util.concurrent.atomic.AtomicInteger; 253import java.util.concurrent.atomic.AtomicLong; 254 255/** 256 * Keep track of all those .apks everywhere. 257 * 258 * This is very central to the platform's security; please run the unit 259 * tests whenever making modifications here: 260 * 261mmm frameworks/base/tests/AndroidTests 262adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 263adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 264 * 265 * {@hide} 266 */ 267public class PackageManagerService extends IPackageManager.Stub { 268 static final String TAG = "PackageManager"; 269 static final boolean DEBUG_SETTINGS = false; 270 static final boolean DEBUG_PREFERRED = false; 271 static final boolean DEBUG_UPGRADE = false; 272 private static final boolean DEBUG_BACKUP = true; 273 private static final boolean DEBUG_INSTALL = false; 274 private static final boolean DEBUG_REMOVE = false; 275 private static final boolean DEBUG_BROADCASTS = false; 276 private static final boolean DEBUG_SHOW_INFO = false; 277 private static final boolean DEBUG_PACKAGE_INFO = false; 278 private static final boolean DEBUG_INTENT_MATCHING = false; 279 private static final boolean DEBUG_PACKAGE_SCANNING = false; 280 private static final boolean DEBUG_VERIFY = false; 281 private static final boolean DEBUG_DEXOPT = false; 282 private static final boolean DEBUG_ABI_SELECTION = false; 283 private static final boolean DEBUG_DOMAIN_VERIFICATION = false; 284 285 private static final int RADIO_UID = Process.PHONE_UID; 286 private static final int LOG_UID = Process.LOG_UID; 287 private static final int NFC_UID = Process.NFC_UID; 288 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 289 private static final int SHELL_UID = Process.SHELL_UID; 290 291 // Cap the size of permission trees that 3rd party apps can define 292 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 293 294 // Suffix used during package installation when copying/moving 295 // package apks to install directory. 296 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 297 298 static final int SCAN_NO_DEX = 1<<1; 299 static final int SCAN_FORCE_DEX = 1<<2; 300 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 301 static final int SCAN_NEW_INSTALL = 1<<4; 302 static final int SCAN_NO_PATHS = 1<<5; 303 static final int SCAN_UPDATE_TIME = 1<<6; 304 static final int SCAN_DEFER_DEX = 1<<7; 305 static final int SCAN_BOOTING = 1<<8; 306 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 307 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 308 static final int SCAN_REQUIRE_KNOWN = 1<<12; 309 static final int SCAN_MOVE = 1<<13; 310 311 static final int REMOVE_CHATTY = 1<<16; 312 313 private static final int[] EMPTY_INT_ARRAY = new int[0]; 314 315 /** 316 * Timeout (in milliseconds) after which the watchdog should declare that 317 * our handler thread is wedged. The usual default for such things is one 318 * minute but we sometimes do very lengthy I/O operations on this thread, 319 * such as installing multi-gigabyte applications, so ours needs to be longer. 320 */ 321 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 322 323 /** 324 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 325 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 326 * settings entry if available, otherwise we use the hardcoded default. If it's been 327 * more than this long since the last fstrim, we force one during the boot sequence. 328 * 329 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 330 * one gets run at the next available charging+idle time. This final mandatory 331 * no-fstrim check kicks in only of the other scheduling criteria is never met. 332 */ 333 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 334 335 /** 336 * Whether verification is enabled by default. 337 */ 338 private static final boolean DEFAULT_VERIFY_ENABLE = true; 339 340 /** 341 * The default maximum time to wait for the verification agent to return in 342 * milliseconds. 343 */ 344 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 345 346 /** 347 * The default response for package verification timeout. 348 * 349 * This can be either PackageManager.VERIFICATION_ALLOW or 350 * PackageManager.VERIFICATION_REJECT. 351 */ 352 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 353 354 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 355 356 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 357 DEFAULT_CONTAINER_PACKAGE, 358 "com.android.defcontainer.DefaultContainerService"); 359 360 private static final String KILL_APP_REASON_GIDS_CHANGED = 361 "permission grant or revoke changed gids"; 362 363 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 364 "permissions revoked"; 365 366 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 367 368 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 369 370 /** Permission grant: not grant the permission. */ 371 private static final int GRANT_DENIED = 1; 372 373 /** Permission grant: grant the permission as an install permission. */ 374 private static final int GRANT_INSTALL = 2; 375 376 /** Permission grant: grant the permission as an install permission for a legacy app. */ 377 private static final int GRANT_INSTALL_LEGACY = 3; 378 379 /** Permission grant: grant the permission as a runtime one. */ 380 private static final int GRANT_RUNTIME = 4; 381 382 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 383 private static final int GRANT_UPGRADE = 5; 384 385 final ServiceThread mHandlerThread; 386 387 final PackageHandler mHandler; 388 389 /** 390 * Messages for {@link #mHandler} that need to wait for system ready before 391 * being dispatched. 392 */ 393 private ArrayList<Message> mPostSystemReadyMessages; 394 395 final int mSdkVersion = Build.VERSION.SDK_INT; 396 397 final Context mContext; 398 final boolean mFactoryTest; 399 final boolean mOnlyCore; 400 final boolean mLazyDexOpt; 401 final long mDexOptLRUThresholdInMills; 402 final DisplayMetrics mMetrics; 403 final int mDefParseFlags; 404 final String[] mSeparateProcesses; 405 final boolean mIsUpgrade; 406 407 // This is where all application persistent data goes. 408 final File mAppDataDir; 409 410 // This is where all application persistent data goes for secondary users. 411 final File mUserAppDataDir; 412 413 /** The location for ASEC container files on internal storage. */ 414 final String mAsecInternalPath; 415 416 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 417 // LOCK HELD. Can be called with mInstallLock held. 418 final Installer mInstaller; 419 420 /** Directory where installed third-party apps stored */ 421 final File mAppInstallDir; 422 423 /** 424 * Directory to which applications installed internally have their 425 * 32 bit native libraries copied. 426 */ 427 private File mAppLib32InstallDir; 428 429 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 430 // apps. 431 final File mDrmAppPrivateInstallDir; 432 433 // ---------------------------------------------------------------- 434 435 // Lock for state used when installing and doing other long running 436 // operations. Methods that must be called with this lock held have 437 // the suffix "LI". 438 final Object mInstallLock = new Object(); 439 440 // ---------------------------------------------------------------- 441 442 // Keys are String (package name), values are Package. This also serves 443 // as the lock for the global state. Methods that must be called with 444 // this lock held have the prefix "LP". 445 final ArrayMap<String, PackageParser.Package> mPackages = 446 new ArrayMap<String, PackageParser.Package>(); 447 448 // Tracks available target package names -> overlay package paths. 449 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 450 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 451 452 final Settings mSettings; 453 boolean mRestoredSettings; 454 455 // System configuration read by SystemConfig. 456 final int[] mGlobalGids; 457 final SparseArray<ArraySet<String>> mSystemPermissions; 458 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 459 460 // If mac_permissions.xml was found for seinfo labeling. 461 boolean mFoundPolicyFile; 462 463 // If a recursive restorecon of /data/data/<pkg> is needed. 464 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 465 466 public static final class SharedLibraryEntry { 467 public final String path; 468 public final String apk; 469 470 SharedLibraryEntry(String _path, String _apk) { 471 path = _path; 472 apk = _apk; 473 } 474 } 475 476 // Currently known shared libraries. 477 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 478 new ArrayMap<String, SharedLibraryEntry>(); 479 480 // All available activities, for your resolving pleasure. 481 final ActivityIntentResolver mActivities = 482 new ActivityIntentResolver(); 483 484 // All available receivers, for your resolving pleasure. 485 final ActivityIntentResolver mReceivers = 486 new ActivityIntentResolver(); 487 488 // All available services, for your resolving pleasure. 489 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 490 491 // All available providers, for your resolving pleasure. 492 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 493 494 // Mapping from provider base names (first directory in content URI codePath) 495 // to the provider information. 496 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 497 new ArrayMap<String, PackageParser.Provider>(); 498 499 // Mapping from instrumentation class names to info about them. 500 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 501 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 502 503 // Mapping from permission names to info about them. 504 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 505 new ArrayMap<String, PackageParser.PermissionGroup>(); 506 507 // Packages whose data we have transfered into another package, thus 508 // should no longer exist. 509 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 510 511 // Broadcast actions that are only available to the system. 512 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 513 514 /** List of packages waiting for verification. */ 515 final SparseArray<PackageVerificationState> mPendingVerification 516 = new SparseArray<PackageVerificationState>(); 517 518 /** Set of packages associated with each app op permission. */ 519 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 520 521 final PackageInstallerService mInstallerService; 522 523 private final PackageDexOptimizer mPackageDexOptimizer; 524 525 private AtomicInteger mNextMoveId = new AtomicInteger(); 526 private final MoveCallbacks mMoveCallbacks; 527 528 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 529 530 // Cache of users who need badging. 531 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 532 533 /** Token for keys in mPendingVerification. */ 534 private int mPendingVerificationToken = 0; 535 536 volatile boolean mSystemReady; 537 volatile boolean mSafeMode; 538 volatile boolean mHasSystemUidErrors; 539 540 ApplicationInfo mAndroidApplication; 541 final ActivityInfo mResolveActivity = new ActivityInfo(); 542 final ResolveInfo mResolveInfo = new ResolveInfo(); 543 ComponentName mResolveComponentName; 544 PackageParser.Package mPlatformPackage; 545 ComponentName mCustomResolverComponentName; 546 547 boolean mResolverReplaced = false; 548 549 private final ComponentName mIntentFilterVerifierComponent; 550 private int mIntentFilterVerificationToken = 0; 551 552 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 553 = new SparseArray<IntentFilterVerificationState>(); 554 555 private interface IntentFilterVerifier<T extends IntentFilter> { 556 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 557 T filter, String packageName); 558 void startVerifications(int userId); 559 void receiveVerificationResponse(int verificationId); 560 } 561 562 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 563 private Context mContext; 564 private ComponentName mIntentFilterVerifierComponent; 565 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 566 567 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 568 mContext = context; 569 mIntentFilterVerifierComponent = verifierComponent; 570 } 571 572 private String getDefaultScheme() { 573 // TODO: replace SCHEME_HTTP with SCHEME_HTTPS 574 return IntentFilter.SCHEME_HTTP; 575 } 576 577 @Override 578 public void startVerifications(int userId) { 579 // Launch verifications requests 580 int count = mCurrentIntentFilterVerifications.size(); 581 for (int n=0; n<count; n++) { 582 int verificationId = mCurrentIntentFilterVerifications.get(n); 583 final IntentFilterVerificationState ivs = 584 mIntentFilterVerificationStates.get(verificationId); 585 586 String packageName = ivs.getPackageName(); 587 588 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 589 final int filterCount = filters.size(); 590 ArraySet<String> domainsSet = new ArraySet<>(); 591 for (int m=0; m<filterCount; m++) { 592 PackageParser.ActivityIntentInfo filter = filters.get(m); 593 domainsSet.addAll(filter.getHostsList()); 594 } 595 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 596 synchronized (mPackages) { 597 if (mSettings.createIntentFilterVerificationIfNeededLPw( 598 packageName, domainsList) != null) { 599 scheduleWriteSettingsLocked(); 600 } 601 } 602 sendVerificationRequest(userId, verificationId, ivs); 603 } 604 mCurrentIntentFilterVerifications.clear(); 605 } 606 607 private void sendVerificationRequest(int userId, int verificationId, 608 IntentFilterVerificationState ivs) { 609 610 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 611 verificationIntent.putExtra( 612 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 613 verificationId); 614 verificationIntent.putExtra( 615 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 616 getDefaultScheme()); 617 verificationIntent.putExtra( 618 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 619 ivs.getHostsString()); 620 verificationIntent.putExtra( 621 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 622 ivs.getPackageName()); 623 verificationIntent.setComponent(mIntentFilterVerifierComponent); 624 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 625 626 UserHandle user = new UserHandle(userId); 627 mContext.sendBroadcastAsUser(verificationIntent, user); 628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 629 "Sending IntenFilter verification broadcast"); 630 } 631 632 public void receiveVerificationResponse(int verificationId) { 633 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 634 635 final boolean verified = ivs.isVerified(); 636 637 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 638 final int count = filters.size(); 639 for (int n=0; n<count; n++) { 640 PackageParser.ActivityIntentInfo filter = filters.get(n); 641 filter.setVerified(verified); 642 643 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 644 + " verified with result:" + verified + " and hosts:" 645 + ivs.getHostsString()); 646 } 647 648 mIntentFilterVerificationStates.remove(verificationId); 649 650 final String packageName = ivs.getPackageName(); 651 IntentFilterVerificationInfo ivi = null; 652 653 synchronized (mPackages) { 654 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 655 } 656 if (ivi == null) { 657 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 658 + verificationId + " packageName:" + packageName); 659 return; 660 } 661 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 662 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 663 664 synchronized (mPackages) { 665 if (verified) { 666 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 667 } else { 668 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 669 } 670 scheduleWriteSettingsLocked(); 671 672 final int userId = ivs.getUserId(); 673 if (userId != UserHandle.USER_ALL) { 674 final int userStatus = 675 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 676 677 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 678 boolean needUpdate = false; 679 680 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 681 // already been set by the User thru the Disambiguation dialog 682 switch (userStatus) { 683 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 684 if (verified) { 685 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 686 } else { 687 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 688 } 689 needUpdate = true; 690 break; 691 692 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 693 if (verified) { 694 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 695 needUpdate = true; 696 } 697 break; 698 699 default: 700 // Nothing to do 701 } 702 703 if (needUpdate) { 704 mSettings.updateIntentFilterVerificationStatusLPw( 705 packageName, updatedStatus, userId); 706 scheduleWritePackageRestrictionsLocked(userId); 707 } 708 } 709 } 710 } 711 712 @Override 713 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 714 ActivityIntentInfo filter, String packageName) { 715 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 716 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 717 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 718 "IntentFilter does not contain HTTP nor HTTPS data scheme"); 719 return false; 720 } 721 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 722 if (ivs == null) { 723 ivs = createDomainVerificationState(verifierId, userId, verificationId, 724 packageName); 725 } 726 if (!hasValidDomains(filter)) { 727 return false; 728 } 729 ivs.addFilter(filter); 730 return true; 731 } 732 733 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 734 int userId, int verificationId, String packageName) { 735 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 736 verifierId, userId, packageName); 737 ivs.setPendingState(); 738 synchronized (mPackages) { 739 mIntentFilterVerificationStates.append(verificationId, ivs); 740 mCurrentIntentFilterVerifications.add(verificationId); 741 } 742 return ivs; 743 } 744 } 745 746 private static boolean hasValidDomains(ActivityIntentInfo filter) { 747 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 748 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 749 if (!hasHTTPorHTTPS) { 750 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 751 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 752 return false; 753 } 754 return true; 755 } 756 757 private IntentFilterVerifier mIntentFilterVerifier; 758 759 // Set of pending broadcasts for aggregating enable/disable of components. 760 static class PendingPackageBroadcasts { 761 // for each user id, a map of <package name -> components within that package> 762 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 763 764 public PendingPackageBroadcasts() { 765 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 766 } 767 768 public ArrayList<String> get(int userId, String packageName) { 769 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 770 return packages.get(packageName); 771 } 772 773 public void put(int userId, String packageName, ArrayList<String> components) { 774 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 775 packages.put(packageName, components); 776 } 777 778 public void remove(int userId, String packageName) { 779 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 780 if (packages != null) { 781 packages.remove(packageName); 782 } 783 } 784 785 public void remove(int userId) { 786 mUidMap.remove(userId); 787 } 788 789 public int userIdCount() { 790 return mUidMap.size(); 791 } 792 793 public int userIdAt(int n) { 794 return mUidMap.keyAt(n); 795 } 796 797 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 798 return mUidMap.get(userId); 799 } 800 801 public int size() { 802 // total number of pending broadcast entries across all userIds 803 int num = 0; 804 for (int i = 0; i< mUidMap.size(); i++) { 805 num += mUidMap.valueAt(i).size(); 806 } 807 return num; 808 } 809 810 public void clear() { 811 mUidMap.clear(); 812 } 813 814 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 815 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 816 if (map == null) { 817 map = new ArrayMap<String, ArrayList<String>>(); 818 mUidMap.put(userId, map); 819 } 820 return map; 821 } 822 } 823 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 824 825 // Service Connection to remote media container service to copy 826 // package uri's from external media onto secure containers 827 // or internal storage. 828 private IMediaContainerService mContainerService = null; 829 830 static final int SEND_PENDING_BROADCAST = 1; 831 static final int MCS_BOUND = 3; 832 static final int END_COPY = 4; 833 static final int INIT_COPY = 5; 834 static final int MCS_UNBIND = 6; 835 static final int START_CLEANING_PACKAGE = 7; 836 static final int FIND_INSTALL_LOC = 8; 837 static final int POST_INSTALL = 9; 838 static final int MCS_RECONNECT = 10; 839 static final int MCS_GIVE_UP = 11; 840 static final int UPDATED_MEDIA_STATUS = 12; 841 static final int WRITE_SETTINGS = 13; 842 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 843 static final int PACKAGE_VERIFIED = 15; 844 static final int CHECK_PENDING_VERIFICATION = 16; 845 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 846 static final int INTENT_FILTER_VERIFIED = 18; 847 848 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 849 850 // Delay time in millisecs 851 static final int BROADCAST_DELAY = 10 * 1000; 852 853 static UserManagerService sUserManager; 854 855 // Stores a list of users whose package restrictions file needs to be updated 856 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 857 858 final private DefaultContainerConnection mDefContainerConn = 859 new DefaultContainerConnection(); 860 class DefaultContainerConnection implements ServiceConnection { 861 public void onServiceConnected(ComponentName name, IBinder service) { 862 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 863 IMediaContainerService imcs = 864 IMediaContainerService.Stub.asInterface(service); 865 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 866 } 867 868 public void onServiceDisconnected(ComponentName name) { 869 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 870 } 871 }; 872 873 // Recordkeeping of restore-after-install operations that are currently in flight 874 // between the Package Manager and the Backup Manager 875 class PostInstallData { 876 public InstallArgs args; 877 public PackageInstalledInfo res; 878 879 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 880 args = _a; 881 res = _r; 882 } 883 }; 884 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 885 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 886 887 // backup/restore of preferred activity state 888 private static final String TAG_PREFERRED_BACKUP = "pa"; 889 890 private final String mRequiredVerifierPackage; 891 892 private final PackageUsage mPackageUsage = new PackageUsage(); 893 894 private class PackageUsage { 895 private static final int WRITE_INTERVAL 896 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 897 898 private final Object mFileLock = new Object(); 899 private final AtomicLong mLastWritten = new AtomicLong(0); 900 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 901 902 private boolean mIsHistoricalPackageUsageAvailable = true; 903 904 boolean isHistoricalPackageUsageAvailable() { 905 return mIsHistoricalPackageUsageAvailable; 906 } 907 908 void write(boolean force) { 909 if (force) { 910 writeInternal(); 911 return; 912 } 913 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 914 && !DEBUG_DEXOPT) { 915 return; 916 } 917 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 918 new Thread("PackageUsage_DiskWriter") { 919 @Override 920 public void run() { 921 try { 922 writeInternal(); 923 } finally { 924 mBackgroundWriteRunning.set(false); 925 } 926 } 927 }.start(); 928 } 929 } 930 931 private void writeInternal() { 932 synchronized (mPackages) { 933 synchronized (mFileLock) { 934 AtomicFile file = getFile(); 935 FileOutputStream f = null; 936 try { 937 f = file.startWrite(); 938 BufferedOutputStream out = new BufferedOutputStream(f); 939 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 940 StringBuilder sb = new StringBuilder(); 941 for (PackageParser.Package pkg : mPackages.values()) { 942 if (pkg.mLastPackageUsageTimeInMills == 0) { 943 continue; 944 } 945 sb.setLength(0); 946 sb.append(pkg.packageName); 947 sb.append(' '); 948 sb.append((long)pkg.mLastPackageUsageTimeInMills); 949 sb.append('\n'); 950 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 951 } 952 out.flush(); 953 file.finishWrite(f); 954 } catch (IOException e) { 955 if (f != null) { 956 file.failWrite(f); 957 } 958 Log.e(TAG, "Failed to write package usage times", e); 959 } 960 } 961 } 962 mLastWritten.set(SystemClock.elapsedRealtime()); 963 } 964 965 void readLP() { 966 synchronized (mFileLock) { 967 AtomicFile file = getFile(); 968 BufferedInputStream in = null; 969 try { 970 in = new BufferedInputStream(file.openRead()); 971 StringBuffer sb = new StringBuffer(); 972 while (true) { 973 String packageName = readToken(in, sb, ' '); 974 if (packageName == null) { 975 break; 976 } 977 String timeInMillisString = readToken(in, sb, '\n'); 978 if (timeInMillisString == null) { 979 throw new IOException("Failed to find last usage time for package " 980 + packageName); 981 } 982 PackageParser.Package pkg = mPackages.get(packageName); 983 if (pkg == null) { 984 continue; 985 } 986 long timeInMillis; 987 try { 988 timeInMillis = Long.parseLong(timeInMillisString.toString()); 989 } catch (NumberFormatException e) { 990 throw new IOException("Failed to parse " + timeInMillisString 991 + " as a long.", e); 992 } 993 pkg.mLastPackageUsageTimeInMills = timeInMillis; 994 } 995 } catch (FileNotFoundException expected) { 996 mIsHistoricalPackageUsageAvailable = false; 997 } catch (IOException e) { 998 Log.w(TAG, "Failed to read package usage times", e); 999 } finally { 1000 IoUtils.closeQuietly(in); 1001 } 1002 } 1003 mLastWritten.set(SystemClock.elapsedRealtime()); 1004 } 1005 1006 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1007 throws IOException { 1008 sb.setLength(0); 1009 while (true) { 1010 int ch = in.read(); 1011 if (ch == -1) { 1012 if (sb.length() == 0) { 1013 return null; 1014 } 1015 throw new IOException("Unexpected EOF"); 1016 } 1017 if (ch == endOfToken) { 1018 return sb.toString(); 1019 } 1020 sb.append((char)ch); 1021 } 1022 } 1023 1024 private AtomicFile getFile() { 1025 File dataDir = Environment.getDataDirectory(); 1026 File systemDir = new File(dataDir, "system"); 1027 File fname = new File(systemDir, "package-usage.list"); 1028 return new AtomicFile(fname); 1029 } 1030 } 1031 1032 class PackageHandler extends Handler { 1033 private boolean mBound = false; 1034 final ArrayList<HandlerParams> mPendingInstalls = 1035 new ArrayList<HandlerParams>(); 1036 1037 private boolean connectToService() { 1038 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1039 " DefaultContainerService"); 1040 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1041 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1042 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1043 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1044 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1045 mBound = true; 1046 return true; 1047 } 1048 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1049 return false; 1050 } 1051 1052 private void disconnectService() { 1053 mContainerService = null; 1054 mBound = false; 1055 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1056 mContext.unbindService(mDefContainerConn); 1057 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1058 } 1059 1060 PackageHandler(Looper looper) { 1061 super(looper); 1062 } 1063 1064 public void handleMessage(Message msg) { 1065 try { 1066 doHandleMessage(msg); 1067 } finally { 1068 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1069 } 1070 } 1071 1072 void doHandleMessage(Message msg) { 1073 switch (msg.what) { 1074 case INIT_COPY: { 1075 HandlerParams params = (HandlerParams) msg.obj; 1076 int idx = mPendingInstalls.size(); 1077 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1078 // If a bind was already initiated we dont really 1079 // need to do anything. The pending install 1080 // will be processed later on. 1081 if (!mBound) { 1082 // If this is the only one pending we might 1083 // have to bind to the service again. 1084 if (!connectToService()) { 1085 Slog.e(TAG, "Failed to bind to media container service"); 1086 params.serviceError(); 1087 return; 1088 } else { 1089 // Once we bind to the service, the first 1090 // pending request will be processed. 1091 mPendingInstalls.add(idx, params); 1092 } 1093 } else { 1094 mPendingInstalls.add(idx, params); 1095 // Already bound to the service. Just make 1096 // sure we trigger off processing the first request. 1097 if (idx == 0) { 1098 mHandler.sendEmptyMessage(MCS_BOUND); 1099 } 1100 } 1101 break; 1102 } 1103 case MCS_BOUND: { 1104 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1105 if (msg.obj != null) { 1106 mContainerService = (IMediaContainerService) msg.obj; 1107 } 1108 if (mContainerService == null) { 1109 // Something seriously wrong. Bail out 1110 Slog.e(TAG, "Cannot bind to media container service"); 1111 for (HandlerParams params : mPendingInstalls) { 1112 // Indicate service bind error 1113 params.serviceError(); 1114 } 1115 mPendingInstalls.clear(); 1116 } else if (mPendingInstalls.size() > 0) { 1117 HandlerParams params = mPendingInstalls.get(0); 1118 if (params != null) { 1119 if (params.startCopy()) { 1120 // We are done... look for more work or to 1121 // go idle. 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, 1123 "Checking for more work or unbind..."); 1124 // Delete pending install 1125 if (mPendingInstalls.size() > 0) { 1126 mPendingInstalls.remove(0); 1127 } 1128 if (mPendingInstalls.size() == 0) { 1129 if (mBound) { 1130 if (DEBUG_SD_INSTALL) Log.i(TAG, 1131 "Posting delayed MCS_UNBIND"); 1132 removeMessages(MCS_UNBIND); 1133 Message ubmsg = obtainMessage(MCS_UNBIND); 1134 // Unbind after a little delay, to avoid 1135 // continual thrashing. 1136 sendMessageDelayed(ubmsg, 10000); 1137 } 1138 } else { 1139 // There are more pending requests in queue. 1140 // Just post MCS_BOUND message to trigger processing 1141 // of next pending install. 1142 if (DEBUG_SD_INSTALL) Log.i(TAG, 1143 "Posting MCS_BOUND for next work"); 1144 mHandler.sendEmptyMessage(MCS_BOUND); 1145 } 1146 } 1147 } 1148 } else { 1149 // Should never happen ideally. 1150 Slog.w(TAG, "Empty queue"); 1151 } 1152 break; 1153 } 1154 case MCS_RECONNECT: { 1155 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1156 if (mPendingInstalls.size() > 0) { 1157 if (mBound) { 1158 disconnectService(); 1159 } 1160 if (!connectToService()) { 1161 Slog.e(TAG, "Failed to bind to media container service"); 1162 for (HandlerParams params : mPendingInstalls) { 1163 // Indicate service bind error 1164 params.serviceError(); 1165 } 1166 mPendingInstalls.clear(); 1167 } 1168 } 1169 break; 1170 } 1171 case MCS_UNBIND: { 1172 // If there is no actual work left, then time to unbind. 1173 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1174 1175 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1176 if (mBound) { 1177 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1178 1179 disconnectService(); 1180 } 1181 } else if (mPendingInstalls.size() > 0) { 1182 // There are more pending requests in queue. 1183 // Just post MCS_BOUND message to trigger processing 1184 // of next pending install. 1185 mHandler.sendEmptyMessage(MCS_BOUND); 1186 } 1187 1188 break; 1189 } 1190 case MCS_GIVE_UP: { 1191 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1192 mPendingInstalls.remove(0); 1193 break; 1194 } 1195 case SEND_PENDING_BROADCAST: { 1196 String packages[]; 1197 ArrayList<String> components[]; 1198 int size = 0; 1199 int uids[]; 1200 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1201 synchronized (mPackages) { 1202 if (mPendingBroadcasts == null) { 1203 return; 1204 } 1205 size = mPendingBroadcasts.size(); 1206 if (size <= 0) { 1207 // Nothing to be done. Just return 1208 return; 1209 } 1210 packages = new String[size]; 1211 components = new ArrayList[size]; 1212 uids = new int[size]; 1213 int i = 0; // filling out the above arrays 1214 1215 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1216 int packageUserId = mPendingBroadcasts.userIdAt(n); 1217 Iterator<Map.Entry<String, ArrayList<String>>> it 1218 = mPendingBroadcasts.packagesForUserId(packageUserId) 1219 .entrySet().iterator(); 1220 while (it.hasNext() && i < size) { 1221 Map.Entry<String, ArrayList<String>> ent = it.next(); 1222 packages[i] = ent.getKey(); 1223 components[i] = ent.getValue(); 1224 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1225 uids[i] = (ps != null) 1226 ? UserHandle.getUid(packageUserId, ps.appId) 1227 : -1; 1228 i++; 1229 } 1230 } 1231 size = i; 1232 mPendingBroadcasts.clear(); 1233 } 1234 // Send broadcasts 1235 for (int i = 0; i < size; i++) { 1236 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1237 } 1238 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1239 break; 1240 } 1241 case START_CLEANING_PACKAGE: { 1242 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1243 final String packageName = (String)msg.obj; 1244 final int userId = msg.arg1; 1245 final boolean andCode = msg.arg2 != 0; 1246 synchronized (mPackages) { 1247 if (userId == UserHandle.USER_ALL) { 1248 int[] users = sUserManager.getUserIds(); 1249 for (int user : users) { 1250 mSettings.addPackageToCleanLPw( 1251 new PackageCleanItem(user, packageName, andCode)); 1252 } 1253 } else { 1254 mSettings.addPackageToCleanLPw( 1255 new PackageCleanItem(userId, packageName, andCode)); 1256 } 1257 } 1258 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1259 startCleaningPackages(); 1260 } break; 1261 case POST_INSTALL: { 1262 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1263 PostInstallData data = mRunningInstalls.get(msg.arg1); 1264 mRunningInstalls.delete(msg.arg1); 1265 boolean deleteOld = false; 1266 1267 if (data != null) { 1268 InstallArgs args = data.args; 1269 PackageInstalledInfo res = data.res; 1270 1271 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1272 res.removedInfo.sendBroadcast(false, true, false); 1273 Bundle extras = new Bundle(1); 1274 extras.putInt(Intent.EXTRA_UID, res.uid); 1275 1276 // Now that we successfully installed the package, grant runtime 1277 // permissions if requested before broadcasting the install. 1278 if ((args.installFlags 1279 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1280 grantRequestedRuntimePermissions(res.pkg, 1281 args.user.getIdentifier()); 1282 } 1283 1284 // Determine the set of users who are adding this 1285 // package for the first time vs. those who are seeing 1286 // an update. 1287 int[] firstUsers; 1288 int[] updateUsers = new int[0]; 1289 if (res.origUsers == null || res.origUsers.length == 0) { 1290 firstUsers = res.newUsers; 1291 } else { 1292 firstUsers = new int[0]; 1293 for (int i=0; i<res.newUsers.length; i++) { 1294 int user = res.newUsers[i]; 1295 boolean isNew = true; 1296 for (int j=0; j<res.origUsers.length; j++) { 1297 if (res.origUsers[j] == user) { 1298 isNew = false; 1299 break; 1300 } 1301 } 1302 if (isNew) { 1303 int[] newFirst = new int[firstUsers.length+1]; 1304 System.arraycopy(firstUsers, 0, newFirst, 0, 1305 firstUsers.length); 1306 newFirst[firstUsers.length] = user; 1307 firstUsers = newFirst; 1308 } else { 1309 int[] newUpdate = new int[updateUsers.length+1]; 1310 System.arraycopy(updateUsers, 0, newUpdate, 0, 1311 updateUsers.length); 1312 newUpdate[updateUsers.length] = user; 1313 updateUsers = newUpdate; 1314 } 1315 } 1316 } 1317 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1318 res.pkg.applicationInfo.packageName, 1319 extras, null, null, firstUsers); 1320 final boolean update = res.removedInfo.removedPackage != null; 1321 if (update) { 1322 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1323 } 1324 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1325 res.pkg.applicationInfo.packageName, 1326 extras, null, null, updateUsers); 1327 if (update) { 1328 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1329 res.pkg.applicationInfo.packageName, 1330 extras, null, null, updateUsers); 1331 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1332 null, null, 1333 res.pkg.applicationInfo.packageName, null, updateUsers); 1334 1335 // treat asec-hosted packages like removable media on upgrade 1336 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1337 if (DEBUG_INSTALL) { 1338 Slog.i(TAG, "upgrading pkg " + res.pkg 1339 + " is ASEC-hosted -> AVAILABLE"); 1340 } 1341 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1342 ArrayList<String> pkgList = new ArrayList<String>(1); 1343 pkgList.add(res.pkg.applicationInfo.packageName); 1344 sendResourcesChangedBroadcast(true, true, 1345 pkgList,uidArray, null); 1346 } 1347 } 1348 if (res.removedInfo.args != null) { 1349 // Remove the replaced package's older resources safely now 1350 deleteOld = true; 1351 } 1352 1353 // Log current value of "unknown sources" setting 1354 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1355 getUnknownSourcesSettings()); 1356 } 1357 // Force a gc to clear up things 1358 Runtime.getRuntime().gc(); 1359 // We delete after a gc for applications on sdcard. 1360 if (deleteOld) { 1361 synchronized (mInstallLock) { 1362 res.removedInfo.args.doPostDeleteLI(true); 1363 } 1364 } 1365 if (args.observer != null) { 1366 try { 1367 Bundle extras = extrasForInstallResult(res); 1368 args.observer.onPackageInstalled(res.name, res.returnCode, 1369 res.returnMsg, extras); 1370 } catch (RemoteException e) { 1371 Slog.i(TAG, "Observer no longer exists."); 1372 } 1373 } 1374 } else { 1375 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1376 } 1377 } break; 1378 case UPDATED_MEDIA_STATUS: { 1379 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1380 boolean reportStatus = msg.arg1 == 1; 1381 boolean doGc = msg.arg2 == 1; 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1383 if (doGc) { 1384 // Force a gc to clear up stale containers. 1385 Runtime.getRuntime().gc(); 1386 } 1387 if (msg.obj != null) { 1388 @SuppressWarnings("unchecked") 1389 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1390 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1391 // Unload containers 1392 unloadAllContainers(args); 1393 } 1394 if (reportStatus) { 1395 try { 1396 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1397 PackageHelper.getMountService().finishMediaUpdate(); 1398 } catch (RemoteException e) { 1399 Log.e(TAG, "MountService not running?"); 1400 } 1401 } 1402 } break; 1403 case WRITE_SETTINGS: { 1404 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1405 synchronized (mPackages) { 1406 removeMessages(WRITE_SETTINGS); 1407 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1408 mSettings.writeLPr(); 1409 mDirtyUsers.clear(); 1410 } 1411 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1412 } break; 1413 case WRITE_PACKAGE_RESTRICTIONS: { 1414 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1415 synchronized (mPackages) { 1416 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1417 for (int userId : mDirtyUsers) { 1418 mSettings.writePackageRestrictionsLPr(userId); 1419 } 1420 mDirtyUsers.clear(); 1421 } 1422 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1423 } break; 1424 case CHECK_PENDING_VERIFICATION: { 1425 final int verificationId = msg.arg1; 1426 final PackageVerificationState state = mPendingVerification.get(verificationId); 1427 1428 if ((state != null) && !state.timeoutExtended()) { 1429 final InstallArgs args = state.getInstallArgs(); 1430 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1431 1432 Slog.i(TAG, "Verification timed out for " + originUri); 1433 mPendingVerification.remove(verificationId); 1434 1435 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1436 1437 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1438 Slog.i(TAG, "Continuing with installation of " + originUri); 1439 state.setVerifierResponse(Binder.getCallingUid(), 1440 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1441 broadcastPackageVerified(verificationId, originUri, 1442 PackageManager.VERIFICATION_ALLOW, 1443 state.getInstallArgs().getUser()); 1444 try { 1445 ret = args.copyApk(mContainerService, true); 1446 } catch (RemoteException e) { 1447 Slog.e(TAG, "Could not contact the ContainerService"); 1448 } 1449 } else { 1450 broadcastPackageVerified(verificationId, originUri, 1451 PackageManager.VERIFICATION_REJECT, 1452 state.getInstallArgs().getUser()); 1453 } 1454 1455 processPendingInstall(args, ret); 1456 mHandler.sendEmptyMessage(MCS_UNBIND); 1457 } 1458 break; 1459 } 1460 case PACKAGE_VERIFIED: { 1461 final int verificationId = msg.arg1; 1462 1463 final PackageVerificationState state = mPendingVerification.get(verificationId); 1464 if (state == null) { 1465 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1466 break; 1467 } 1468 1469 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1470 1471 state.setVerifierResponse(response.callerUid, response.code); 1472 1473 if (state.isVerificationComplete()) { 1474 mPendingVerification.remove(verificationId); 1475 1476 final InstallArgs args = state.getInstallArgs(); 1477 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1478 1479 int ret; 1480 if (state.isInstallAllowed()) { 1481 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1482 broadcastPackageVerified(verificationId, originUri, 1483 response.code, state.getInstallArgs().getUser()); 1484 try { 1485 ret = args.copyApk(mContainerService, true); 1486 } catch (RemoteException e) { 1487 Slog.e(TAG, "Could not contact the ContainerService"); 1488 } 1489 } else { 1490 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1491 } 1492 1493 processPendingInstall(args, ret); 1494 1495 mHandler.sendEmptyMessage(MCS_UNBIND); 1496 } 1497 1498 break; 1499 } 1500 case START_INTENT_FILTER_VERIFICATIONS: { 1501 int userId = msg.arg1; 1502 int verifierUid = msg.arg2; 1503 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1504 1505 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1506 break; 1507 } 1508 case INTENT_FILTER_VERIFIED: { 1509 final int verificationId = msg.arg1; 1510 1511 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1512 verificationId); 1513 if (state == null) { 1514 Slog.w(TAG, "Invalid IntentFilter verification token " 1515 + verificationId + " received"); 1516 break; 1517 } 1518 1519 final int userId = state.getUserId(); 1520 1521 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1522 "Processing IntentFilter verification with token:" 1523 + verificationId + " and userId:" + userId); 1524 1525 final IntentFilterVerificationResponse response = 1526 (IntentFilterVerificationResponse) msg.obj; 1527 1528 state.setVerifierResponse(response.callerUid, response.code); 1529 1530 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1531 "IntentFilter verification with token:" + verificationId 1532 + " and userId:" + userId 1533 + " is settings verifier response with response code:" 1534 + response.code); 1535 1536 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1537 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1538 + response.getFailedDomainsString()); 1539 } 1540 1541 if (state.isVerificationComplete()) { 1542 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1543 } else { 1544 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1545 "IntentFilter verification with token:" + verificationId 1546 + " was not said to be complete"); 1547 } 1548 1549 break; 1550 } 1551 } 1552 } 1553 } 1554 1555 private StorageEventListener mStorageListener = new StorageEventListener() { 1556 @Override 1557 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1558 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1559 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1560 // TODO: ensure that private directories exist for all active users 1561 // TODO: remove user data whose serial number doesn't match 1562 loadPrivatePackages(vol); 1563 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1564 unloadPrivatePackages(vol); 1565 } 1566 } 1567 1568 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1569 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1570 updateExternalMediaStatus(true, false); 1571 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1572 updateExternalMediaStatus(false, false); 1573 } 1574 } 1575 } 1576 1577 @Override 1578 public void onVolumeForgotten(String fsUuid) { 1579 // TODO: remove all packages hosted on this uuid 1580 } 1581 }; 1582 1583 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1584 if (userId >= UserHandle.USER_OWNER) { 1585 grantRequestedRuntimePermissionsForUser(pkg, userId); 1586 } else if (userId == UserHandle.USER_ALL) { 1587 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1588 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1589 } 1590 } 1591 } 1592 1593 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1594 SettingBase sb = (SettingBase) pkg.mExtras; 1595 if (sb == null) { 1596 return; 1597 } 1598 1599 PermissionsState permissionsState = sb.getPermissionsState(); 1600 1601 for (String permission : pkg.requestedPermissions) { 1602 BasePermission bp = mSettings.mPermissions.get(permission); 1603 if (bp != null && bp.isRuntime()) { 1604 permissionsState.grantRuntimePermission(bp, userId); 1605 } 1606 } 1607 } 1608 1609 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1610 Bundle extras = null; 1611 switch (res.returnCode) { 1612 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1613 extras = new Bundle(); 1614 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1615 res.origPermission); 1616 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1617 res.origPackage); 1618 break; 1619 } 1620 case PackageManager.INSTALL_SUCCEEDED: { 1621 extras = new Bundle(); 1622 extras.putBoolean(Intent.EXTRA_REPLACING, 1623 res.removedInfo != null && res.removedInfo.removedPackage != null); 1624 break; 1625 } 1626 } 1627 return extras; 1628 } 1629 1630 void scheduleWriteSettingsLocked() { 1631 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1632 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1633 } 1634 } 1635 1636 void scheduleWritePackageRestrictionsLocked(int userId) { 1637 if (!sUserManager.exists(userId)) return; 1638 mDirtyUsers.add(userId); 1639 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1640 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1641 } 1642 } 1643 1644 public static PackageManagerService main(Context context, Installer installer, 1645 boolean factoryTest, boolean onlyCore) { 1646 PackageManagerService m = new PackageManagerService(context, installer, 1647 factoryTest, onlyCore); 1648 ServiceManager.addService("package", m); 1649 return m; 1650 } 1651 1652 static String[] splitString(String str, char sep) { 1653 int count = 1; 1654 int i = 0; 1655 while ((i=str.indexOf(sep, i)) >= 0) { 1656 count++; 1657 i++; 1658 } 1659 1660 String[] res = new String[count]; 1661 i=0; 1662 count = 0; 1663 int lastI=0; 1664 while ((i=str.indexOf(sep, i)) >= 0) { 1665 res[count] = str.substring(lastI, i); 1666 count++; 1667 i++; 1668 lastI = i; 1669 } 1670 res[count] = str.substring(lastI, str.length()); 1671 return res; 1672 } 1673 1674 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1675 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1676 Context.DISPLAY_SERVICE); 1677 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1678 } 1679 1680 public PackageManagerService(Context context, Installer installer, 1681 boolean factoryTest, boolean onlyCore) { 1682 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1683 SystemClock.uptimeMillis()); 1684 1685 if (mSdkVersion <= 0) { 1686 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1687 } 1688 1689 mContext = context; 1690 mFactoryTest = factoryTest; 1691 mOnlyCore = onlyCore; 1692 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1693 mMetrics = new DisplayMetrics(); 1694 mSettings = new Settings(mPackages); 1695 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1696 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1697 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1698 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1699 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1700 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1701 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1702 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1703 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1704 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1705 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1706 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1707 1708 // TODO: add a property to control this? 1709 long dexOptLRUThresholdInMinutes; 1710 if (mLazyDexOpt) { 1711 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1712 } else { 1713 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1714 } 1715 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1716 1717 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1718 if (separateProcesses != null && separateProcesses.length() > 0) { 1719 if ("*".equals(separateProcesses)) { 1720 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1721 mSeparateProcesses = null; 1722 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1723 } else { 1724 mDefParseFlags = 0; 1725 mSeparateProcesses = separateProcesses.split(","); 1726 Slog.w(TAG, "Running with debug.separate_processes: " 1727 + separateProcesses); 1728 } 1729 } else { 1730 mDefParseFlags = 0; 1731 mSeparateProcesses = null; 1732 } 1733 1734 mInstaller = installer; 1735 mPackageDexOptimizer = new PackageDexOptimizer(this); 1736 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1737 1738 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1739 FgThread.get().getLooper()); 1740 1741 getDefaultDisplayMetrics(context, mMetrics); 1742 1743 SystemConfig systemConfig = SystemConfig.getInstance(); 1744 mGlobalGids = systemConfig.getGlobalGids(); 1745 mSystemPermissions = systemConfig.getSystemPermissions(); 1746 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1747 1748 synchronized (mInstallLock) { 1749 // writer 1750 synchronized (mPackages) { 1751 mHandlerThread = new ServiceThread(TAG, 1752 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1753 mHandlerThread.start(); 1754 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1755 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1756 1757 File dataDir = Environment.getDataDirectory(); 1758 mAppDataDir = new File(dataDir, "data"); 1759 mAppInstallDir = new File(dataDir, "app"); 1760 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1761 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1762 mUserAppDataDir = new File(dataDir, "user"); 1763 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1764 1765 sUserManager = new UserManagerService(context, this, 1766 mInstallLock, mPackages); 1767 1768 // Propagate permission configuration in to package manager. 1769 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1770 = systemConfig.getPermissions(); 1771 for (int i=0; i<permConfig.size(); i++) { 1772 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1773 BasePermission bp = mSettings.mPermissions.get(perm.name); 1774 if (bp == null) { 1775 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1776 mSettings.mPermissions.put(perm.name, bp); 1777 } 1778 if (perm.gids != null) { 1779 bp.setGids(perm.gids, perm.perUser); 1780 } 1781 } 1782 1783 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1784 for (int i=0; i<libConfig.size(); i++) { 1785 mSharedLibraries.put(libConfig.keyAt(i), 1786 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1787 } 1788 1789 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1790 1791 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1792 mSdkVersion, mOnlyCore); 1793 1794 String customResolverActivity = Resources.getSystem().getString( 1795 R.string.config_customResolverActivity); 1796 if (TextUtils.isEmpty(customResolverActivity)) { 1797 customResolverActivity = null; 1798 } else { 1799 mCustomResolverComponentName = ComponentName.unflattenFromString( 1800 customResolverActivity); 1801 } 1802 1803 long startTime = SystemClock.uptimeMillis(); 1804 1805 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1806 startTime); 1807 1808 // Set flag to monitor and not change apk file paths when 1809 // scanning install directories. 1810 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1811 1812 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1813 1814 /** 1815 * Add everything in the in the boot class path to the 1816 * list of process files because dexopt will have been run 1817 * if necessary during zygote startup. 1818 */ 1819 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1820 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1821 1822 if (bootClassPath != null) { 1823 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1824 for (String element : bootClassPathElements) { 1825 alreadyDexOpted.add(element); 1826 } 1827 } else { 1828 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1829 } 1830 1831 if (systemServerClassPath != null) { 1832 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1833 for (String element : systemServerClassPathElements) { 1834 alreadyDexOpted.add(element); 1835 } 1836 } else { 1837 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1838 } 1839 1840 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1841 final String[] dexCodeInstructionSets = 1842 getDexCodeInstructionSets( 1843 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1844 1845 /** 1846 * Ensure all external libraries have had dexopt run on them. 1847 */ 1848 if (mSharedLibraries.size() > 0) { 1849 // NOTE: For now, we're compiling these system "shared libraries" 1850 // (and framework jars) into all available architectures. It's possible 1851 // to compile them only when we come across an app that uses them (there's 1852 // already logic for that in scanPackageLI) but that adds some complexity. 1853 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1854 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1855 final String lib = libEntry.path; 1856 if (lib == null) { 1857 continue; 1858 } 1859 1860 try { 1861 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1862 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1863 alreadyDexOpted.add(lib); 1864 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1865 } 1866 } catch (FileNotFoundException e) { 1867 Slog.w(TAG, "Library not found: " + lib); 1868 } catch (IOException e) { 1869 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1870 + e.getMessage()); 1871 } 1872 } 1873 } 1874 } 1875 1876 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1877 1878 // Gross hack for now: we know this file doesn't contain any 1879 // code, so don't dexopt it to avoid the resulting log spew. 1880 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1881 1882 // Gross hack for now: we know this file is only part of 1883 // the boot class path for art, so don't dexopt it to 1884 // avoid the resulting log spew. 1885 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1886 1887 /** 1888 * There are a number of commands implemented in Java, which 1889 * we currently need to do the dexopt on so that they can be 1890 * run from a non-root shell. 1891 */ 1892 String[] frameworkFiles = frameworkDir.list(); 1893 if (frameworkFiles != null) { 1894 // TODO: We could compile these only for the most preferred ABI. We should 1895 // first double check that the dex files for these commands are not referenced 1896 // by other system apps. 1897 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1898 for (int i=0; i<frameworkFiles.length; i++) { 1899 File libPath = new File(frameworkDir, frameworkFiles[i]); 1900 String path = libPath.getPath(); 1901 // Skip the file if we already did it. 1902 if (alreadyDexOpted.contains(path)) { 1903 continue; 1904 } 1905 // Skip the file if it is not a type we want to dexopt. 1906 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1907 continue; 1908 } 1909 try { 1910 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1911 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1912 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1913 } 1914 } catch (FileNotFoundException e) { 1915 Slog.w(TAG, "Jar not found: " + path); 1916 } catch (IOException e) { 1917 Slog.w(TAG, "Exception reading jar: " + path, e); 1918 } 1919 } 1920 } 1921 } 1922 1923 // Collect vendor overlay packages. 1924 // (Do this before scanning any apps.) 1925 // For security and version matching reason, only consider 1926 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1927 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1928 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1929 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1930 1931 // Find base frameworks (resource packages without code). 1932 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1933 | PackageParser.PARSE_IS_SYSTEM_DIR 1934 | PackageParser.PARSE_IS_PRIVILEGED, 1935 scanFlags | SCAN_NO_DEX, 0); 1936 1937 // Collected privileged system packages. 1938 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1939 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1940 | PackageParser.PARSE_IS_SYSTEM_DIR 1941 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1942 1943 // Collect ordinary system packages. 1944 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1945 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1946 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1947 1948 // Collect all vendor packages. 1949 File vendorAppDir = new File("/vendor/app"); 1950 try { 1951 vendorAppDir = vendorAppDir.getCanonicalFile(); 1952 } catch (IOException e) { 1953 // failed to look up canonical path, continue with original one 1954 } 1955 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1956 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1957 1958 // Collect all OEM packages. 1959 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1960 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1961 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1962 1963 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1964 mInstaller.moveFiles(); 1965 1966 // Prune any system packages that no longer exist. 1967 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1968 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1969 if (!mOnlyCore) { 1970 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1971 while (psit.hasNext()) { 1972 PackageSetting ps = psit.next(); 1973 1974 /* 1975 * If this is not a system app, it can't be a 1976 * disable system app. 1977 */ 1978 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1979 continue; 1980 } 1981 1982 /* 1983 * If the package is scanned, it's not erased. 1984 */ 1985 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1986 if (scannedPkg != null) { 1987 /* 1988 * If the system app is both scanned and in the 1989 * disabled packages list, then it must have been 1990 * added via OTA. Remove it from the currently 1991 * scanned package so the previously user-installed 1992 * application can be scanned. 1993 */ 1994 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1995 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1996 + ps.name + "; removing system app. Last known codePath=" 1997 + ps.codePathString + ", installStatus=" + ps.installStatus 1998 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1999 + scannedPkg.mVersionCode); 2000 removePackageLI(ps, true); 2001 expectingBetter.put(ps.name, ps.codePath); 2002 } 2003 2004 continue; 2005 } 2006 2007 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2008 psit.remove(); 2009 logCriticalInfo(Log.WARN, "System package " + ps.name 2010 + " no longer exists; wiping its data"); 2011 removeDataDirsLI(null, ps.name); 2012 } else { 2013 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2014 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2015 possiblyDeletedUpdatedSystemApps.add(ps.name); 2016 } 2017 } 2018 } 2019 } 2020 2021 //look for any incomplete package installations 2022 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2023 //clean up list 2024 for(int i = 0; i < deletePkgsList.size(); i++) { 2025 //clean up here 2026 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2027 } 2028 //delete tmp files 2029 deleteTempPackageFiles(); 2030 2031 // Remove any shared userIDs that have no associated packages 2032 mSettings.pruneSharedUsersLPw(); 2033 2034 if (!mOnlyCore) { 2035 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2036 SystemClock.uptimeMillis()); 2037 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2038 2039 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2040 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2041 2042 /** 2043 * Remove disable package settings for any updated system 2044 * apps that were removed via an OTA. If they're not a 2045 * previously-updated app, remove them completely. 2046 * Otherwise, just revoke their system-level permissions. 2047 */ 2048 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2049 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2050 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2051 2052 String msg; 2053 if (deletedPkg == null) { 2054 msg = "Updated system package " + deletedAppName 2055 + " no longer exists; wiping its data"; 2056 removeDataDirsLI(null, deletedAppName); 2057 } else { 2058 msg = "Updated system app + " + deletedAppName 2059 + " no longer present; removing system privileges for " 2060 + deletedAppName; 2061 2062 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2063 2064 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2065 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2066 } 2067 logCriticalInfo(Log.WARN, msg); 2068 } 2069 2070 /** 2071 * Make sure all system apps that we expected to appear on 2072 * the userdata partition actually showed up. If they never 2073 * appeared, crawl back and revive the system version. 2074 */ 2075 for (int i = 0; i < expectingBetter.size(); i++) { 2076 final String packageName = expectingBetter.keyAt(i); 2077 if (!mPackages.containsKey(packageName)) { 2078 final File scanFile = expectingBetter.valueAt(i); 2079 2080 logCriticalInfo(Log.WARN, "Expected better " + packageName 2081 + " but never showed up; reverting to system"); 2082 2083 final int reparseFlags; 2084 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2085 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2086 | PackageParser.PARSE_IS_SYSTEM_DIR 2087 | PackageParser.PARSE_IS_PRIVILEGED; 2088 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2089 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2090 | PackageParser.PARSE_IS_SYSTEM_DIR; 2091 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2092 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2093 | PackageParser.PARSE_IS_SYSTEM_DIR; 2094 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2095 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2096 | PackageParser.PARSE_IS_SYSTEM_DIR; 2097 } else { 2098 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2099 continue; 2100 } 2101 2102 mSettings.enableSystemPackageLPw(packageName); 2103 2104 try { 2105 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2106 } catch (PackageManagerException e) { 2107 Slog.e(TAG, "Failed to parse original system package: " 2108 + e.getMessage()); 2109 } 2110 } 2111 } 2112 } 2113 2114 // Now that we know all of the shared libraries, update all clients to have 2115 // the correct library paths. 2116 updateAllSharedLibrariesLPw(); 2117 2118 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2119 // NOTE: We ignore potential failures here during a system scan (like 2120 // the rest of the commands above) because there's precious little we 2121 // can do about it. A settings error is reported, though. 2122 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2123 false /* force dexopt */, false /* defer dexopt */); 2124 } 2125 2126 // Now that we know all the packages we are keeping, 2127 // read and update their last usage times. 2128 mPackageUsage.readLP(); 2129 2130 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2131 SystemClock.uptimeMillis()); 2132 Slog.i(TAG, "Time to scan packages: " 2133 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2134 + " seconds"); 2135 2136 // If the platform SDK has changed since the last time we booted, 2137 // we need to re-grant app permission to catch any new ones that 2138 // appear. This is really a hack, and means that apps can in some 2139 // cases get permissions that the user didn't initially explicitly 2140 // allow... it would be nice to have some better way to handle 2141 // this situation. 2142 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2143 != mSdkVersion; 2144 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2145 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2146 + "; regranting permissions for internal storage"); 2147 mSettings.mInternalSdkPlatform = mSdkVersion; 2148 2149 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2150 | (regrantPermissions 2151 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2152 : 0)); 2153 2154 // If this is the first boot, and it is a normal boot, then 2155 // we need to initialize the default preferred apps. 2156 if (!mRestoredSettings && !onlyCore) { 2157 mSettings.readDefaultPreferredAppsLPw(this, 0); 2158 } 2159 2160 // If this is first boot after an OTA, and a normal boot, then 2161 // we need to clear code cache directories. 2162 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2163 if (mIsUpgrade && !onlyCore) { 2164 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2165 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2166 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2167 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2168 } 2169 mSettings.mFingerprint = Build.FINGERPRINT; 2170 } 2171 2172 primeDomainVerificationsLPw(); 2173 checkDefaultBrowser(); 2174 2175 // All the changes are done during package scanning. 2176 mSettings.updateInternalDatabaseVersion(); 2177 2178 // can downgrade to reader 2179 mSettings.writeLPr(); 2180 2181 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2182 SystemClock.uptimeMillis()); 2183 2184 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2185 2186 mInstallerService = new PackageInstallerService(context, this); 2187 2188 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2189 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2190 mIntentFilterVerifierComponent); 2191 2192 } // synchronized (mPackages) 2193 } // synchronized (mInstallLock) 2194 2195 // Now after opening every single application zip, make sure they 2196 // are all flushed. Not really needed, but keeps things nice and 2197 // tidy. 2198 Runtime.getRuntime().gc(); 2199 } 2200 2201 @Override 2202 public boolean isFirstBoot() { 2203 return !mRestoredSettings; 2204 } 2205 2206 @Override 2207 public boolean isOnlyCoreApps() { 2208 return mOnlyCore; 2209 } 2210 2211 @Override 2212 public boolean isUpgrade() { 2213 return mIsUpgrade; 2214 } 2215 2216 private String getRequiredVerifierLPr() { 2217 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2218 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2219 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2220 2221 String requiredVerifier = null; 2222 2223 final int N = receivers.size(); 2224 for (int i = 0; i < N; i++) { 2225 final ResolveInfo info = receivers.get(i); 2226 2227 if (info.activityInfo == null) { 2228 continue; 2229 } 2230 2231 final String packageName = info.activityInfo.packageName; 2232 2233 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2234 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2235 continue; 2236 } 2237 2238 if (requiredVerifier != null) { 2239 throw new RuntimeException("There can be only one required verifier"); 2240 } 2241 2242 requiredVerifier = packageName; 2243 } 2244 2245 return requiredVerifier; 2246 } 2247 2248 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2249 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2250 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2251 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2252 2253 ComponentName verifierComponentName = null; 2254 2255 int priority = -1000; 2256 final int N = receivers.size(); 2257 for (int i = 0; i < N; i++) { 2258 final ResolveInfo info = receivers.get(i); 2259 2260 if (info.activityInfo == null) { 2261 continue; 2262 } 2263 2264 final String packageName = info.activityInfo.packageName; 2265 2266 final PackageSetting ps = mSettings.mPackages.get(packageName); 2267 if (ps == null) { 2268 continue; 2269 } 2270 2271 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2272 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2273 continue; 2274 } 2275 2276 // Select the IntentFilterVerifier with the highest priority 2277 if (priority < info.priority) { 2278 priority = info.priority; 2279 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2280 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2281 + verifierComponentName + " with priority: " + info.priority); 2282 } 2283 } 2284 2285 return verifierComponentName; 2286 } 2287 2288 private void primeDomainVerificationsLPw() { 2289 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2290 boolean updated = false; 2291 ArraySet<String> allHostsSet = new ArraySet<>(); 2292 for (PackageParser.Package pkg : mPackages.values()) { 2293 final String packageName = pkg.packageName; 2294 if (!hasDomainURLs(pkg)) { 2295 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2296 "package with no domain URLs: " + packageName); 2297 continue; 2298 } 2299 if (!pkg.isSystemApp()) { 2300 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2301 "No priming domain verifications for a non system package : " + 2302 packageName); 2303 continue; 2304 } 2305 for (PackageParser.Activity a : pkg.activities) { 2306 for (ActivityIntentInfo filter : a.intents) { 2307 if (hasValidDomains(filter)) { 2308 allHostsSet.addAll(filter.getHostsList()); 2309 } 2310 } 2311 } 2312 if (allHostsSet.size() == 0) { 2313 allHostsSet.add("*"); 2314 } 2315 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2316 IntentFilterVerificationInfo ivi = 2317 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2318 if (ivi != null) { 2319 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2320 "Priming domain verifications for package: " + packageName + 2321 " with hosts:" + ivi.getDomainsString()); 2322 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2323 updated = true; 2324 } 2325 else { 2326 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2327 "No priming domain verifications for package: " + packageName); 2328 } 2329 allHostsSet.clear(); 2330 } 2331 if (updated) { 2332 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2333 "Will need to write primed domain verifications"); 2334 } 2335 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2336 } 2337 2338 private void checkDefaultBrowser() { 2339 final int myUserId = UserHandle.myUserId(); 2340 final String packageName = getDefaultBrowserPackageName(myUserId); 2341 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2342 if (info == null) { 2343 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2344 packageName); 2345 setDefaultBrowserPackageName(null, myUserId); 2346 } 2347 } 2348 2349 @Override 2350 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2351 throws RemoteException { 2352 try { 2353 return super.onTransact(code, data, reply, flags); 2354 } catch (RuntimeException e) { 2355 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2356 Slog.wtf(TAG, "Package Manager Crash", e); 2357 } 2358 throw e; 2359 } 2360 } 2361 2362 void cleanupInstallFailedPackage(PackageSetting ps) { 2363 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2364 2365 removeDataDirsLI(ps.volumeUuid, ps.name); 2366 if (ps.codePath != null) { 2367 if (ps.codePath.isDirectory()) { 2368 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2369 } else { 2370 ps.codePath.delete(); 2371 } 2372 } 2373 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2374 if (ps.resourcePath.isDirectory()) { 2375 FileUtils.deleteContents(ps.resourcePath); 2376 } 2377 ps.resourcePath.delete(); 2378 } 2379 mSettings.removePackageLPw(ps.name); 2380 } 2381 2382 static int[] appendInts(int[] cur, int[] add) { 2383 if (add == null) return cur; 2384 if (cur == null) return add; 2385 final int N = add.length; 2386 for (int i=0; i<N; i++) { 2387 cur = appendInt(cur, add[i]); 2388 } 2389 return cur; 2390 } 2391 2392 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2393 if (!sUserManager.exists(userId)) return null; 2394 final PackageSetting ps = (PackageSetting) p.mExtras; 2395 if (ps == null) { 2396 return null; 2397 } 2398 2399 final PermissionsState permissionsState = ps.getPermissionsState(); 2400 2401 final int[] gids = permissionsState.computeGids(userId); 2402 final Set<String> permissions = permissionsState.getPermissions(userId); 2403 final PackageUserState state = ps.readUserState(userId); 2404 2405 return PackageParser.generatePackageInfo(p, gids, flags, 2406 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2407 } 2408 2409 @Override 2410 public boolean isPackageFrozen(String packageName) { 2411 synchronized (mPackages) { 2412 final PackageSetting ps = mSettings.mPackages.get(packageName); 2413 if (ps != null) { 2414 return ps.frozen; 2415 } 2416 } 2417 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2418 return true; 2419 } 2420 2421 @Override 2422 public boolean isPackageAvailable(String packageName, int userId) { 2423 if (!sUserManager.exists(userId)) return false; 2424 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2425 synchronized (mPackages) { 2426 PackageParser.Package p = mPackages.get(packageName); 2427 if (p != null) { 2428 final PackageSetting ps = (PackageSetting) p.mExtras; 2429 if (ps != null) { 2430 final PackageUserState state = ps.readUserState(userId); 2431 if (state != null) { 2432 return PackageParser.isAvailable(state); 2433 } 2434 } 2435 } 2436 } 2437 return false; 2438 } 2439 2440 @Override 2441 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2442 if (!sUserManager.exists(userId)) return null; 2443 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2444 // reader 2445 synchronized (mPackages) { 2446 PackageParser.Package p = mPackages.get(packageName); 2447 if (DEBUG_PACKAGE_INFO) 2448 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2449 if (p != null) { 2450 return generatePackageInfo(p, flags, userId); 2451 } 2452 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2453 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2454 } 2455 } 2456 return null; 2457 } 2458 2459 @Override 2460 public String[] currentToCanonicalPackageNames(String[] names) { 2461 String[] out = new String[names.length]; 2462 // reader 2463 synchronized (mPackages) { 2464 for (int i=names.length-1; i>=0; i--) { 2465 PackageSetting ps = mSettings.mPackages.get(names[i]); 2466 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2467 } 2468 } 2469 return out; 2470 } 2471 2472 @Override 2473 public String[] canonicalToCurrentPackageNames(String[] names) { 2474 String[] out = new String[names.length]; 2475 // reader 2476 synchronized (mPackages) { 2477 for (int i=names.length-1; i>=0; i--) { 2478 String cur = mSettings.mRenamedPackages.get(names[i]); 2479 out[i] = cur != null ? cur : names[i]; 2480 } 2481 } 2482 return out; 2483 } 2484 2485 @Override 2486 public int getPackageUid(String packageName, int userId) { 2487 if (!sUserManager.exists(userId)) return -1; 2488 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2489 2490 // reader 2491 synchronized (mPackages) { 2492 PackageParser.Package p = mPackages.get(packageName); 2493 if(p != null) { 2494 return UserHandle.getUid(userId, p.applicationInfo.uid); 2495 } 2496 PackageSetting ps = mSettings.mPackages.get(packageName); 2497 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2498 return -1; 2499 } 2500 p = ps.pkg; 2501 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2502 } 2503 } 2504 2505 @Override 2506 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2507 if (!sUserManager.exists(userId)) { 2508 return null; 2509 } 2510 2511 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2512 "getPackageGids"); 2513 2514 // reader 2515 synchronized (mPackages) { 2516 PackageParser.Package p = mPackages.get(packageName); 2517 if (DEBUG_PACKAGE_INFO) { 2518 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2519 } 2520 if (p != null) { 2521 PackageSetting ps = (PackageSetting) p.mExtras; 2522 return ps.getPermissionsState().computeGids(userId); 2523 } 2524 } 2525 2526 return null; 2527 } 2528 2529 static PermissionInfo generatePermissionInfo( 2530 BasePermission bp, int flags) { 2531 if (bp.perm != null) { 2532 return PackageParser.generatePermissionInfo(bp.perm, flags); 2533 } 2534 PermissionInfo pi = new PermissionInfo(); 2535 pi.name = bp.name; 2536 pi.packageName = bp.sourcePackage; 2537 pi.nonLocalizedLabel = bp.name; 2538 pi.protectionLevel = bp.protectionLevel; 2539 return pi; 2540 } 2541 2542 @Override 2543 public PermissionInfo getPermissionInfo(String name, int flags) { 2544 // reader 2545 synchronized (mPackages) { 2546 final BasePermission p = mSettings.mPermissions.get(name); 2547 if (p != null) { 2548 return generatePermissionInfo(p, flags); 2549 } 2550 return null; 2551 } 2552 } 2553 2554 @Override 2555 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2556 // reader 2557 synchronized (mPackages) { 2558 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2559 for (BasePermission p : mSettings.mPermissions.values()) { 2560 if (group == null) { 2561 if (p.perm == null || p.perm.info.group == null) { 2562 out.add(generatePermissionInfo(p, flags)); 2563 } 2564 } else { 2565 if (p.perm != null && group.equals(p.perm.info.group)) { 2566 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2567 } 2568 } 2569 } 2570 2571 if (out.size() > 0) { 2572 return out; 2573 } 2574 return mPermissionGroups.containsKey(group) ? out : null; 2575 } 2576 } 2577 2578 @Override 2579 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2580 // reader 2581 synchronized (mPackages) { 2582 return PackageParser.generatePermissionGroupInfo( 2583 mPermissionGroups.get(name), flags); 2584 } 2585 } 2586 2587 @Override 2588 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2589 // reader 2590 synchronized (mPackages) { 2591 final int N = mPermissionGroups.size(); 2592 ArrayList<PermissionGroupInfo> out 2593 = new ArrayList<PermissionGroupInfo>(N); 2594 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2595 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2596 } 2597 return out; 2598 } 2599 } 2600 2601 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2602 int userId) { 2603 if (!sUserManager.exists(userId)) return null; 2604 PackageSetting ps = mSettings.mPackages.get(packageName); 2605 if (ps != null) { 2606 if (ps.pkg == null) { 2607 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2608 flags, userId); 2609 if (pInfo != null) { 2610 return pInfo.applicationInfo; 2611 } 2612 return null; 2613 } 2614 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2615 ps.readUserState(userId), userId); 2616 } 2617 return null; 2618 } 2619 2620 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2621 int userId) { 2622 if (!sUserManager.exists(userId)) return null; 2623 PackageSetting ps = mSettings.mPackages.get(packageName); 2624 if (ps != null) { 2625 PackageParser.Package pkg = ps.pkg; 2626 if (pkg == null) { 2627 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2628 return null; 2629 } 2630 // Only data remains, so we aren't worried about code paths 2631 pkg = new PackageParser.Package(packageName); 2632 pkg.applicationInfo.packageName = packageName; 2633 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2634 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2635 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2636 packageName, userId).getAbsolutePath(); 2637 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2638 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2639 } 2640 return generatePackageInfo(pkg, flags, userId); 2641 } 2642 return null; 2643 } 2644 2645 @Override 2646 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2647 if (!sUserManager.exists(userId)) return null; 2648 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2649 // writer 2650 synchronized (mPackages) { 2651 PackageParser.Package p = mPackages.get(packageName); 2652 if (DEBUG_PACKAGE_INFO) Log.v( 2653 TAG, "getApplicationInfo " + packageName 2654 + ": " + p); 2655 if (p != null) { 2656 PackageSetting ps = mSettings.mPackages.get(packageName); 2657 if (ps == null) return null; 2658 // Note: isEnabledLP() does not apply here - always return info 2659 return PackageParser.generateApplicationInfo( 2660 p, flags, ps.readUserState(userId), userId); 2661 } 2662 if ("android".equals(packageName)||"system".equals(packageName)) { 2663 return mAndroidApplication; 2664 } 2665 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2666 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2667 } 2668 } 2669 return null; 2670 } 2671 2672 @Override 2673 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2674 final IPackageDataObserver observer) { 2675 mContext.enforceCallingOrSelfPermission( 2676 android.Manifest.permission.CLEAR_APP_CACHE, null); 2677 // Queue up an async operation since clearing cache may take a little while. 2678 mHandler.post(new Runnable() { 2679 public void run() { 2680 mHandler.removeCallbacks(this); 2681 int retCode = -1; 2682 synchronized (mInstallLock) { 2683 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2684 if (retCode < 0) { 2685 Slog.w(TAG, "Couldn't clear application caches"); 2686 } 2687 } 2688 if (observer != null) { 2689 try { 2690 observer.onRemoveCompleted(null, (retCode >= 0)); 2691 } catch (RemoteException e) { 2692 Slog.w(TAG, "RemoveException when invoking call back"); 2693 } 2694 } 2695 } 2696 }); 2697 } 2698 2699 @Override 2700 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2701 final IntentSender pi) { 2702 mContext.enforceCallingOrSelfPermission( 2703 android.Manifest.permission.CLEAR_APP_CACHE, null); 2704 // Queue up an async operation since clearing cache may take a little while. 2705 mHandler.post(new Runnable() { 2706 public void run() { 2707 mHandler.removeCallbacks(this); 2708 int retCode = -1; 2709 synchronized (mInstallLock) { 2710 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2711 if (retCode < 0) { 2712 Slog.w(TAG, "Couldn't clear application caches"); 2713 } 2714 } 2715 if(pi != null) { 2716 try { 2717 // Callback via pending intent 2718 int code = (retCode >= 0) ? 1 : 0; 2719 pi.sendIntent(null, code, null, 2720 null, null); 2721 } catch (SendIntentException e1) { 2722 Slog.i(TAG, "Failed to send pending intent"); 2723 } 2724 } 2725 } 2726 }); 2727 } 2728 2729 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2730 synchronized (mInstallLock) { 2731 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2732 throw new IOException("Failed to free enough space"); 2733 } 2734 } 2735 } 2736 2737 @Override 2738 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2739 if (!sUserManager.exists(userId)) return null; 2740 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2741 synchronized (mPackages) { 2742 PackageParser.Activity a = mActivities.mActivities.get(component); 2743 2744 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2745 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2746 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2747 if (ps == null) return null; 2748 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2749 userId); 2750 } 2751 if (mResolveComponentName.equals(component)) { 2752 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2753 new PackageUserState(), userId); 2754 } 2755 } 2756 return null; 2757 } 2758 2759 @Override 2760 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2761 String resolvedType) { 2762 synchronized (mPackages) { 2763 PackageParser.Activity a = mActivities.mActivities.get(component); 2764 if (a == null) { 2765 return false; 2766 } 2767 for (int i=0; i<a.intents.size(); i++) { 2768 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2769 intent.getData(), intent.getCategories(), TAG) >= 0) { 2770 return true; 2771 } 2772 } 2773 return false; 2774 } 2775 } 2776 2777 @Override 2778 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2779 if (!sUserManager.exists(userId)) return null; 2780 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2781 synchronized (mPackages) { 2782 PackageParser.Activity a = mReceivers.mActivities.get(component); 2783 if (DEBUG_PACKAGE_INFO) Log.v( 2784 TAG, "getReceiverInfo " + component + ": " + a); 2785 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2786 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2787 if (ps == null) return null; 2788 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2789 userId); 2790 } 2791 } 2792 return null; 2793 } 2794 2795 @Override 2796 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2797 if (!sUserManager.exists(userId)) return null; 2798 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2799 synchronized (mPackages) { 2800 PackageParser.Service s = mServices.mServices.get(component); 2801 if (DEBUG_PACKAGE_INFO) Log.v( 2802 TAG, "getServiceInfo " + component + ": " + s); 2803 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2804 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2805 if (ps == null) return null; 2806 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2807 userId); 2808 } 2809 } 2810 return null; 2811 } 2812 2813 @Override 2814 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2815 if (!sUserManager.exists(userId)) return null; 2816 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2817 synchronized (mPackages) { 2818 PackageParser.Provider p = mProviders.mProviders.get(component); 2819 if (DEBUG_PACKAGE_INFO) Log.v( 2820 TAG, "getProviderInfo " + component + ": " + p); 2821 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2822 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2823 if (ps == null) return null; 2824 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2825 userId); 2826 } 2827 } 2828 return null; 2829 } 2830 2831 @Override 2832 public String[] getSystemSharedLibraryNames() { 2833 Set<String> libSet; 2834 synchronized (mPackages) { 2835 libSet = mSharedLibraries.keySet(); 2836 int size = libSet.size(); 2837 if (size > 0) { 2838 String[] libs = new String[size]; 2839 libSet.toArray(libs); 2840 return libs; 2841 } 2842 } 2843 return null; 2844 } 2845 2846 /** 2847 * @hide 2848 */ 2849 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2850 synchronized (mPackages) { 2851 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2852 if (lib != null && lib.apk != null) { 2853 return mPackages.get(lib.apk); 2854 } 2855 } 2856 return null; 2857 } 2858 2859 @Override 2860 public FeatureInfo[] getSystemAvailableFeatures() { 2861 Collection<FeatureInfo> featSet; 2862 synchronized (mPackages) { 2863 featSet = mAvailableFeatures.values(); 2864 int size = featSet.size(); 2865 if (size > 0) { 2866 FeatureInfo[] features = new FeatureInfo[size+1]; 2867 featSet.toArray(features); 2868 FeatureInfo fi = new FeatureInfo(); 2869 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2870 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2871 features[size] = fi; 2872 return features; 2873 } 2874 } 2875 return null; 2876 } 2877 2878 @Override 2879 public boolean hasSystemFeature(String name) { 2880 synchronized (mPackages) { 2881 return mAvailableFeatures.containsKey(name); 2882 } 2883 } 2884 2885 private void checkValidCaller(int uid, int userId) { 2886 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2887 return; 2888 2889 throw new SecurityException("Caller uid=" + uid 2890 + " is not privileged to communicate with user=" + userId); 2891 } 2892 2893 @Override 2894 public int checkPermission(String permName, String pkgName, int userId) { 2895 if (!sUserManager.exists(userId)) { 2896 return PackageManager.PERMISSION_DENIED; 2897 } 2898 2899 synchronized (mPackages) { 2900 final PackageParser.Package p = mPackages.get(pkgName); 2901 if (p != null && p.mExtras != null) { 2902 final PackageSetting ps = (PackageSetting) p.mExtras; 2903 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2904 return PackageManager.PERMISSION_GRANTED; 2905 } 2906 } 2907 } 2908 2909 return PackageManager.PERMISSION_DENIED; 2910 } 2911 2912 @Override 2913 public int checkUidPermission(String permName, int uid) { 2914 final int userId = UserHandle.getUserId(uid); 2915 2916 if (!sUserManager.exists(userId)) { 2917 return PackageManager.PERMISSION_DENIED; 2918 } 2919 2920 synchronized (mPackages) { 2921 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2922 if (obj != null) { 2923 final SettingBase ps = (SettingBase) obj; 2924 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2925 return PackageManager.PERMISSION_GRANTED; 2926 } 2927 } else { 2928 ArraySet<String> perms = mSystemPermissions.get(uid); 2929 if (perms != null && perms.contains(permName)) { 2930 return PackageManager.PERMISSION_GRANTED; 2931 } 2932 } 2933 } 2934 2935 return PackageManager.PERMISSION_DENIED; 2936 } 2937 2938 /** 2939 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2940 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2941 * @param checkShell TODO(yamasani): 2942 * @param message the message to log on security exception 2943 */ 2944 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2945 boolean checkShell, String message) { 2946 if (userId < 0) { 2947 throw new IllegalArgumentException("Invalid userId " + userId); 2948 } 2949 if (checkShell) { 2950 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2951 } 2952 if (userId == UserHandle.getUserId(callingUid)) return; 2953 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2954 if (requireFullPermission) { 2955 mContext.enforceCallingOrSelfPermission( 2956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2957 } else { 2958 try { 2959 mContext.enforceCallingOrSelfPermission( 2960 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2961 } catch (SecurityException se) { 2962 mContext.enforceCallingOrSelfPermission( 2963 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2964 } 2965 } 2966 } 2967 } 2968 2969 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2970 if (callingUid == Process.SHELL_UID) { 2971 if (userHandle >= 0 2972 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2973 throw new SecurityException("Shell does not have permission to access user " 2974 + userHandle); 2975 } else if (userHandle < 0) { 2976 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2977 + Debug.getCallers(3)); 2978 } 2979 } 2980 } 2981 2982 private BasePermission findPermissionTreeLP(String permName) { 2983 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2984 if (permName.startsWith(bp.name) && 2985 permName.length() > bp.name.length() && 2986 permName.charAt(bp.name.length()) == '.') { 2987 return bp; 2988 } 2989 } 2990 return null; 2991 } 2992 2993 private BasePermission checkPermissionTreeLP(String permName) { 2994 if (permName != null) { 2995 BasePermission bp = findPermissionTreeLP(permName); 2996 if (bp != null) { 2997 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2998 return bp; 2999 } 3000 throw new SecurityException("Calling uid " 3001 + Binder.getCallingUid() 3002 + " is not allowed to add to permission tree " 3003 + bp.name + " owned by uid " + bp.uid); 3004 } 3005 } 3006 throw new SecurityException("No permission tree found for " + permName); 3007 } 3008 3009 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3010 if (s1 == null) { 3011 return s2 == null; 3012 } 3013 if (s2 == null) { 3014 return false; 3015 } 3016 if (s1.getClass() != s2.getClass()) { 3017 return false; 3018 } 3019 return s1.equals(s2); 3020 } 3021 3022 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3023 if (pi1.icon != pi2.icon) return false; 3024 if (pi1.logo != pi2.logo) return false; 3025 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3026 if (!compareStrings(pi1.name, pi2.name)) return false; 3027 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3028 // We'll take care of setting this one. 3029 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3030 // These are not currently stored in settings. 3031 //if (!compareStrings(pi1.group, pi2.group)) return false; 3032 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3033 //if (pi1.labelRes != pi2.labelRes) return false; 3034 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3035 return true; 3036 } 3037 3038 int permissionInfoFootprint(PermissionInfo info) { 3039 int size = info.name.length(); 3040 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3041 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3042 return size; 3043 } 3044 3045 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3046 int size = 0; 3047 for (BasePermission perm : mSettings.mPermissions.values()) { 3048 if (perm.uid == tree.uid) { 3049 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3050 } 3051 } 3052 return size; 3053 } 3054 3055 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3056 // We calculate the max size of permissions defined by this uid and throw 3057 // if that plus the size of 'info' would exceed our stated maximum. 3058 if (tree.uid != Process.SYSTEM_UID) { 3059 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3060 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3061 throw new SecurityException("Permission tree size cap exceeded"); 3062 } 3063 } 3064 } 3065 3066 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3067 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3068 throw new SecurityException("Label must be specified in permission"); 3069 } 3070 BasePermission tree = checkPermissionTreeLP(info.name); 3071 BasePermission bp = mSettings.mPermissions.get(info.name); 3072 boolean added = bp == null; 3073 boolean changed = true; 3074 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3075 if (added) { 3076 enforcePermissionCapLocked(info, tree); 3077 bp = new BasePermission(info.name, tree.sourcePackage, 3078 BasePermission.TYPE_DYNAMIC); 3079 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3080 throw new SecurityException( 3081 "Not allowed to modify non-dynamic permission " 3082 + info.name); 3083 } else { 3084 if (bp.protectionLevel == fixedLevel 3085 && bp.perm.owner.equals(tree.perm.owner) 3086 && bp.uid == tree.uid 3087 && comparePermissionInfos(bp.perm.info, info)) { 3088 changed = false; 3089 } 3090 } 3091 bp.protectionLevel = fixedLevel; 3092 info = new PermissionInfo(info); 3093 info.protectionLevel = fixedLevel; 3094 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3095 bp.perm.info.packageName = tree.perm.info.packageName; 3096 bp.uid = tree.uid; 3097 if (added) { 3098 mSettings.mPermissions.put(info.name, bp); 3099 } 3100 if (changed) { 3101 if (!async) { 3102 mSettings.writeLPr(); 3103 } else { 3104 scheduleWriteSettingsLocked(); 3105 } 3106 } 3107 return added; 3108 } 3109 3110 @Override 3111 public boolean addPermission(PermissionInfo info) { 3112 synchronized (mPackages) { 3113 return addPermissionLocked(info, false); 3114 } 3115 } 3116 3117 @Override 3118 public boolean addPermissionAsync(PermissionInfo info) { 3119 synchronized (mPackages) { 3120 return addPermissionLocked(info, true); 3121 } 3122 } 3123 3124 @Override 3125 public void removePermission(String name) { 3126 synchronized (mPackages) { 3127 checkPermissionTreeLP(name); 3128 BasePermission bp = mSettings.mPermissions.get(name); 3129 if (bp != null) { 3130 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3131 throw new SecurityException( 3132 "Not allowed to modify non-dynamic permission " 3133 + name); 3134 } 3135 mSettings.mPermissions.remove(name); 3136 mSettings.writeLPr(); 3137 } 3138 } 3139 } 3140 3141 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3142 BasePermission bp) { 3143 int index = pkg.requestedPermissions.indexOf(bp.name); 3144 if (index == -1) { 3145 throw new SecurityException("Package " + pkg.packageName 3146 + " has not requested permission " + bp.name); 3147 } 3148 if (!bp.isRuntime()) { 3149 throw new SecurityException("Permission " + bp.name 3150 + " is not a changeable permission type"); 3151 } 3152 } 3153 3154 @Override 3155 public void grantRuntimePermission(String packageName, String name, int userId) { 3156 if (!sUserManager.exists(userId)) { 3157 Log.e(TAG, "No such user:" + userId); 3158 return; 3159 } 3160 3161 mContext.enforceCallingOrSelfPermission( 3162 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3163 "grantRuntimePermission"); 3164 3165 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3166 "grantRuntimePermission"); 3167 3168 boolean gidsChanged = false; 3169 final SettingBase sb; 3170 3171 synchronized (mPackages) { 3172 final PackageParser.Package pkg = mPackages.get(packageName); 3173 if (pkg == null) { 3174 throw new IllegalArgumentException("Unknown package: " + packageName); 3175 } 3176 3177 final BasePermission bp = mSettings.mPermissions.get(name); 3178 if (bp == null) { 3179 throw new IllegalArgumentException("Unknown permission: " + name); 3180 } 3181 3182 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3183 3184 sb = (SettingBase) pkg.mExtras; 3185 if (sb == null) { 3186 throw new IllegalArgumentException("Unknown package: " + packageName); 3187 } 3188 3189 final PermissionsState permissionsState = sb.getPermissionsState(); 3190 3191 final int flags = permissionsState.getPermissionFlags(name, userId); 3192 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3193 throw new SecurityException("Cannot grant system fixed permission: " 3194 + name + " for package: " + packageName); 3195 } 3196 3197 final int result = permissionsState.grantRuntimePermission(bp, userId); 3198 switch (result) { 3199 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3200 return; 3201 } 3202 3203 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3204 gidsChanged = true; 3205 } break; 3206 } 3207 3208 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3209 3210 // Not critical if that is lost - app has to request again. 3211 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3212 } 3213 3214 if (gidsChanged) { 3215 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3216 } 3217 } 3218 3219 @Override 3220 public void revokeRuntimePermission(String packageName, String name, int userId) { 3221 if (!sUserManager.exists(userId)) { 3222 Log.e(TAG, "No such user:" + userId); 3223 return; 3224 } 3225 3226 mContext.enforceCallingOrSelfPermission( 3227 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3228 "revokeRuntimePermission"); 3229 3230 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3231 "revokeRuntimePermission"); 3232 3233 final SettingBase sb; 3234 3235 synchronized (mPackages) { 3236 final PackageParser.Package pkg = mPackages.get(packageName); 3237 if (pkg == null) { 3238 throw new IllegalArgumentException("Unknown package: " + packageName); 3239 } 3240 3241 final BasePermission bp = mSettings.mPermissions.get(name); 3242 if (bp == null) { 3243 throw new IllegalArgumentException("Unknown permission: " + name); 3244 } 3245 3246 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3247 3248 sb = (SettingBase) pkg.mExtras; 3249 if (sb == null) { 3250 throw new IllegalArgumentException("Unknown package: " + packageName); 3251 } 3252 3253 final PermissionsState permissionsState = sb.getPermissionsState(); 3254 3255 final int flags = permissionsState.getPermissionFlags(name, userId); 3256 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3257 throw new SecurityException("Cannot revoke system fixed permission: " 3258 + name + " for package: " + packageName); 3259 } 3260 3261 if (permissionsState.revokeRuntimePermission(bp, userId) == 3262 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3263 return; 3264 } 3265 3266 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3267 3268 // Critical, after this call app should never have the permission. 3269 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3270 } 3271 3272 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3273 } 3274 3275 @Override 3276 public int getPermissionFlags(String name, String packageName, int userId) { 3277 if (!sUserManager.exists(userId)) { 3278 return 0; 3279 } 3280 3281 mContext.enforceCallingOrSelfPermission( 3282 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3283 "getPermissionFlags"); 3284 3285 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3286 "getPermissionFlags"); 3287 3288 synchronized (mPackages) { 3289 final PackageParser.Package pkg = mPackages.get(packageName); 3290 if (pkg == null) { 3291 throw new IllegalArgumentException("Unknown package: " + packageName); 3292 } 3293 3294 final BasePermission bp = mSettings.mPermissions.get(name); 3295 if (bp == null) { 3296 throw new IllegalArgumentException("Unknown permission: " + name); 3297 } 3298 3299 SettingBase sb = (SettingBase) pkg.mExtras; 3300 if (sb == null) { 3301 throw new IllegalArgumentException("Unknown package: " + packageName); 3302 } 3303 3304 PermissionsState permissionsState = sb.getPermissionsState(); 3305 return permissionsState.getPermissionFlags(name, userId); 3306 } 3307 } 3308 3309 @Override 3310 public void updatePermissionFlags(String name, String packageName, int flagMask, 3311 int flagValues, int userId) { 3312 if (!sUserManager.exists(userId)) { 3313 return; 3314 } 3315 3316 mContext.enforceCallingOrSelfPermission( 3317 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3318 "updatePermissionFlags"); 3319 3320 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3321 "updatePermissionFlags"); 3322 3323 // Only the system can change policy flags. 3324 if (getCallingUid() != Process.SYSTEM_UID) { 3325 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3326 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3327 } 3328 3329 // Only the package manager can change system flags. 3330 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3331 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3332 3333 synchronized (mPackages) { 3334 final PackageParser.Package pkg = mPackages.get(packageName); 3335 if (pkg == null) { 3336 throw new IllegalArgumentException("Unknown package: " + packageName); 3337 } 3338 3339 final BasePermission bp = mSettings.mPermissions.get(name); 3340 if (bp == null) { 3341 throw new IllegalArgumentException("Unknown permission: " + name); 3342 } 3343 3344 SettingBase sb = (SettingBase) pkg.mExtras; 3345 if (sb == null) { 3346 throw new IllegalArgumentException("Unknown package: " + packageName); 3347 } 3348 3349 PermissionsState permissionsState = sb.getPermissionsState(); 3350 3351 // Only the package manager can change flags for system component permissions. 3352 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3353 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3354 return; 3355 } 3356 3357 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3358 // Install and runtime permissions are stored in different places, 3359 // so figure out what permission changed and persist the change. 3360 if (permissionsState.getInstallPermissionState(name) != null) { 3361 scheduleWriteSettingsLocked(); 3362 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3363 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3364 } 3365 } 3366 } 3367 } 3368 3369 @Override 3370 public boolean shouldShowRequestPermissionRationale(String permissionName, 3371 String packageName, int userId) { 3372 if (UserHandle.getCallingUserId() != userId) { 3373 mContext.enforceCallingPermission( 3374 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3375 "canShowRequestPermissionRationale for user " + userId); 3376 } 3377 3378 final int uid = getPackageUid(packageName, userId); 3379 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3380 return false; 3381 } 3382 3383 if (checkPermission(permissionName, packageName, userId) 3384 == PackageManager.PERMISSION_GRANTED) { 3385 return false; 3386 } 3387 3388 final int flags; 3389 3390 final long identity = Binder.clearCallingIdentity(); 3391 try { 3392 flags = getPermissionFlags(permissionName, 3393 packageName, userId); 3394 } finally { 3395 Binder.restoreCallingIdentity(identity); 3396 } 3397 3398 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3399 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3400 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3401 3402 if ((flags & fixedFlags) != 0) { 3403 return false; 3404 } 3405 3406 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3407 } 3408 3409 @Override 3410 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3411 mContext.enforceCallingOrSelfPermission( 3412 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3413 "addOnPermissionsChangeListener"); 3414 3415 synchronized (mPackages) { 3416 mOnPermissionChangeListeners.addListenerLocked(listener); 3417 } 3418 } 3419 3420 @Override 3421 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3422 synchronized (mPackages) { 3423 mOnPermissionChangeListeners.removeListenerLocked(listener); 3424 } 3425 } 3426 3427 @Override 3428 public boolean isProtectedBroadcast(String actionName) { 3429 synchronized (mPackages) { 3430 return mProtectedBroadcasts.contains(actionName); 3431 } 3432 } 3433 3434 @Override 3435 public int checkSignatures(String pkg1, String pkg2) { 3436 synchronized (mPackages) { 3437 final PackageParser.Package p1 = mPackages.get(pkg1); 3438 final PackageParser.Package p2 = mPackages.get(pkg2); 3439 if (p1 == null || p1.mExtras == null 3440 || p2 == null || p2.mExtras == null) { 3441 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3442 } 3443 return compareSignatures(p1.mSignatures, p2.mSignatures); 3444 } 3445 } 3446 3447 @Override 3448 public int checkUidSignatures(int uid1, int uid2) { 3449 // Map to base uids. 3450 uid1 = UserHandle.getAppId(uid1); 3451 uid2 = UserHandle.getAppId(uid2); 3452 // reader 3453 synchronized (mPackages) { 3454 Signature[] s1; 3455 Signature[] s2; 3456 Object obj = mSettings.getUserIdLPr(uid1); 3457 if (obj != null) { 3458 if (obj instanceof SharedUserSetting) { 3459 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3460 } else if (obj instanceof PackageSetting) { 3461 s1 = ((PackageSetting)obj).signatures.mSignatures; 3462 } else { 3463 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3464 } 3465 } else { 3466 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3467 } 3468 obj = mSettings.getUserIdLPr(uid2); 3469 if (obj != null) { 3470 if (obj instanceof SharedUserSetting) { 3471 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3472 } else if (obj instanceof PackageSetting) { 3473 s2 = ((PackageSetting)obj).signatures.mSignatures; 3474 } else { 3475 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3476 } 3477 } else { 3478 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3479 } 3480 return compareSignatures(s1, s2); 3481 } 3482 } 3483 3484 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3485 final long identity = Binder.clearCallingIdentity(); 3486 try { 3487 if (sb instanceof SharedUserSetting) { 3488 SharedUserSetting sus = (SharedUserSetting) sb; 3489 final int packageCount = sus.packages.size(); 3490 for (int i = 0; i < packageCount; i++) { 3491 PackageSetting susPs = sus.packages.valueAt(i); 3492 if (userId == UserHandle.USER_ALL) { 3493 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3494 } else { 3495 final int uid = UserHandle.getUid(userId, susPs.appId); 3496 killUid(uid, reason); 3497 } 3498 } 3499 } else if (sb instanceof PackageSetting) { 3500 PackageSetting ps = (PackageSetting) sb; 3501 if (userId == UserHandle.USER_ALL) { 3502 killApplication(ps.pkg.packageName, ps.appId, reason); 3503 } else { 3504 final int uid = UserHandle.getUid(userId, ps.appId); 3505 killUid(uid, reason); 3506 } 3507 } 3508 } finally { 3509 Binder.restoreCallingIdentity(identity); 3510 } 3511 } 3512 3513 private static void killUid(int uid, String reason) { 3514 IActivityManager am = ActivityManagerNative.getDefault(); 3515 if (am != null) { 3516 try { 3517 am.killUid(uid, reason); 3518 } catch (RemoteException e) { 3519 /* ignore - same process */ 3520 } 3521 } 3522 } 3523 3524 /** 3525 * Compares two sets of signatures. Returns: 3526 * <br /> 3527 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3528 * <br /> 3529 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3530 * <br /> 3531 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3532 * <br /> 3533 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3534 * <br /> 3535 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3536 */ 3537 static int compareSignatures(Signature[] s1, Signature[] s2) { 3538 if (s1 == null) { 3539 return s2 == null 3540 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3541 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3542 } 3543 3544 if (s2 == null) { 3545 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3546 } 3547 3548 if (s1.length != s2.length) { 3549 return PackageManager.SIGNATURE_NO_MATCH; 3550 } 3551 3552 // Since both signature sets are of size 1, we can compare without HashSets. 3553 if (s1.length == 1) { 3554 return s1[0].equals(s2[0]) ? 3555 PackageManager.SIGNATURE_MATCH : 3556 PackageManager.SIGNATURE_NO_MATCH; 3557 } 3558 3559 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3560 for (Signature sig : s1) { 3561 set1.add(sig); 3562 } 3563 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3564 for (Signature sig : s2) { 3565 set2.add(sig); 3566 } 3567 // Make sure s2 contains all signatures in s1. 3568 if (set1.equals(set2)) { 3569 return PackageManager.SIGNATURE_MATCH; 3570 } 3571 return PackageManager.SIGNATURE_NO_MATCH; 3572 } 3573 3574 /** 3575 * If the database version for this type of package (internal storage or 3576 * external storage) is less than the version where package signatures 3577 * were updated, return true. 3578 */ 3579 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3580 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3581 DatabaseVersion.SIGNATURE_END_ENTITY)) 3582 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3583 DatabaseVersion.SIGNATURE_END_ENTITY)); 3584 } 3585 3586 /** 3587 * Used for backward compatibility to make sure any packages with 3588 * certificate chains get upgraded to the new style. {@code existingSigs} 3589 * will be in the old format (since they were stored on disk from before the 3590 * system upgrade) and {@code scannedSigs} will be in the newer format. 3591 */ 3592 private int compareSignaturesCompat(PackageSignatures existingSigs, 3593 PackageParser.Package scannedPkg) { 3594 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3595 return PackageManager.SIGNATURE_NO_MATCH; 3596 } 3597 3598 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3599 for (Signature sig : existingSigs.mSignatures) { 3600 existingSet.add(sig); 3601 } 3602 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3603 for (Signature sig : scannedPkg.mSignatures) { 3604 try { 3605 Signature[] chainSignatures = sig.getChainSignatures(); 3606 for (Signature chainSig : chainSignatures) { 3607 scannedCompatSet.add(chainSig); 3608 } 3609 } catch (CertificateEncodingException e) { 3610 scannedCompatSet.add(sig); 3611 } 3612 } 3613 /* 3614 * Make sure the expanded scanned set contains all signatures in the 3615 * existing one. 3616 */ 3617 if (scannedCompatSet.equals(existingSet)) { 3618 // Migrate the old signatures to the new scheme. 3619 existingSigs.assignSignatures(scannedPkg.mSignatures); 3620 // The new KeySets will be re-added later in the scanning process. 3621 synchronized (mPackages) { 3622 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3623 } 3624 return PackageManager.SIGNATURE_MATCH; 3625 } 3626 return PackageManager.SIGNATURE_NO_MATCH; 3627 } 3628 3629 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3630 if (isExternal(scannedPkg)) { 3631 return mSettings.isExternalDatabaseVersionOlderThan( 3632 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3633 } else { 3634 return mSettings.isInternalDatabaseVersionOlderThan( 3635 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3636 } 3637 } 3638 3639 private int compareSignaturesRecover(PackageSignatures existingSigs, 3640 PackageParser.Package scannedPkg) { 3641 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3642 return PackageManager.SIGNATURE_NO_MATCH; 3643 } 3644 3645 String msg = null; 3646 try { 3647 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3648 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3649 + scannedPkg.packageName); 3650 return PackageManager.SIGNATURE_MATCH; 3651 } 3652 } catch (CertificateException e) { 3653 msg = e.getMessage(); 3654 } 3655 3656 logCriticalInfo(Log.INFO, 3657 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3658 return PackageManager.SIGNATURE_NO_MATCH; 3659 } 3660 3661 @Override 3662 public String[] getPackagesForUid(int uid) { 3663 uid = UserHandle.getAppId(uid); 3664 // reader 3665 synchronized (mPackages) { 3666 Object obj = mSettings.getUserIdLPr(uid); 3667 if (obj instanceof SharedUserSetting) { 3668 final SharedUserSetting sus = (SharedUserSetting) obj; 3669 final int N = sus.packages.size(); 3670 final String[] res = new String[N]; 3671 final Iterator<PackageSetting> it = sus.packages.iterator(); 3672 int i = 0; 3673 while (it.hasNext()) { 3674 res[i++] = it.next().name; 3675 } 3676 return res; 3677 } else if (obj instanceof PackageSetting) { 3678 final PackageSetting ps = (PackageSetting) obj; 3679 return new String[] { ps.name }; 3680 } 3681 } 3682 return null; 3683 } 3684 3685 @Override 3686 public String getNameForUid(int uid) { 3687 // reader 3688 synchronized (mPackages) { 3689 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3690 if (obj instanceof SharedUserSetting) { 3691 final SharedUserSetting sus = (SharedUserSetting) obj; 3692 return sus.name + ":" + sus.userId; 3693 } else if (obj instanceof PackageSetting) { 3694 final PackageSetting ps = (PackageSetting) obj; 3695 return ps.name; 3696 } 3697 } 3698 return null; 3699 } 3700 3701 @Override 3702 public int getUidForSharedUser(String sharedUserName) { 3703 if(sharedUserName == null) { 3704 return -1; 3705 } 3706 // reader 3707 synchronized (mPackages) { 3708 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3709 if (suid == null) { 3710 return -1; 3711 } 3712 return suid.userId; 3713 } 3714 } 3715 3716 @Override 3717 public int getFlagsForUid(int uid) { 3718 synchronized (mPackages) { 3719 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3720 if (obj instanceof SharedUserSetting) { 3721 final SharedUserSetting sus = (SharedUserSetting) obj; 3722 return sus.pkgFlags; 3723 } else if (obj instanceof PackageSetting) { 3724 final PackageSetting ps = (PackageSetting) obj; 3725 return ps.pkgFlags; 3726 } 3727 } 3728 return 0; 3729 } 3730 3731 @Override 3732 public int getPrivateFlagsForUid(int uid) { 3733 synchronized (mPackages) { 3734 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3735 if (obj instanceof SharedUserSetting) { 3736 final SharedUserSetting sus = (SharedUserSetting) obj; 3737 return sus.pkgPrivateFlags; 3738 } else if (obj instanceof PackageSetting) { 3739 final PackageSetting ps = (PackageSetting) obj; 3740 return ps.pkgPrivateFlags; 3741 } 3742 } 3743 return 0; 3744 } 3745 3746 @Override 3747 public boolean isUidPrivileged(int uid) { 3748 uid = UserHandle.getAppId(uid); 3749 // reader 3750 synchronized (mPackages) { 3751 Object obj = mSettings.getUserIdLPr(uid); 3752 if (obj instanceof SharedUserSetting) { 3753 final SharedUserSetting sus = (SharedUserSetting) obj; 3754 final Iterator<PackageSetting> it = sus.packages.iterator(); 3755 while (it.hasNext()) { 3756 if (it.next().isPrivileged()) { 3757 return true; 3758 } 3759 } 3760 } else if (obj instanceof PackageSetting) { 3761 final PackageSetting ps = (PackageSetting) obj; 3762 return ps.isPrivileged(); 3763 } 3764 } 3765 return false; 3766 } 3767 3768 @Override 3769 public String[] getAppOpPermissionPackages(String permissionName) { 3770 synchronized (mPackages) { 3771 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3772 if (pkgs == null) { 3773 return null; 3774 } 3775 return pkgs.toArray(new String[pkgs.size()]); 3776 } 3777 } 3778 3779 @Override 3780 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3781 int flags, int userId) { 3782 if (!sUserManager.exists(userId)) return null; 3783 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3784 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3785 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3786 } 3787 3788 @Override 3789 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3790 IntentFilter filter, int match, ComponentName activity) { 3791 final int userId = UserHandle.getCallingUserId(); 3792 if (DEBUG_PREFERRED) { 3793 Log.v(TAG, "setLastChosenActivity intent=" + intent 3794 + " resolvedType=" + resolvedType 3795 + " flags=" + flags 3796 + " filter=" + filter 3797 + " match=" + match 3798 + " activity=" + activity); 3799 filter.dump(new PrintStreamPrinter(System.out), " "); 3800 } 3801 intent.setComponent(null); 3802 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3803 // Find any earlier preferred or last chosen entries and nuke them 3804 findPreferredActivity(intent, resolvedType, 3805 flags, query, 0, false, true, false, userId); 3806 // Add the new activity as the last chosen for this filter 3807 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3808 "Setting last chosen"); 3809 } 3810 3811 @Override 3812 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3813 final int userId = UserHandle.getCallingUserId(); 3814 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3815 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3816 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3817 false, false, false, userId); 3818 } 3819 3820 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3821 int flags, List<ResolveInfo> query, int userId) { 3822 if (query != null) { 3823 final int N = query.size(); 3824 if (N == 1) { 3825 return query.get(0); 3826 } else if (N > 1) { 3827 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3828 // If there is more than one activity with the same priority, 3829 // then let the user decide between them. 3830 ResolveInfo r0 = query.get(0); 3831 ResolveInfo r1 = query.get(1); 3832 if (DEBUG_INTENT_MATCHING || debug) { 3833 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3834 + r1.activityInfo.name + "=" + r1.priority); 3835 } 3836 // If the first activity has a higher priority, or a different 3837 // default, then it is always desireable to pick it. 3838 if (r0.priority != r1.priority 3839 || r0.preferredOrder != r1.preferredOrder 3840 || r0.isDefault != r1.isDefault) { 3841 return query.get(0); 3842 } 3843 // If we have saved a preference for a preferred activity for 3844 // this Intent, use that. 3845 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3846 flags, query, r0.priority, true, false, debug, userId); 3847 if (ri != null) { 3848 return ri; 3849 } 3850 if (userId != 0) { 3851 ri = new ResolveInfo(mResolveInfo); 3852 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3853 ri.activityInfo.applicationInfo = new ApplicationInfo( 3854 ri.activityInfo.applicationInfo); 3855 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3856 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3857 return ri; 3858 } 3859 return mResolveInfo; 3860 } 3861 } 3862 return null; 3863 } 3864 3865 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3866 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3867 final int N = query.size(); 3868 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3869 .get(userId); 3870 // Get the list of persistent preferred activities that handle the intent 3871 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3872 List<PersistentPreferredActivity> pprefs = ppir != null 3873 ? ppir.queryIntent(intent, resolvedType, 3874 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3875 : null; 3876 if (pprefs != null && pprefs.size() > 0) { 3877 final int M = pprefs.size(); 3878 for (int i=0; i<M; i++) { 3879 final PersistentPreferredActivity ppa = pprefs.get(i); 3880 if (DEBUG_PREFERRED || debug) { 3881 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3882 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3883 + "\n component=" + ppa.mComponent); 3884 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3885 } 3886 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3887 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3888 if (DEBUG_PREFERRED || debug) { 3889 Slog.v(TAG, "Found persistent preferred activity:"); 3890 if (ai != null) { 3891 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3892 } else { 3893 Slog.v(TAG, " null"); 3894 } 3895 } 3896 if (ai == null) { 3897 // This previously registered persistent preferred activity 3898 // component is no longer known. Ignore it and do NOT remove it. 3899 continue; 3900 } 3901 for (int j=0; j<N; j++) { 3902 final ResolveInfo ri = query.get(j); 3903 if (!ri.activityInfo.applicationInfo.packageName 3904 .equals(ai.applicationInfo.packageName)) { 3905 continue; 3906 } 3907 if (!ri.activityInfo.name.equals(ai.name)) { 3908 continue; 3909 } 3910 // Found a persistent preference that can handle the intent. 3911 if (DEBUG_PREFERRED || debug) { 3912 Slog.v(TAG, "Returning persistent preferred activity: " + 3913 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3914 } 3915 return ri; 3916 } 3917 } 3918 } 3919 return null; 3920 } 3921 3922 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3923 List<ResolveInfo> query, int priority, boolean always, 3924 boolean removeMatches, boolean debug, int userId) { 3925 if (!sUserManager.exists(userId)) return null; 3926 // writer 3927 synchronized (mPackages) { 3928 if (intent.getSelector() != null) { 3929 intent = intent.getSelector(); 3930 } 3931 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3932 3933 // Try to find a matching persistent preferred activity. 3934 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3935 debug, userId); 3936 3937 // If a persistent preferred activity matched, use it. 3938 if (pri != null) { 3939 return pri; 3940 } 3941 3942 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3943 // Get the list of preferred activities that handle the intent 3944 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3945 List<PreferredActivity> prefs = pir != null 3946 ? pir.queryIntent(intent, resolvedType, 3947 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3948 : null; 3949 if (prefs != null && prefs.size() > 0) { 3950 boolean changed = false; 3951 try { 3952 // First figure out how good the original match set is. 3953 // We will only allow preferred activities that came 3954 // from the same match quality. 3955 int match = 0; 3956 3957 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3958 3959 final int N = query.size(); 3960 for (int j=0; j<N; j++) { 3961 final ResolveInfo ri = query.get(j); 3962 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3963 + ": 0x" + Integer.toHexString(match)); 3964 if (ri.match > match) { 3965 match = ri.match; 3966 } 3967 } 3968 3969 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3970 + Integer.toHexString(match)); 3971 3972 match &= IntentFilter.MATCH_CATEGORY_MASK; 3973 final int M = prefs.size(); 3974 for (int i=0; i<M; i++) { 3975 final PreferredActivity pa = prefs.get(i); 3976 if (DEBUG_PREFERRED || debug) { 3977 Slog.v(TAG, "Checking PreferredActivity ds=" 3978 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3979 + "\n component=" + pa.mPref.mComponent); 3980 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3981 } 3982 if (pa.mPref.mMatch != match) { 3983 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3984 + Integer.toHexString(pa.mPref.mMatch)); 3985 continue; 3986 } 3987 // If it's not an "always" type preferred activity and that's what we're 3988 // looking for, skip it. 3989 if (always && !pa.mPref.mAlways) { 3990 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3991 continue; 3992 } 3993 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3994 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3995 if (DEBUG_PREFERRED || debug) { 3996 Slog.v(TAG, "Found preferred activity:"); 3997 if (ai != null) { 3998 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3999 } else { 4000 Slog.v(TAG, " null"); 4001 } 4002 } 4003 if (ai == null) { 4004 // This previously registered preferred activity 4005 // component is no longer known. Most likely an update 4006 // to the app was installed and in the new version this 4007 // component no longer exists. Clean it up by removing 4008 // it from the preferred activities list, and skip it. 4009 Slog.w(TAG, "Removing dangling preferred activity: " 4010 + pa.mPref.mComponent); 4011 pir.removeFilter(pa); 4012 changed = true; 4013 continue; 4014 } 4015 for (int j=0; j<N; j++) { 4016 final ResolveInfo ri = query.get(j); 4017 if (!ri.activityInfo.applicationInfo.packageName 4018 .equals(ai.applicationInfo.packageName)) { 4019 continue; 4020 } 4021 if (!ri.activityInfo.name.equals(ai.name)) { 4022 continue; 4023 } 4024 4025 if (removeMatches) { 4026 pir.removeFilter(pa); 4027 changed = true; 4028 if (DEBUG_PREFERRED) { 4029 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4030 } 4031 break; 4032 } 4033 4034 // Okay we found a previously set preferred or last chosen app. 4035 // If the result set is different from when this 4036 // was created, we need to clear it and re-ask the 4037 // user their preference, if we're looking for an "always" type entry. 4038 if (always && !pa.mPref.sameSet(query)) { 4039 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4040 + intent + " type " + resolvedType); 4041 if (DEBUG_PREFERRED) { 4042 Slog.v(TAG, "Removing preferred activity since set changed " 4043 + pa.mPref.mComponent); 4044 } 4045 pir.removeFilter(pa); 4046 // Re-add the filter as a "last chosen" entry (!always) 4047 PreferredActivity lastChosen = new PreferredActivity( 4048 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4049 pir.addFilter(lastChosen); 4050 changed = true; 4051 return null; 4052 } 4053 4054 // Yay! Either the set matched or we're looking for the last chosen 4055 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4056 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4057 return ri; 4058 } 4059 } 4060 } finally { 4061 if (changed) { 4062 if (DEBUG_PREFERRED) { 4063 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4064 } 4065 scheduleWritePackageRestrictionsLocked(userId); 4066 } 4067 } 4068 } 4069 } 4070 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4071 return null; 4072 } 4073 4074 /* 4075 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4076 */ 4077 @Override 4078 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4079 int targetUserId) { 4080 mContext.enforceCallingOrSelfPermission( 4081 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4082 List<CrossProfileIntentFilter> matches = 4083 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4084 if (matches != null) { 4085 int size = matches.size(); 4086 for (int i = 0; i < size; i++) { 4087 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4088 } 4089 } 4090 return false; 4091 } 4092 4093 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4094 String resolvedType, int userId) { 4095 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4096 if (resolver != null) { 4097 return resolver.queryIntent(intent, resolvedType, false, userId); 4098 } 4099 return null; 4100 } 4101 4102 @Override 4103 public List<ResolveInfo> queryIntentActivities(Intent intent, 4104 String resolvedType, int flags, int userId) { 4105 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4106 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4107 ComponentName comp = intent.getComponent(); 4108 if (comp == null) { 4109 if (intent.getSelector() != null) { 4110 intent = intent.getSelector(); 4111 comp = intent.getComponent(); 4112 } 4113 } 4114 4115 if (comp != null) { 4116 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4117 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4118 if (ai != null) { 4119 final ResolveInfo ri = new ResolveInfo(); 4120 ri.activityInfo = ai; 4121 list.add(ri); 4122 } 4123 return list; 4124 } 4125 4126 // reader 4127 synchronized (mPackages) { 4128 final String pkgName = intent.getPackage(); 4129 if (pkgName == null) { 4130 List<CrossProfileIntentFilter> matchingFilters = 4131 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4132 // Check for results that need to skip the current profile. 4133 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4134 resolvedType, flags, userId); 4135 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4136 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4137 result.add(resolveInfo); 4138 return filterIfNotPrimaryUser(result, userId); 4139 } 4140 4141 // Check for results in the current profile. 4142 List<ResolveInfo> result = mActivities.queryIntent( 4143 intent, resolvedType, flags, userId); 4144 4145 // Check for cross profile results. 4146 resolveInfo = queryCrossProfileIntents( 4147 matchingFilters, intent, resolvedType, flags, userId); 4148 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4149 result.add(resolveInfo); 4150 Collections.sort(result, mResolvePrioritySorter); 4151 } 4152 result = filterIfNotPrimaryUser(result, userId); 4153 if (result.size() > 1 && hasWebURI(intent)) { 4154 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4155 } 4156 return result; 4157 } 4158 final PackageParser.Package pkg = mPackages.get(pkgName); 4159 if (pkg != null) { 4160 return filterIfNotPrimaryUser( 4161 mActivities.queryIntentForPackage( 4162 intent, resolvedType, flags, pkg.activities, userId), 4163 userId); 4164 } 4165 return new ArrayList<ResolveInfo>(); 4166 } 4167 } 4168 4169 private boolean isUserEnabled(int userId) { 4170 long callingId = Binder.clearCallingIdentity(); 4171 try { 4172 UserInfo userInfo = sUserManager.getUserInfo(userId); 4173 return userInfo != null && userInfo.isEnabled(); 4174 } finally { 4175 Binder.restoreCallingIdentity(callingId); 4176 } 4177 } 4178 4179 /** 4180 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4181 * 4182 * @return filtered list 4183 */ 4184 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4185 if (userId == UserHandle.USER_OWNER) { 4186 return resolveInfos; 4187 } 4188 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4189 ResolveInfo info = resolveInfos.get(i); 4190 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4191 resolveInfos.remove(i); 4192 } 4193 } 4194 return resolveInfos; 4195 } 4196 4197 private static boolean hasWebURI(Intent intent) { 4198 if (intent.getData() == null) { 4199 return false; 4200 } 4201 final String scheme = intent.getScheme(); 4202 if (TextUtils.isEmpty(scheme)) { 4203 return false; 4204 } 4205 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4206 } 4207 4208 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4209 int flags, List<ResolveInfo> candidates) { 4210 if (DEBUG_PREFERRED) { 4211 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4212 candidates.size()); 4213 } 4214 4215 final int userId = UserHandle.getCallingUserId(); 4216 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4217 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4218 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4219 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4220 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4221 4222 synchronized (mPackages) { 4223 final int count = candidates.size(); 4224 // First, try to use the domain prefered App. Partition the candidates into four lists: 4225 // one for the final results, one for the "do not use ever", one for "undefined status" 4226 // and finally one for "Browser App type". 4227 for (int n=0; n<count; n++) { 4228 ResolveInfo info = candidates.get(n); 4229 String packageName = info.activityInfo.packageName; 4230 PackageSetting ps = mSettings.mPackages.get(packageName); 4231 if (ps != null) { 4232 // Add to the special match all list (Browser use case) 4233 if (info.handleAllWebDataURI) { 4234 matchAllList.add(info); 4235 continue; 4236 } 4237 // Try to get the status from User settings first 4238 int status = getDomainVerificationStatusLPr(ps, userId); 4239 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4240 alwaysList.add(info); 4241 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4242 neverList.add(info); 4243 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4244 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4245 undefinedList.add(info); 4246 } 4247 } 4248 } 4249 // First try to add the "always" if there is any 4250 if (alwaysList.size() > 0) { 4251 result.addAll(alwaysList); 4252 } else { 4253 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4254 result.addAll(undefinedList); 4255 // Also add Browsers (all of them or only the default one) 4256 if ((flags & MATCH_ALL) != 0) { 4257 result.addAll(matchAllList); 4258 } else { 4259 // Try to add the Default Browser if we can 4260 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4261 UserHandle.myUserId()); 4262 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4263 boolean defaultBrowserFound = false; 4264 final int browserCount = matchAllList.size(); 4265 for (int n=0; n<browserCount; n++) { 4266 ResolveInfo browser = matchAllList.get(n); 4267 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4268 result.add(browser); 4269 defaultBrowserFound = true; 4270 break; 4271 } 4272 } 4273 if (!defaultBrowserFound) { 4274 result.addAll(matchAllList); 4275 } 4276 } else { 4277 result.addAll(matchAllList); 4278 } 4279 } 4280 4281 // If there is nothing selected, add all candidates and remove the ones that the User 4282 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4283 if (result.size() == 0) { 4284 result.addAll(candidates); 4285 result.removeAll(neverList); 4286 } 4287 } 4288 } 4289 if (DEBUG_PREFERRED) { 4290 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4291 result.size()); 4292 } 4293 return result; 4294 } 4295 4296 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4297 int status = ps.getDomainVerificationStatusForUser(userId); 4298 // if none available, get the master status 4299 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4300 if (ps.getIntentFilterVerificationInfo() != null) { 4301 status = ps.getIntentFilterVerificationInfo().getStatus(); 4302 } 4303 } 4304 return status; 4305 } 4306 4307 private ResolveInfo querySkipCurrentProfileIntents( 4308 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4309 int flags, int sourceUserId) { 4310 if (matchingFilters != null) { 4311 int size = matchingFilters.size(); 4312 for (int i = 0; i < size; i ++) { 4313 CrossProfileIntentFilter filter = matchingFilters.get(i); 4314 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4315 // Checking if there are activities in the target user that can handle the 4316 // intent. 4317 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4318 flags, sourceUserId); 4319 if (resolveInfo != null) { 4320 return resolveInfo; 4321 } 4322 } 4323 } 4324 } 4325 return null; 4326 } 4327 4328 // Return matching ResolveInfo if any for skip current profile intent filters. 4329 private ResolveInfo queryCrossProfileIntents( 4330 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4331 int flags, int sourceUserId) { 4332 if (matchingFilters != null) { 4333 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4334 // match the same intent. For performance reasons, it is better not to 4335 // run queryIntent twice for the same userId 4336 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4337 int size = matchingFilters.size(); 4338 for (int i = 0; i < size; i++) { 4339 CrossProfileIntentFilter filter = matchingFilters.get(i); 4340 int targetUserId = filter.getTargetUserId(); 4341 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4342 && !alreadyTriedUserIds.get(targetUserId)) { 4343 // Checking if there are activities in the target user that can handle the 4344 // intent. 4345 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4346 flags, sourceUserId); 4347 if (resolveInfo != null) return resolveInfo; 4348 alreadyTriedUserIds.put(targetUserId, true); 4349 } 4350 } 4351 } 4352 return null; 4353 } 4354 4355 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4356 String resolvedType, int flags, int sourceUserId) { 4357 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4358 resolvedType, flags, filter.getTargetUserId()); 4359 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4360 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4361 } 4362 return null; 4363 } 4364 4365 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4366 int sourceUserId, int targetUserId) { 4367 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4368 String className; 4369 if (targetUserId == UserHandle.USER_OWNER) { 4370 className = FORWARD_INTENT_TO_USER_OWNER; 4371 } else { 4372 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4373 } 4374 ComponentName forwardingActivityComponentName = new ComponentName( 4375 mAndroidApplication.packageName, className); 4376 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4377 sourceUserId); 4378 if (targetUserId == UserHandle.USER_OWNER) { 4379 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4380 forwardingResolveInfo.noResourceId = true; 4381 } 4382 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4383 forwardingResolveInfo.priority = 0; 4384 forwardingResolveInfo.preferredOrder = 0; 4385 forwardingResolveInfo.match = 0; 4386 forwardingResolveInfo.isDefault = true; 4387 forwardingResolveInfo.filter = filter; 4388 forwardingResolveInfo.targetUserId = targetUserId; 4389 return forwardingResolveInfo; 4390 } 4391 4392 @Override 4393 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4394 Intent[] specifics, String[] specificTypes, Intent intent, 4395 String resolvedType, int flags, int userId) { 4396 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4397 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4398 false, "query intent activity options"); 4399 final String resultsAction = intent.getAction(); 4400 4401 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4402 | PackageManager.GET_RESOLVED_FILTER, userId); 4403 4404 if (DEBUG_INTENT_MATCHING) { 4405 Log.v(TAG, "Query " + intent + ": " + results); 4406 } 4407 4408 int specificsPos = 0; 4409 int N; 4410 4411 // todo: note that the algorithm used here is O(N^2). This 4412 // isn't a problem in our current environment, but if we start running 4413 // into situations where we have more than 5 or 10 matches then this 4414 // should probably be changed to something smarter... 4415 4416 // First we go through and resolve each of the specific items 4417 // that were supplied, taking care of removing any corresponding 4418 // duplicate items in the generic resolve list. 4419 if (specifics != null) { 4420 for (int i=0; i<specifics.length; i++) { 4421 final Intent sintent = specifics[i]; 4422 if (sintent == null) { 4423 continue; 4424 } 4425 4426 if (DEBUG_INTENT_MATCHING) { 4427 Log.v(TAG, "Specific #" + i + ": " + sintent); 4428 } 4429 4430 String action = sintent.getAction(); 4431 if (resultsAction != null && resultsAction.equals(action)) { 4432 // If this action was explicitly requested, then don't 4433 // remove things that have it. 4434 action = null; 4435 } 4436 4437 ResolveInfo ri = null; 4438 ActivityInfo ai = null; 4439 4440 ComponentName comp = sintent.getComponent(); 4441 if (comp == null) { 4442 ri = resolveIntent( 4443 sintent, 4444 specificTypes != null ? specificTypes[i] : null, 4445 flags, userId); 4446 if (ri == null) { 4447 continue; 4448 } 4449 if (ri == mResolveInfo) { 4450 // ACK! Must do something better with this. 4451 } 4452 ai = ri.activityInfo; 4453 comp = new ComponentName(ai.applicationInfo.packageName, 4454 ai.name); 4455 } else { 4456 ai = getActivityInfo(comp, flags, userId); 4457 if (ai == null) { 4458 continue; 4459 } 4460 } 4461 4462 // Look for any generic query activities that are duplicates 4463 // of this specific one, and remove them from the results. 4464 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4465 N = results.size(); 4466 int j; 4467 for (j=specificsPos; j<N; j++) { 4468 ResolveInfo sri = results.get(j); 4469 if ((sri.activityInfo.name.equals(comp.getClassName()) 4470 && sri.activityInfo.applicationInfo.packageName.equals( 4471 comp.getPackageName())) 4472 || (action != null && sri.filter.matchAction(action))) { 4473 results.remove(j); 4474 if (DEBUG_INTENT_MATCHING) Log.v( 4475 TAG, "Removing duplicate item from " + j 4476 + " due to specific " + specificsPos); 4477 if (ri == null) { 4478 ri = sri; 4479 } 4480 j--; 4481 N--; 4482 } 4483 } 4484 4485 // Add this specific item to its proper place. 4486 if (ri == null) { 4487 ri = new ResolveInfo(); 4488 ri.activityInfo = ai; 4489 } 4490 results.add(specificsPos, ri); 4491 ri.specificIndex = i; 4492 specificsPos++; 4493 } 4494 } 4495 4496 // Now we go through the remaining generic results and remove any 4497 // duplicate actions that are found here. 4498 N = results.size(); 4499 for (int i=specificsPos; i<N-1; i++) { 4500 final ResolveInfo rii = results.get(i); 4501 if (rii.filter == null) { 4502 continue; 4503 } 4504 4505 // Iterate over all of the actions of this result's intent 4506 // filter... typically this should be just one. 4507 final Iterator<String> it = rii.filter.actionsIterator(); 4508 if (it == null) { 4509 continue; 4510 } 4511 while (it.hasNext()) { 4512 final String action = it.next(); 4513 if (resultsAction != null && resultsAction.equals(action)) { 4514 // If this action was explicitly requested, then don't 4515 // remove things that have it. 4516 continue; 4517 } 4518 for (int j=i+1; j<N; j++) { 4519 final ResolveInfo rij = results.get(j); 4520 if (rij.filter != null && rij.filter.hasAction(action)) { 4521 results.remove(j); 4522 if (DEBUG_INTENT_MATCHING) Log.v( 4523 TAG, "Removing duplicate item from " + j 4524 + " due to action " + action + " at " + i); 4525 j--; 4526 N--; 4527 } 4528 } 4529 } 4530 4531 // If the caller didn't request filter information, drop it now 4532 // so we don't have to marshall/unmarshall it. 4533 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4534 rii.filter = null; 4535 } 4536 } 4537 4538 // Filter out the caller activity if so requested. 4539 if (caller != null) { 4540 N = results.size(); 4541 for (int i=0; i<N; i++) { 4542 ActivityInfo ainfo = results.get(i).activityInfo; 4543 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4544 && caller.getClassName().equals(ainfo.name)) { 4545 results.remove(i); 4546 break; 4547 } 4548 } 4549 } 4550 4551 // If the caller didn't request filter information, 4552 // drop them now so we don't have to 4553 // marshall/unmarshall it. 4554 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4555 N = results.size(); 4556 for (int i=0; i<N; i++) { 4557 results.get(i).filter = null; 4558 } 4559 } 4560 4561 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4562 return results; 4563 } 4564 4565 @Override 4566 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4567 int userId) { 4568 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4569 ComponentName comp = intent.getComponent(); 4570 if (comp == null) { 4571 if (intent.getSelector() != null) { 4572 intent = intent.getSelector(); 4573 comp = intent.getComponent(); 4574 } 4575 } 4576 if (comp != null) { 4577 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4578 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4579 if (ai != null) { 4580 ResolveInfo ri = new ResolveInfo(); 4581 ri.activityInfo = ai; 4582 list.add(ri); 4583 } 4584 return list; 4585 } 4586 4587 // reader 4588 synchronized (mPackages) { 4589 String pkgName = intent.getPackage(); 4590 if (pkgName == null) { 4591 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4592 } 4593 final PackageParser.Package pkg = mPackages.get(pkgName); 4594 if (pkg != null) { 4595 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4596 userId); 4597 } 4598 return null; 4599 } 4600 } 4601 4602 @Override 4603 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4604 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4605 if (!sUserManager.exists(userId)) return null; 4606 if (query != null) { 4607 if (query.size() >= 1) { 4608 // If there is more than one service with the same priority, 4609 // just arbitrarily pick the first one. 4610 return query.get(0); 4611 } 4612 } 4613 return null; 4614 } 4615 4616 @Override 4617 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4618 int userId) { 4619 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4620 ComponentName comp = intent.getComponent(); 4621 if (comp == null) { 4622 if (intent.getSelector() != null) { 4623 intent = intent.getSelector(); 4624 comp = intent.getComponent(); 4625 } 4626 } 4627 if (comp != null) { 4628 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4629 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4630 if (si != null) { 4631 final ResolveInfo ri = new ResolveInfo(); 4632 ri.serviceInfo = si; 4633 list.add(ri); 4634 } 4635 return list; 4636 } 4637 4638 // reader 4639 synchronized (mPackages) { 4640 String pkgName = intent.getPackage(); 4641 if (pkgName == null) { 4642 return mServices.queryIntent(intent, resolvedType, flags, userId); 4643 } 4644 final PackageParser.Package pkg = mPackages.get(pkgName); 4645 if (pkg != null) { 4646 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4647 userId); 4648 } 4649 return null; 4650 } 4651 } 4652 4653 @Override 4654 public List<ResolveInfo> queryIntentContentProviders( 4655 Intent intent, String resolvedType, int flags, int userId) { 4656 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4657 ComponentName comp = intent.getComponent(); 4658 if (comp == null) { 4659 if (intent.getSelector() != null) { 4660 intent = intent.getSelector(); 4661 comp = intent.getComponent(); 4662 } 4663 } 4664 if (comp != null) { 4665 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4666 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4667 if (pi != null) { 4668 final ResolveInfo ri = new ResolveInfo(); 4669 ri.providerInfo = pi; 4670 list.add(ri); 4671 } 4672 return list; 4673 } 4674 4675 // reader 4676 synchronized (mPackages) { 4677 String pkgName = intent.getPackage(); 4678 if (pkgName == null) { 4679 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4680 } 4681 final PackageParser.Package pkg = mPackages.get(pkgName); 4682 if (pkg != null) { 4683 return mProviders.queryIntentForPackage( 4684 intent, resolvedType, flags, pkg.providers, userId); 4685 } 4686 return null; 4687 } 4688 } 4689 4690 @Override 4691 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4692 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4693 4694 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4695 4696 // writer 4697 synchronized (mPackages) { 4698 ArrayList<PackageInfo> list; 4699 if (listUninstalled) { 4700 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4701 for (PackageSetting ps : mSettings.mPackages.values()) { 4702 PackageInfo pi; 4703 if (ps.pkg != null) { 4704 pi = generatePackageInfo(ps.pkg, flags, userId); 4705 } else { 4706 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4707 } 4708 if (pi != null) { 4709 list.add(pi); 4710 } 4711 } 4712 } else { 4713 list = new ArrayList<PackageInfo>(mPackages.size()); 4714 for (PackageParser.Package p : mPackages.values()) { 4715 PackageInfo pi = generatePackageInfo(p, flags, userId); 4716 if (pi != null) { 4717 list.add(pi); 4718 } 4719 } 4720 } 4721 4722 return new ParceledListSlice<PackageInfo>(list); 4723 } 4724 } 4725 4726 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4727 String[] permissions, boolean[] tmp, int flags, int userId) { 4728 int numMatch = 0; 4729 final PermissionsState permissionsState = ps.getPermissionsState(); 4730 for (int i=0; i<permissions.length; i++) { 4731 final String permission = permissions[i]; 4732 if (permissionsState.hasPermission(permission, userId)) { 4733 tmp[i] = true; 4734 numMatch++; 4735 } else { 4736 tmp[i] = false; 4737 } 4738 } 4739 if (numMatch == 0) { 4740 return; 4741 } 4742 PackageInfo pi; 4743 if (ps.pkg != null) { 4744 pi = generatePackageInfo(ps.pkg, flags, userId); 4745 } else { 4746 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4747 } 4748 // The above might return null in cases of uninstalled apps or install-state 4749 // skew across users/profiles. 4750 if (pi != null) { 4751 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4752 if (numMatch == permissions.length) { 4753 pi.requestedPermissions = permissions; 4754 } else { 4755 pi.requestedPermissions = new String[numMatch]; 4756 numMatch = 0; 4757 for (int i=0; i<permissions.length; i++) { 4758 if (tmp[i]) { 4759 pi.requestedPermissions[numMatch] = permissions[i]; 4760 numMatch++; 4761 } 4762 } 4763 } 4764 } 4765 list.add(pi); 4766 } 4767 } 4768 4769 @Override 4770 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4771 String[] permissions, int flags, int userId) { 4772 if (!sUserManager.exists(userId)) return null; 4773 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4774 4775 // writer 4776 synchronized (mPackages) { 4777 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4778 boolean[] tmpBools = new boolean[permissions.length]; 4779 if (listUninstalled) { 4780 for (PackageSetting ps : mSettings.mPackages.values()) { 4781 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4782 } 4783 } else { 4784 for (PackageParser.Package pkg : mPackages.values()) { 4785 PackageSetting ps = (PackageSetting)pkg.mExtras; 4786 if (ps != null) { 4787 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4788 userId); 4789 } 4790 } 4791 } 4792 4793 return new ParceledListSlice<PackageInfo>(list); 4794 } 4795 } 4796 4797 @Override 4798 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4799 if (!sUserManager.exists(userId)) return null; 4800 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4801 4802 // writer 4803 synchronized (mPackages) { 4804 ArrayList<ApplicationInfo> list; 4805 if (listUninstalled) { 4806 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4807 for (PackageSetting ps : mSettings.mPackages.values()) { 4808 ApplicationInfo ai; 4809 if (ps.pkg != null) { 4810 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4811 ps.readUserState(userId), userId); 4812 } else { 4813 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4814 } 4815 if (ai != null) { 4816 list.add(ai); 4817 } 4818 } 4819 } else { 4820 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4821 for (PackageParser.Package p : mPackages.values()) { 4822 if (p.mExtras != null) { 4823 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4824 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4825 if (ai != null) { 4826 list.add(ai); 4827 } 4828 } 4829 } 4830 } 4831 4832 return new ParceledListSlice<ApplicationInfo>(list); 4833 } 4834 } 4835 4836 public List<ApplicationInfo> getPersistentApplications(int flags) { 4837 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4838 4839 // reader 4840 synchronized (mPackages) { 4841 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4842 final int userId = UserHandle.getCallingUserId(); 4843 while (i.hasNext()) { 4844 final PackageParser.Package p = i.next(); 4845 if (p.applicationInfo != null 4846 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4847 && (!mSafeMode || isSystemApp(p))) { 4848 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4849 if (ps != null) { 4850 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4851 ps.readUserState(userId), userId); 4852 if (ai != null) { 4853 finalList.add(ai); 4854 } 4855 } 4856 } 4857 } 4858 } 4859 4860 return finalList; 4861 } 4862 4863 @Override 4864 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4865 if (!sUserManager.exists(userId)) return null; 4866 // reader 4867 synchronized (mPackages) { 4868 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4869 PackageSetting ps = provider != null 4870 ? mSettings.mPackages.get(provider.owner.packageName) 4871 : null; 4872 return ps != null 4873 && mSettings.isEnabledLPr(provider.info, flags, userId) 4874 && (!mSafeMode || (provider.info.applicationInfo.flags 4875 &ApplicationInfo.FLAG_SYSTEM) != 0) 4876 ? PackageParser.generateProviderInfo(provider, flags, 4877 ps.readUserState(userId), userId) 4878 : null; 4879 } 4880 } 4881 4882 /** 4883 * @deprecated 4884 */ 4885 @Deprecated 4886 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4887 // reader 4888 synchronized (mPackages) { 4889 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4890 .entrySet().iterator(); 4891 final int userId = UserHandle.getCallingUserId(); 4892 while (i.hasNext()) { 4893 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4894 PackageParser.Provider p = entry.getValue(); 4895 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4896 4897 if (ps != null && p.syncable 4898 && (!mSafeMode || (p.info.applicationInfo.flags 4899 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4900 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4901 ps.readUserState(userId), userId); 4902 if (info != null) { 4903 outNames.add(entry.getKey()); 4904 outInfo.add(info); 4905 } 4906 } 4907 } 4908 } 4909 } 4910 4911 @Override 4912 public List<ProviderInfo> queryContentProviders(String processName, 4913 int uid, int flags) { 4914 ArrayList<ProviderInfo> finalList = null; 4915 // reader 4916 synchronized (mPackages) { 4917 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4918 final int userId = processName != null ? 4919 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4920 while (i.hasNext()) { 4921 final PackageParser.Provider p = i.next(); 4922 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4923 if (ps != null && p.info.authority != null 4924 && (processName == null 4925 || (p.info.processName.equals(processName) 4926 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4927 && mSettings.isEnabledLPr(p.info, flags, userId) 4928 && (!mSafeMode 4929 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4930 if (finalList == null) { 4931 finalList = new ArrayList<ProviderInfo>(3); 4932 } 4933 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4934 ps.readUserState(userId), userId); 4935 if (info != null) { 4936 finalList.add(info); 4937 } 4938 } 4939 } 4940 } 4941 4942 if (finalList != null) { 4943 Collections.sort(finalList, mProviderInitOrderSorter); 4944 } 4945 4946 return finalList; 4947 } 4948 4949 @Override 4950 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4951 int flags) { 4952 // reader 4953 synchronized (mPackages) { 4954 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4955 return PackageParser.generateInstrumentationInfo(i, flags); 4956 } 4957 } 4958 4959 @Override 4960 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4961 int flags) { 4962 ArrayList<InstrumentationInfo> finalList = 4963 new ArrayList<InstrumentationInfo>(); 4964 4965 // reader 4966 synchronized (mPackages) { 4967 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4968 while (i.hasNext()) { 4969 final PackageParser.Instrumentation p = i.next(); 4970 if (targetPackage == null 4971 || targetPackage.equals(p.info.targetPackage)) { 4972 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4973 flags); 4974 if (ii != null) { 4975 finalList.add(ii); 4976 } 4977 } 4978 } 4979 } 4980 4981 return finalList; 4982 } 4983 4984 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4985 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4986 if (overlays == null) { 4987 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4988 return; 4989 } 4990 for (PackageParser.Package opkg : overlays.values()) { 4991 // Not much to do if idmap fails: we already logged the error 4992 // and we certainly don't want to abort installation of pkg simply 4993 // because an overlay didn't fit properly. For these reasons, 4994 // ignore the return value of createIdmapForPackagePairLI. 4995 createIdmapForPackagePairLI(pkg, opkg); 4996 } 4997 } 4998 4999 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 5000 PackageParser.Package opkg) { 5001 if (!opkg.mTrustedOverlay) { 5002 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 5003 opkg.baseCodePath + ": overlay not trusted"); 5004 return false; 5005 } 5006 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5007 if (overlaySet == null) { 5008 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5009 opkg.baseCodePath + " but target package has no known overlays"); 5010 return false; 5011 } 5012 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5013 // TODO: generate idmap for split APKs 5014 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5015 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5016 + opkg.baseCodePath); 5017 return false; 5018 } 5019 PackageParser.Package[] overlayArray = 5020 overlaySet.values().toArray(new PackageParser.Package[0]); 5021 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5022 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5023 return p1.mOverlayPriority - p2.mOverlayPriority; 5024 } 5025 }; 5026 Arrays.sort(overlayArray, cmp); 5027 5028 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5029 int i = 0; 5030 for (PackageParser.Package p : overlayArray) { 5031 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5032 } 5033 return true; 5034 } 5035 5036 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5037 final File[] files = dir.listFiles(); 5038 if (ArrayUtils.isEmpty(files)) { 5039 Log.d(TAG, "No files in app dir " + dir); 5040 return; 5041 } 5042 5043 if (DEBUG_PACKAGE_SCANNING) { 5044 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5045 + " flags=0x" + Integer.toHexString(parseFlags)); 5046 } 5047 5048 for (File file : files) { 5049 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5050 && !PackageInstallerService.isStageName(file.getName()); 5051 if (!isPackage) { 5052 // Ignore entries which are not packages 5053 continue; 5054 } 5055 try { 5056 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5057 scanFlags, currentTime, null); 5058 } catch (PackageManagerException e) { 5059 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5060 5061 // Delete invalid userdata apps 5062 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5063 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5064 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5065 if (file.isDirectory()) { 5066 mInstaller.rmPackageDir(file.getAbsolutePath()); 5067 } else { 5068 file.delete(); 5069 } 5070 } 5071 } 5072 } 5073 } 5074 5075 private static File getSettingsProblemFile() { 5076 File dataDir = Environment.getDataDirectory(); 5077 File systemDir = new File(dataDir, "system"); 5078 File fname = new File(systemDir, "uiderrors.txt"); 5079 return fname; 5080 } 5081 5082 static void reportSettingsProblem(int priority, String msg) { 5083 logCriticalInfo(priority, msg); 5084 } 5085 5086 static void logCriticalInfo(int priority, String msg) { 5087 Slog.println(priority, TAG, msg); 5088 EventLogTags.writePmCriticalInfo(msg); 5089 try { 5090 File fname = getSettingsProblemFile(); 5091 FileOutputStream out = new FileOutputStream(fname, true); 5092 PrintWriter pw = new FastPrintWriter(out); 5093 SimpleDateFormat formatter = new SimpleDateFormat(); 5094 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5095 pw.println(dateString + ": " + msg); 5096 pw.close(); 5097 FileUtils.setPermissions( 5098 fname.toString(), 5099 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5100 -1, -1); 5101 } catch (java.io.IOException e) { 5102 } 5103 } 5104 5105 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5106 PackageParser.Package pkg, File srcFile, int parseFlags) 5107 throws PackageManagerException { 5108 if (ps != null 5109 && ps.codePath.equals(srcFile) 5110 && ps.timeStamp == srcFile.lastModified() 5111 && !isCompatSignatureUpdateNeeded(pkg) 5112 && !isRecoverSignatureUpdateNeeded(pkg)) { 5113 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5114 if (ps.signatures.mSignatures != null 5115 && ps.signatures.mSignatures.length != 0 5116 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5117 // Optimization: reuse the existing cached certificates 5118 // if the package appears to be unchanged. 5119 pkg.mSignatures = ps.signatures.mSignatures; 5120 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5121 synchronized (mPackages) { 5122 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5123 } 5124 return; 5125 } 5126 5127 Slog.w(TAG, "PackageSetting for " + ps.name 5128 + " is missing signatures. Collecting certs again to recover them."); 5129 } else { 5130 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5131 } 5132 5133 try { 5134 pp.collectCertificates(pkg, parseFlags); 5135 pp.collectManifestDigest(pkg); 5136 } catch (PackageParserException e) { 5137 throw PackageManagerException.from(e); 5138 } 5139 } 5140 5141 /* 5142 * Scan a package and return the newly parsed package. 5143 * Returns null in case of errors and the error code is stored in mLastScanError 5144 */ 5145 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5146 long currentTime, UserHandle user) throws PackageManagerException { 5147 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5148 parseFlags |= mDefParseFlags; 5149 PackageParser pp = new PackageParser(); 5150 pp.setSeparateProcesses(mSeparateProcesses); 5151 pp.setOnlyCoreApps(mOnlyCore); 5152 pp.setDisplayMetrics(mMetrics); 5153 5154 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5155 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5156 } 5157 5158 final PackageParser.Package pkg; 5159 try { 5160 pkg = pp.parsePackage(scanFile, parseFlags); 5161 } catch (PackageParserException e) { 5162 throw PackageManagerException.from(e); 5163 } 5164 5165 PackageSetting ps = null; 5166 PackageSetting updatedPkg; 5167 // reader 5168 synchronized (mPackages) { 5169 // Look to see if we already know about this package. 5170 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5171 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5172 // This package has been renamed to its original name. Let's 5173 // use that. 5174 ps = mSettings.peekPackageLPr(oldName); 5175 } 5176 // If there was no original package, see one for the real package name. 5177 if (ps == null) { 5178 ps = mSettings.peekPackageLPr(pkg.packageName); 5179 } 5180 // Check to see if this package could be hiding/updating a system 5181 // package. Must look for it either under the original or real 5182 // package name depending on our state. 5183 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5184 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5185 } 5186 boolean updatedPkgBetter = false; 5187 // First check if this is a system package that may involve an update 5188 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5189 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5190 // it needs to drop FLAG_PRIVILEGED. 5191 if (locationIsPrivileged(scanFile)) { 5192 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5193 } else { 5194 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5195 } 5196 5197 if (ps != null && !ps.codePath.equals(scanFile)) { 5198 // The path has changed from what was last scanned... check the 5199 // version of the new path against what we have stored to determine 5200 // what to do. 5201 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5202 if (pkg.mVersionCode <= ps.versionCode) { 5203 // The system package has been updated and the code path does not match 5204 // Ignore entry. Skip it. 5205 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5206 + " ignored: updated version " + ps.versionCode 5207 + " better than this " + pkg.mVersionCode); 5208 if (!updatedPkg.codePath.equals(scanFile)) { 5209 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5210 + ps.name + " changing from " + updatedPkg.codePathString 5211 + " to " + scanFile); 5212 updatedPkg.codePath = scanFile; 5213 updatedPkg.codePathString = scanFile.toString(); 5214 updatedPkg.resourcePath = scanFile; 5215 updatedPkg.resourcePathString = scanFile.toString(); 5216 } 5217 updatedPkg.pkg = pkg; 5218 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5219 } else { 5220 // The current app on the system partition is better than 5221 // what we have updated to on the data partition; switch 5222 // back to the system partition version. 5223 // At this point, its safely assumed that package installation for 5224 // apps in system partition will go through. If not there won't be a working 5225 // version of the app 5226 // writer 5227 synchronized (mPackages) { 5228 // Just remove the loaded entries from package lists. 5229 mPackages.remove(ps.name); 5230 } 5231 5232 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5233 + " reverting from " + ps.codePathString 5234 + ": new version " + pkg.mVersionCode 5235 + " better than installed " + ps.versionCode); 5236 5237 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5238 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5239 synchronized (mInstallLock) { 5240 args.cleanUpResourcesLI(); 5241 } 5242 synchronized (mPackages) { 5243 mSettings.enableSystemPackageLPw(ps.name); 5244 } 5245 updatedPkgBetter = true; 5246 } 5247 } 5248 } 5249 5250 if (updatedPkg != null) { 5251 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5252 // initially 5253 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5254 5255 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5256 // flag set initially 5257 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5258 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5259 } 5260 } 5261 5262 // Verify certificates against what was last scanned 5263 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5264 5265 /* 5266 * A new system app appeared, but we already had a non-system one of the 5267 * same name installed earlier. 5268 */ 5269 boolean shouldHideSystemApp = false; 5270 if (updatedPkg == null && ps != null 5271 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5272 /* 5273 * Check to make sure the signatures match first. If they don't, 5274 * wipe the installed application and its data. 5275 */ 5276 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5277 != PackageManager.SIGNATURE_MATCH) { 5278 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5279 + " signatures don't match existing userdata copy; removing"); 5280 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5281 ps = null; 5282 } else { 5283 /* 5284 * If the newly-added system app is an older version than the 5285 * already installed version, hide it. It will be scanned later 5286 * and re-added like an update. 5287 */ 5288 if (pkg.mVersionCode <= ps.versionCode) { 5289 shouldHideSystemApp = true; 5290 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5291 + " but new version " + pkg.mVersionCode + " better than installed " 5292 + ps.versionCode + "; hiding system"); 5293 } else { 5294 /* 5295 * The newly found system app is a newer version that the 5296 * one previously installed. Simply remove the 5297 * already-installed application and replace it with our own 5298 * while keeping the application data. 5299 */ 5300 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5301 + " reverting from " + ps.codePathString + ": new version " 5302 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5303 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5304 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5305 synchronized (mInstallLock) { 5306 args.cleanUpResourcesLI(); 5307 } 5308 } 5309 } 5310 } 5311 5312 // The apk is forward locked (not public) if its code and resources 5313 // are kept in different files. (except for app in either system or 5314 // vendor path). 5315 // TODO grab this value from PackageSettings 5316 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5317 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5318 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5319 } 5320 } 5321 5322 // TODO: extend to support forward-locked splits 5323 String resourcePath = null; 5324 String baseResourcePath = null; 5325 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5326 if (ps != null && ps.resourcePathString != null) { 5327 resourcePath = ps.resourcePathString; 5328 baseResourcePath = ps.resourcePathString; 5329 } else { 5330 // Should not happen at all. Just log an error. 5331 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5332 } 5333 } else { 5334 resourcePath = pkg.codePath; 5335 baseResourcePath = pkg.baseCodePath; 5336 } 5337 5338 // Set application objects path explicitly. 5339 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5340 pkg.applicationInfo.setCodePath(pkg.codePath); 5341 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5342 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5343 pkg.applicationInfo.setResourcePath(resourcePath); 5344 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5345 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5346 5347 // Note that we invoke the following method only if we are about to unpack an application 5348 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5349 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5350 5351 /* 5352 * If the system app should be overridden by a previously installed 5353 * data, hide the system app now and let the /data/app scan pick it up 5354 * again. 5355 */ 5356 if (shouldHideSystemApp) { 5357 synchronized (mPackages) { 5358 /* 5359 * We have to grant systems permissions before we hide, because 5360 * grantPermissions will assume the package update is trying to 5361 * expand its permissions. 5362 */ 5363 grantPermissionsLPw(pkg, true, pkg.packageName); 5364 mSettings.disableSystemPackageLPw(pkg.packageName); 5365 } 5366 } 5367 5368 return scannedPkg; 5369 } 5370 5371 private static String fixProcessName(String defProcessName, 5372 String processName, int uid) { 5373 if (processName == null) { 5374 return defProcessName; 5375 } 5376 return processName; 5377 } 5378 5379 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5380 throws PackageManagerException { 5381 if (pkgSetting.signatures.mSignatures != null) { 5382 // Already existing package. Make sure signatures match 5383 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5384 == PackageManager.SIGNATURE_MATCH; 5385 if (!match) { 5386 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5387 == PackageManager.SIGNATURE_MATCH; 5388 } 5389 if (!match) { 5390 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5391 == PackageManager.SIGNATURE_MATCH; 5392 } 5393 if (!match) { 5394 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5395 + pkg.packageName + " signatures do not match the " 5396 + "previously installed version; ignoring!"); 5397 } 5398 } 5399 5400 // Check for shared user signatures 5401 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5402 // Already existing package. Make sure signatures match 5403 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5404 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5405 if (!match) { 5406 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5407 == PackageManager.SIGNATURE_MATCH; 5408 } 5409 if (!match) { 5410 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5411 == PackageManager.SIGNATURE_MATCH; 5412 } 5413 if (!match) { 5414 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5415 "Package " + pkg.packageName 5416 + " has no signatures that match those in shared user " 5417 + pkgSetting.sharedUser.name + "; ignoring!"); 5418 } 5419 } 5420 } 5421 5422 /** 5423 * Enforces that only the system UID or root's UID can call a method exposed 5424 * via Binder. 5425 * 5426 * @param message used as message if SecurityException is thrown 5427 * @throws SecurityException if the caller is not system or root 5428 */ 5429 private static final void enforceSystemOrRoot(String message) { 5430 final int uid = Binder.getCallingUid(); 5431 if (uid != Process.SYSTEM_UID && uid != 0) { 5432 throw new SecurityException(message); 5433 } 5434 } 5435 5436 @Override 5437 public void performBootDexOpt() { 5438 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5439 5440 // Before everything else, see whether we need to fstrim. 5441 try { 5442 IMountService ms = PackageHelper.getMountService(); 5443 if (ms != null) { 5444 final boolean isUpgrade = isUpgrade(); 5445 boolean doTrim = isUpgrade; 5446 if (doTrim) { 5447 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5448 } else { 5449 final long interval = android.provider.Settings.Global.getLong( 5450 mContext.getContentResolver(), 5451 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5452 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5453 if (interval > 0) { 5454 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5455 if (timeSinceLast > interval) { 5456 doTrim = true; 5457 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5458 + "; running immediately"); 5459 } 5460 } 5461 } 5462 if (doTrim) { 5463 if (!isFirstBoot()) { 5464 try { 5465 ActivityManagerNative.getDefault().showBootMessage( 5466 mContext.getResources().getString( 5467 R.string.android_upgrading_fstrim), true); 5468 } catch (RemoteException e) { 5469 } 5470 } 5471 ms.runMaintenance(); 5472 } 5473 } else { 5474 Slog.e(TAG, "Mount service unavailable!"); 5475 } 5476 } catch (RemoteException e) { 5477 // Can't happen; MountService is local 5478 } 5479 5480 final ArraySet<PackageParser.Package> pkgs; 5481 synchronized (mPackages) { 5482 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5483 } 5484 5485 if (pkgs != null) { 5486 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5487 // in case the device runs out of space. 5488 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5489 // Give priority to core apps. 5490 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5491 PackageParser.Package pkg = it.next(); 5492 if (pkg.coreApp) { 5493 if (DEBUG_DEXOPT) { 5494 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5495 } 5496 sortedPkgs.add(pkg); 5497 it.remove(); 5498 } 5499 } 5500 // Give priority to system apps that listen for pre boot complete. 5501 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5502 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5503 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5504 PackageParser.Package pkg = it.next(); 5505 if (pkgNames.contains(pkg.packageName)) { 5506 if (DEBUG_DEXOPT) { 5507 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5508 } 5509 sortedPkgs.add(pkg); 5510 it.remove(); 5511 } 5512 } 5513 // Give priority to system apps. 5514 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5515 PackageParser.Package pkg = it.next(); 5516 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5517 if (DEBUG_DEXOPT) { 5518 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5519 } 5520 sortedPkgs.add(pkg); 5521 it.remove(); 5522 } 5523 } 5524 // Give priority to updated system apps. 5525 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5526 PackageParser.Package pkg = it.next(); 5527 if (pkg.isUpdatedSystemApp()) { 5528 if (DEBUG_DEXOPT) { 5529 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5530 } 5531 sortedPkgs.add(pkg); 5532 it.remove(); 5533 } 5534 } 5535 // Give priority to apps that listen for boot complete. 5536 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5537 pkgNames = getPackageNamesForIntent(intent); 5538 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5539 PackageParser.Package pkg = it.next(); 5540 if (pkgNames.contains(pkg.packageName)) { 5541 if (DEBUG_DEXOPT) { 5542 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5543 } 5544 sortedPkgs.add(pkg); 5545 it.remove(); 5546 } 5547 } 5548 // Filter out packages that aren't recently used. 5549 filterRecentlyUsedApps(pkgs); 5550 // Add all remaining apps. 5551 for (PackageParser.Package pkg : pkgs) { 5552 if (DEBUG_DEXOPT) { 5553 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5554 } 5555 sortedPkgs.add(pkg); 5556 } 5557 5558 // If we want to be lazy, filter everything that wasn't recently used. 5559 if (mLazyDexOpt) { 5560 filterRecentlyUsedApps(sortedPkgs); 5561 } 5562 5563 int i = 0; 5564 int total = sortedPkgs.size(); 5565 File dataDir = Environment.getDataDirectory(); 5566 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5567 if (lowThreshold == 0) { 5568 throw new IllegalStateException("Invalid low memory threshold"); 5569 } 5570 for (PackageParser.Package pkg : sortedPkgs) { 5571 long usableSpace = dataDir.getUsableSpace(); 5572 if (usableSpace < lowThreshold) { 5573 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5574 break; 5575 } 5576 performBootDexOpt(pkg, ++i, total); 5577 } 5578 } 5579 } 5580 5581 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5582 // Filter out packages that aren't recently used. 5583 // 5584 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5585 // should do a full dexopt. 5586 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5587 int total = pkgs.size(); 5588 int skipped = 0; 5589 long now = System.currentTimeMillis(); 5590 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5591 PackageParser.Package pkg = i.next(); 5592 long then = pkg.mLastPackageUsageTimeInMills; 5593 if (then + mDexOptLRUThresholdInMills < now) { 5594 if (DEBUG_DEXOPT) { 5595 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5596 ((then == 0) ? "never" : new Date(then))); 5597 } 5598 i.remove(); 5599 skipped++; 5600 } 5601 } 5602 if (DEBUG_DEXOPT) { 5603 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5604 } 5605 } 5606 } 5607 5608 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5609 List<ResolveInfo> ris = null; 5610 try { 5611 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5612 intent, null, 0, UserHandle.USER_OWNER); 5613 } catch (RemoteException e) { 5614 } 5615 ArraySet<String> pkgNames = new ArraySet<String>(); 5616 if (ris != null) { 5617 for (ResolveInfo ri : ris) { 5618 pkgNames.add(ri.activityInfo.packageName); 5619 } 5620 } 5621 return pkgNames; 5622 } 5623 5624 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5625 if (DEBUG_DEXOPT) { 5626 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5627 } 5628 if (!isFirstBoot()) { 5629 try { 5630 ActivityManagerNative.getDefault().showBootMessage( 5631 mContext.getResources().getString(R.string.android_upgrading_apk, 5632 curr, total), true); 5633 } catch (RemoteException e) { 5634 } 5635 } 5636 PackageParser.Package p = pkg; 5637 synchronized (mInstallLock) { 5638 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5639 false /* force dex */, false /* defer */, true /* include dependencies */); 5640 } 5641 } 5642 5643 @Override 5644 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5645 return performDexOpt(packageName, instructionSet, false); 5646 } 5647 5648 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5649 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5650 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5651 if (!dexopt && !updateUsage) { 5652 // We aren't going to dexopt or update usage, so bail early. 5653 return false; 5654 } 5655 PackageParser.Package p; 5656 final String targetInstructionSet; 5657 synchronized (mPackages) { 5658 p = mPackages.get(packageName); 5659 if (p == null) { 5660 return false; 5661 } 5662 if (updateUsage) { 5663 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5664 } 5665 mPackageUsage.write(false); 5666 if (!dexopt) { 5667 // We aren't going to dexopt, so bail early. 5668 return false; 5669 } 5670 5671 targetInstructionSet = instructionSet != null ? instructionSet : 5672 getPrimaryInstructionSet(p.applicationInfo); 5673 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5674 return false; 5675 } 5676 } 5677 5678 synchronized (mInstallLock) { 5679 final String[] instructionSets = new String[] { targetInstructionSet }; 5680 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5681 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5682 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5683 } 5684 } 5685 5686 public ArraySet<String> getPackagesThatNeedDexOpt() { 5687 ArraySet<String> pkgs = null; 5688 synchronized (mPackages) { 5689 for (PackageParser.Package p : mPackages.values()) { 5690 if (DEBUG_DEXOPT) { 5691 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5692 } 5693 if (!p.mDexOptPerformed.isEmpty()) { 5694 continue; 5695 } 5696 if (pkgs == null) { 5697 pkgs = new ArraySet<String>(); 5698 } 5699 pkgs.add(p.packageName); 5700 } 5701 } 5702 return pkgs; 5703 } 5704 5705 public void shutdown() { 5706 mPackageUsage.write(true); 5707 } 5708 5709 @Override 5710 public void forceDexOpt(String packageName) { 5711 enforceSystemOrRoot("forceDexOpt"); 5712 5713 PackageParser.Package pkg; 5714 synchronized (mPackages) { 5715 pkg = mPackages.get(packageName); 5716 if (pkg == null) { 5717 throw new IllegalArgumentException("Missing package: " + packageName); 5718 } 5719 } 5720 5721 synchronized (mInstallLock) { 5722 final String[] instructionSets = new String[] { 5723 getPrimaryInstructionSet(pkg.applicationInfo) }; 5724 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5725 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5726 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5727 throw new IllegalStateException("Failed to dexopt: " + res); 5728 } 5729 } 5730 } 5731 5732 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5733 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5734 Slog.w(TAG, "Unable to update from " + oldPkg.name 5735 + " to " + newPkg.packageName 5736 + ": old package not in system partition"); 5737 return false; 5738 } else if (mPackages.get(oldPkg.name) != null) { 5739 Slog.w(TAG, "Unable to update from " + oldPkg.name 5740 + " to " + newPkg.packageName 5741 + ": old package still exists"); 5742 return false; 5743 } 5744 return true; 5745 } 5746 5747 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5748 int[] users = sUserManager.getUserIds(); 5749 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5750 if (res < 0) { 5751 return res; 5752 } 5753 for (int user : users) { 5754 if (user != 0) { 5755 res = mInstaller.createUserData(volumeUuid, packageName, 5756 UserHandle.getUid(user, uid), user, seinfo); 5757 if (res < 0) { 5758 return res; 5759 } 5760 } 5761 } 5762 return res; 5763 } 5764 5765 private int removeDataDirsLI(String volumeUuid, String packageName) { 5766 int[] users = sUserManager.getUserIds(); 5767 int res = 0; 5768 for (int user : users) { 5769 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5770 if (resInner < 0) { 5771 res = resInner; 5772 } 5773 } 5774 5775 return res; 5776 } 5777 5778 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5779 int[] users = sUserManager.getUserIds(); 5780 int res = 0; 5781 for (int user : users) { 5782 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5783 if (resInner < 0) { 5784 res = resInner; 5785 } 5786 } 5787 return res; 5788 } 5789 5790 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5791 PackageParser.Package changingLib) { 5792 if (file.path != null) { 5793 usesLibraryFiles.add(file.path); 5794 return; 5795 } 5796 PackageParser.Package p = mPackages.get(file.apk); 5797 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5798 // If we are doing this while in the middle of updating a library apk, 5799 // then we need to make sure to use that new apk for determining the 5800 // dependencies here. (We haven't yet finished committing the new apk 5801 // to the package manager state.) 5802 if (p == null || p.packageName.equals(changingLib.packageName)) { 5803 p = changingLib; 5804 } 5805 } 5806 if (p != null) { 5807 usesLibraryFiles.addAll(p.getAllCodePaths()); 5808 } 5809 } 5810 5811 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5812 PackageParser.Package changingLib) throws PackageManagerException { 5813 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5814 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5815 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5816 for (int i=0; i<N; i++) { 5817 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5818 if (file == null) { 5819 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5820 "Package " + pkg.packageName + " requires unavailable shared library " 5821 + pkg.usesLibraries.get(i) + "; failing!"); 5822 } 5823 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5824 } 5825 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5826 for (int i=0; i<N; i++) { 5827 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5828 if (file == null) { 5829 Slog.w(TAG, "Package " + pkg.packageName 5830 + " desires unavailable shared library " 5831 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5832 } else { 5833 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5834 } 5835 } 5836 N = usesLibraryFiles.size(); 5837 if (N > 0) { 5838 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5839 } else { 5840 pkg.usesLibraryFiles = null; 5841 } 5842 } 5843 } 5844 5845 private static boolean hasString(List<String> list, List<String> which) { 5846 if (list == null) { 5847 return false; 5848 } 5849 for (int i=list.size()-1; i>=0; i--) { 5850 for (int j=which.size()-1; j>=0; j--) { 5851 if (which.get(j).equals(list.get(i))) { 5852 return true; 5853 } 5854 } 5855 } 5856 return false; 5857 } 5858 5859 private void updateAllSharedLibrariesLPw() { 5860 for (PackageParser.Package pkg : mPackages.values()) { 5861 try { 5862 updateSharedLibrariesLPw(pkg, null); 5863 } catch (PackageManagerException e) { 5864 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5865 } 5866 } 5867 } 5868 5869 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5870 PackageParser.Package changingPkg) { 5871 ArrayList<PackageParser.Package> res = null; 5872 for (PackageParser.Package pkg : mPackages.values()) { 5873 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5874 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5875 if (res == null) { 5876 res = new ArrayList<PackageParser.Package>(); 5877 } 5878 res.add(pkg); 5879 try { 5880 updateSharedLibrariesLPw(pkg, changingPkg); 5881 } catch (PackageManagerException e) { 5882 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5883 } 5884 } 5885 } 5886 return res; 5887 } 5888 5889 /** 5890 * Derive the value of the {@code cpuAbiOverride} based on the provided 5891 * value and an optional stored value from the package settings. 5892 */ 5893 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5894 String cpuAbiOverride = null; 5895 5896 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5897 cpuAbiOverride = null; 5898 } else if (abiOverride != null) { 5899 cpuAbiOverride = abiOverride; 5900 } else if (settings != null) { 5901 cpuAbiOverride = settings.cpuAbiOverrideString; 5902 } 5903 5904 return cpuAbiOverride; 5905 } 5906 5907 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5908 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5909 boolean success = false; 5910 try { 5911 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5912 currentTime, user); 5913 success = true; 5914 return res; 5915 } finally { 5916 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5917 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5918 } 5919 } 5920 } 5921 5922 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5923 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5924 final File scanFile = new File(pkg.codePath); 5925 if (pkg.applicationInfo.getCodePath() == null || 5926 pkg.applicationInfo.getResourcePath() == null) { 5927 // Bail out. The resource and code paths haven't been set. 5928 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5929 "Code and resource paths haven't been set correctly"); 5930 } 5931 5932 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5933 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5934 } else { 5935 // Only allow system apps to be flagged as core apps. 5936 pkg.coreApp = false; 5937 } 5938 5939 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5940 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5941 } 5942 5943 if (mCustomResolverComponentName != null && 5944 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5945 setUpCustomResolverActivity(pkg); 5946 } 5947 5948 if (pkg.packageName.equals("android")) { 5949 synchronized (mPackages) { 5950 if (mAndroidApplication != null) { 5951 Slog.w(TAG, "*************************************************"); 5952 Slog.w(TAG, "Core android package being redefined. Skipping."); 5953 Slog.w(TAG, " file=" + scanFile); 5954 Slog.w(TAG, "*************************************************"); 5955 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5956 "Core android package being redefined. Skipping."); 5957 } 5958 5959 // Set up information for our fall-back user intent resolution activity. 5960 mPlatformPackage = pkg; 5961 pkg.mVersionCode = mSdkVersion; 5962 mAndroidApplication = pkg.applicationInfo; 5963 5964 if (!mResolverReplaced) { 5965 mResolveActivity.applicationInfo = mAndroidApplication; 5966 mResolveActivity.name = ResolverActivity.class.getName(); 5967 mResolveActivity.packageName = mAndroidApplication.packageName; 5968 mResolveActivity.processName = "system:ui"; 5969 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5970 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5971 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5972 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5973 mResolveActivity.exported = true; 5974 mResolveActivity.enabled = true; 5975 mResolveInfo.activityInfo = mResolveActivity; 5976 mResolveInfo.priority = 0; 5977 mResolveInfo.preferredOrder = 0; 5978 mResolveInfo.match = 0; 5979 mResolveComponentName = new ComponentName( 5980 mAndroidApplication.packageName, mResolveActivity.name); 5981 } 5982 } 5983 } 5984 5985 if (DEBUG_PACKAGE_SCANNING) { 5986 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5987 Log.d(TAG, "Scanning package " + pkg.packageName); 5988 } 5989 5990 if (mPackages.containsKey(pkg.packageName) 5991 || mSharedLibraries.containsKey(pkg.packageName)) { 5992 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5993 "Application package " + pkg.packageName 5994 + " already installed. Skipping duplicate."); 5995 } 5996 5997 // If we're only installing presumed-existing packages, require that the 5998 // scanned APK is both already known and at the path previously established 5999 // for it. Previously unknown packages we pick up normally, but if we have an 6000 // a priori expectation about this package's install presence, enforce it. 6001 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 6002 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 6003 if (known != null) { 6004 if (DEBUG_PACKAGE_SCANNING) { 6005 Log.d(TAG, "Examining " + pkg.codePath 6006 + " and requiring known paths " + known.codePathString 6007 + " & " + known.resourcePathString); 6008 } 6009 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6010 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6011 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6012 "Application package " + pkg.packageName 6013 + " found at " + pkg.applicationInfo.getCodePath() 6014 + " but expected at " + known.codePathString + "; ignoring."); 6015 } 6016 } 6017 } 6018 6019 // Initialize package source and resource directories 6020 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6021 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6022 6023 SharedUserSetting suid = null; 6024 PackageSetting pkgSetting = null; 6025 6026 if (!isSystemApp(pkg)) { 6027 // Only system apps can use these features. 6028 pkg.mOriginalPackages = null; 6029 pkg.mRealPackage = null; 6030 pkg.mAdoptPermissions = null; 6031 } 6032 6033 // writer 6034 synchronized (mPackages) { 6035 if (pkg.mSharedUserId != null) { 6036 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6037 if (suid == null) { 6038 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6039 "Creating application package " + pkg.packageName 6040 + " for shared user failed"); 6041 } 6042 if (DEBUG_PACKAGE_SCANNING) { 6043 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6044 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6045 + "): packages=" + suid.packages); 6046 } 6047 } 6048 6049 // Check if we are renaming from an original package name. 6050 PackageSetting origPackage = null; 6051 String realName = null; 6052 if (pkg.mOriginalPackages != null) { 6053 // This package may need to be renamed to a previously 6054 // installed name. Let's check on that... 6055 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6056 if (pkg.mOriginalPackages.contains(renamed)) { 6057 // This package had originally been installed as the 6058 // original name, and we have already taken care of 6059 // transitioning to the new one. Just update the new 6060 // one to continue using the old name. 6061 realName = pkg.mRealPackage; 6062 if (!pkg.packageName.equals(renamed)) { 6063 // Callers into this function may have already taken 6064 // care of renaming the package; only do it here if 6065 // it is not already done. 6066 pkg.setPackageName(renamed); 6067 } 6068 6069 } else { 6070 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6071 if ((origPackage = mSettings.peekPackageLPr( 6072 pkg.mOriginalPackages.get(i))) != null) { 6073 // We do have the package already installed under its 6074 // original name... should we use it? 6075 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6076 // New package is not compatible with original. 6077 origPackage = null; 6078 continue; 6079 } else if (origPackage.sharedUser != null) { 6080 // Make sure uid is compatible between packages. 6081 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6082 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6083 + " to " + pkg.packageName + ": old uid " 6084 + origPackage.sharedUser.name 6085 + " differs from " + pkg.mSharedUserId); 6086 origPackage = null; 6087 continue; 6088 } 6089 } else { 6090 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6091 + pkg.packageName + " to old name " + origPackage.name); 6092 } 6093 break; 6094 } 6095 } 6096 } 6097 } 6098 6099 if (mTransferedPackages.contains(pkg.packageName)) { 6100 Slog.w(TAG, "Package " + pkg.packageName 6101 + " was transferred to another, but its .apk remains"); 6102 } 6103 6104 // Just create the setting, don't add it yet. For already existing packages 6105 // the PkgSetting exists already and doesn't have to be created. 6106 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6107 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6108 pkg.applicationInfo.primaryCpuAbi, 6109 pkg.applicationInfo.secondaryCpuAbi, 6110 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6111 user, false); 6112 if (pkgSetting == null) { 6113 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6114 "Creating application package " + pkg.packageName + " failed"); 6115 } 6116 6117 if (pkgSetting.origPackage != null) { 6118 // If we are first transitioning from an original package, 6119 // fix up the new package's name now. We need to do this after 6120 // looking up the package under its new name, so getPackageLP 6121 // can take care of fiddling things correctly. 6122 pkg.setPackageName(origPackage.name); 6123 6124 // File a report about this. 6125 String msg = "New package " + pkgSetting.realName 6126 + " renamed to replace old package " + pkgSetting.name; 6127 reportSettingsProblem(Log.WARN, msg); 6128 6129 // Make a note of it. 6130 mTransferedPackages.add(origPackage.name); 6131 6132 // No longer need to retain this. 6133 pkgSetting.origPackage = null; 6134 } 6135 6136 if (realName != null) { 6137 // Make a note of it. 6138 mTransferedPackages.add(pkg.packageName); 6139 } 6140 6141 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6142 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6143 } 6144 6145 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6146 // Check all shared libraries and map to their actual file path. 6147 // We only do this here for apps not on a system dir, because those 6148 // are the only ones that can fail an install due to this. We 6149 // will take care of the system apps by updating all of their 6150 // library paths after the scan is done. 6151 updateSharedLibrariesLPw(pkg, null); 6152 } 6153 6154 if (mFoundPolicyFile) { 6155 SELinuxMMAC.assignSeinfoValue(pkg); 6156 } 6157 6158 pkg.applicationInfo.uid = pkgSetting.appId; 6159 pkg.mExtras = pkgSetting; 6160 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 6161 try { 6162 verifySignaturesLP(pkgSetting, pkg); 6163 // We just determined the app is signed correctly, so bring 6164 // over the latest parsed certs. 6165 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6166 } catch (PackageManagerException e) { 6167 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6168 throw e; 6169 } 6170 // The signature has changed, but this package is in the system 6171 // image... let's recover! 6172 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6173 // However... if this package is part of a shared user, but it 6174 // doesn't match the signature of the shared user, let's fail. 6175 // What this means is that you can't change the signatures 6176 // associated with an overall shared user, which doesn't seem all 6177 // that unreasonable. 6178 if (pkgSetting.sharedUser != null) { 6179 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6180 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6181 throw new PackageManagerException( 6182 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6183 "Signature mismatch for shared user : " 6184 + pkgSetting.sharedUser); 6185 } 6186 } 6187 // File a report about this. 6188 String msg = "System package " + pkg.packageName 6189 + " signature changed; retaining data."; 6190 reportSettingsProblem(Log.WARN, msg); 6191 } 6192 } else { 6193 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 6194 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6195 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6196 "Package " + pkg.packageName + " upgrade keys do not match the " 6197 + "previously installed version"); 6198 } else { 6199 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6200 String msg = "System package " + pkg.packageName 6201 + " signature changed; retaining data."; 6202 reportSettingsProblem(Log.WARN, msg); 6203 } 6204 } else { 6205 // We just determined the app is signed correctly, so bring 6206 // over the latest parsed certs. 6207 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6208 } 6209 } 6210 // Verify that this new package doesn't have any content providers 6211 // that conflict with existing packages. Only do this if the 6212 // package isn't already installed, since we don't want to break 6213 // things that are installed. 6214 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6215 final int N = pkg.providers.size(); 6216 int i; 6217 for (i=0; i<N; i++) { 6218 PackageParser.Provider p = pkg.providers.get(i); 6219 if (p.info.authority != null) { 6220 String names[] = p.info.authority.split(";"); 6221 for (int j = 0; j < names.length; j++) { 6222 if (mProvidersByAuthority.containsKey(names[j])) { 6223 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6224 final String otherPackageName = 6225 ((other != null && other.getComponentName() != null) ? 6226 other.getComponentName().getPackageName() : "?"); 6227 throw new PackageManagerException( 6228 INSTALL_FAILED_CONFLICTING_PROVIDER, 6229 "Can't install because provider name " + names[j] 6230 + " (in package " + pkg.applicationInfo.packageName 6231 + ") is already used by " + otherPackageName); 6232 } 6233 } 6234 } 6235 } 6236 } 6237 6238 if (pkg.mAdoptPermissions != null) { 6239 // This package wants to adopt ownership of permissions from 6240 // another package. 6241 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6242 final String origName = pkg.mAdoptPermissions.get(i); 6243 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6244 if (orig != null) { 6245 if (verifyPackageUpdateLPr(orig, pkg)) { 6246 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6247 + pkg.packageName); 6248 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6249 } 6250 } 6251 } 6252 } 6253 } 6254 6255 final String pkgName = pkg.packageName; 6256 6257 final long scanFileTime = scanFile.lastModified(); 6258 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6259 pkg.applicationInfo.processName = fixProcessName( 6260 pkg.applicationInfo.packageName, 6261 pkg.applicationInfo.processName, 6262 pkg.applicationInfo.uid); 6263 6264 File dataPath; 6265 if (mPlatformPackage == pkg) { 6266 // The system package is special. 6267 dataPath = new File(Environment.getDataDirectory(), "system"); 6268 6269 pkg.applicationInfo.dataDir = dataPath.getPath(); 6270 6271 } else { 6272 // This is a normal package, need to make its data directory. 6273 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6274 UserHandle.USER_OWNER); 6275 6276 boolean uidError = false; 6277 if (dataPath.exists()) { 6278 int currentUid = 0; 6279 try { 6280 StructStat stat = Os.stat(dataPath.getPath()); 6281 currentUid = stat.st_uid; 6282 } catch (ErrnoException e) { 6283 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6284 } 6285 6286 // If we have mismatched owners for the data path, we have a problem. 6287 if (currentUid != pkg.applicationInfo.uid) { 6288 boolean recovered = false; 6289 if (currentUid == 0) { 6290 // The directory somehow became owned by root. Wow. 6291 // This is probably because the system was stopped while 6292 // installd was in the middle of messing with its libs 6293 // directory. Ask installd to fix that. 6294 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6295 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6296 if (ret >= 0) { 6297 recovered = true; 6298 String msg = "Package " + pkg.packageName 6299 + " unexpectedly changed to uid 0; recovered to " + 6300 + pkg.applicationInfo.uid; 6301 reportSettingsProblem(Log.WARN, msg); 6302 } 6303 } 6304 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6305 || (scanFlags&SCAN_BOOTING) != 0)) { 6306 // If this is a system app, we can at least delete its 6307 // current data so the application will still work. 6308 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6309 if (ret >= 0) { 6310 // TODO: Kill the processes first 6311 // Old data gone! 6312 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6313 ? "System package " : "Third party package "; 6314 String msg = prefix + pkg.packageName 6315 + " has changed from uid: " 6316 + currentUid + " to " 6317 + pkg.applicationInfo.uid + "; old data erased"; 6318 reportSettingsProblem(Log.WARN, msg); 6319 recovered = true; 6320 6321 // And now re-install the app. 6322 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6323 pkg.applicationInfo.seinfo); 6324 if (ret == -1) { 6325 // Ack should not happen! 6326 msg = prefix + pkg.packageName 6327 + " could not have data directory re-created after delete."; 6328 reportSettingsProblem(Log.WARN, msg); 6329 throw new PackageManagerException( 6330 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6331 } 6332 } 6333 if (!recovered) { 6334 mHasSystemUidErrors = true; 6335 } 6336 } else if (!recovered) { 6337 // If we allow this install to proceed, we will be broken. 6338 // Abort, abort! 6339 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6340 "scanPackageLI"); 6341 } 6342 if (!recovered) { 6343 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6344 + pkg.applicationInfo.uid + "/fs_" 6345 + currentUid; 6346 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6347 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6348 String msg = "Package " + pkg.packageName 6349 + " has mismatched uid: " 6350 + currentUid + " on disk, " 6351 + pkg.applicationInfo.uid + " in settings"; 6352 // writer 6353 synchronized (mPackages) { 6354 mSettings.mReadMessages.append(msg); 6355 mSettings.mReadMessages.append('\n'); 6356 uidError = true; 6357 if (!pkgSetting.uidError) { 6358 reportSettingsProblem(Log.ERROR, msg); 6359 } 6360 } 6361 } 6362 } 6363 pkg.applicationInfo.dataDir = dataPath.getPath(); 6364 if (mShouldRestoreconData) { 6365 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6366 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6367 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6368 } 6369 } else { 6370 if (DEBUG_PACKAGE_SCANNING) { 6371 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6372 Log.v(TAG, "Want this data dir: " + dataPath); 6373 } 6374 //invoke installer to do the actual installation 6375 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6376 pkg.applicationInfo.seinfo); 6377 if (ret < 0) { 6378 // Error from installer 6379 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6380 "Unable to create data dirs [errorCode=" + ret + "]"); 6381 } 6382 6383 if (dataPath.exists()) { 6384 pkg.applicationInfo.dataDir = dataPath.getPath(); 6385 } else { 6386 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6387 pkg.applicationInfo.dataDir = null; 6388 } 6389 } 6390 6391 pkgSetting.uidError = uidError; 6392 } 6393 6394 final String path = scanFile.getPath(); 6395 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6396 6397 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6398 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6399 6400 // Some system apps still use directory structure for native libraries 6401 // in which case we might end up not detecting abi solely based on apk 6402 // structure. Try to detect abi based on directory structure. 6403 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6404 pkg.applicationInfo.primaryCpuAbi == null) { 6405 setBundledAppAbisAndRoots(pkg, pkgSetting); 6406 setNativeLibraryPaths(pkg); 6407 } 6408 6409 } else { 6410 if ((scanFlags & SCAN_MOVE) != 0) { 6411 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6412 // but we already have this packages package info in the PackageSetting. We just 6413 // use that and derive the native library path based on the new codepath. 6414 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6415 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6416 } 6417 6418 // Set native library paths again. For moves, the path will be updated based on the 6419 // ABIs we've determined above. For non-moves, the path will be updated based on the 6420 // ABIs we determined during compilation, but the path will depend on the final 6421 // package path (after the rename away from the stage path). 6422 setNativeLibraryPaths(pkg); 6423 } 6424 6425 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6426 final int[] userIds = sUserManager.getUserIds(); 6427 synchronized (mInstallLock) { 6428 // Create a native library symlink only if we have native libraries 6429 // and if the native libraries are 32 bit libraries. We do not provide 6430 // this symlink for 64 bit libraries. 6431 if (pkg.applicationInfo.primaryCpuAbi != null && 6432 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6433 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6434 for (int userId : userIds) { 6435 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6436 nativeLibPath, userId) < 0) { 6437 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6438 "Failed linking native library dir (user=" + userId + ")"); 6439 } 6440 } 6441 } 6442 } 6443 6444 // This is a special case for the "system" package, where the ABI is 6445 // dictated by the zygote configuration (and init.rc). We should keep track 6446 // of this ABI so that we can deal with "normal" applications that run under 6447 // the same UID correctly. 6448 if (mPlatformPackage == pkg) { 6449 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6450 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6451 } 6452 6453 // If there's a mismatch between the abi-override in the package setting 6454 // and the abiOverride specified for the install. Warn about this because we 6455 // would've already compiled the app without taking the package setting into 6456 // account. 6457 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6458 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6459 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6460 " for package: " + pkg.packageName); 6461 } 6462 } 6463 6464 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6465 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6466 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6467 6468 // Copy the derived override back to the parsed package, so that we can 6469 // update the package settings accordingly. 6470 pkg.cpuAbiOverride = cpuAbiOverride; 6471 6472 if (DEBUG_ABI_SELECTION) { 6473 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6474 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6475 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6476 } 6477 6478 // Push the derived path down into PackageSettings so we know what to 6479 // clean up at uninstall time. 6480 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6481 6482 if (DEBUG_ABI_SELECTION) { 6483 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6484 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6485 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6486 } 6487 6488 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6489 // We don't do this here during boot because we can do it all 6490 // at once after scanning all existing packages. 6491 // 6492 // We also do this *before* we perform dexopt on this package, so that 6493 // we can avoid redundant dexopts, and also to make sure we've got the 6494 // code and package path correct. 6495 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6496 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6497 } 6498 6499 if ((scanFlags & SCAN_NO_DEX) == 0) { 6500 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6501 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6502 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6503 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6504 } 6505 } 6506 if (mFactoryTest && pkg.requestedPermissions.contains( 6507 android.Manifest.permission.FACTORY_TEST)) { 6508 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6509 } 6510 6511 ArrayList<PackageParser.Package> clientLibPkgs = null; 6512 6513 // writer 6514 synchronized (mPackages) { 6515 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6516 // Only system apps can add new shared libraries. 6517 if (pkg.libraryNames != null) { 6518 for (int i=0; i<pkg.libraryNames.size(); i++) { 6519 String name = pkg.libraryNames.get(i); 6520 boolean allowed = false; 6521 if (pkg.isUpdatedSystemApp()) { 6522 // New library entries can only be added through the 6523 // system image. This is important to get rid of a lot 6524 // of nasty edge cases: for example if we allowed a non- 6525 // system update of the app to add a library, then uninstalling 6526 // the update would make the library go away, and assumptions 6527 // we made such as through app install filtering would now 6528 // have allowed apps on the device which aren't compatible 6529 // with it. Better to just have the restriction here, be 6530 // conservative, and create many fewer cases that can negatively 6531 // impact the user experience. 6532 final PackageSetting sysPs = mSettings 6533 .getDisabledSystemPkgLPr(pkg.packageName); 6534 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6535 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6536 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6537 allowed = true; 6538 allowed = true; 6539 break; 6540 } 6541 } 6542 } 6543 } else { 6544 allowed = true; 6545 } 6546 if (allowed) { 6547 if (!mSharedLibraries.containsKey(name)) { 6548 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6549 } else if (!name.equals(pkg.packageName)) { 6550 Slog.w(TAG, "Package " + pkg.packageName + " library " 6551 + name + " already exists; skipping"); 6552 } 6553 } else { 6554 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6555 + name + " that is not declared on system image; skipping"); 6556 } 6557 } 6558 if ((scanFlags&SCAN_BOOTING) == 0) { 6559 // If we are not booting, we need to update any applications 6560 // that are clients of our shared library. If we are booting, 6561 // this will all be done once the scan is complete. 6562 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6563 } 6564 } 6565 } 6566 } 6567 6568 // We also need to dexopt any apps that are dependent on this library. Note that 6569 // if these fail, we should abort the install since installing the library will 6570 // result in some apps being broken. 6571 if (clientLibPkgs != null) { 6572 if ((scanFlags & SCAN_NO_DEX) == 0) { 6573 for (int i = 0; i < clientLibPkgs.size(); i++) { 6574 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6575 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6576 null /* instruction sets */, forceDex, 6577 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6578 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6579 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6580 "scanPackageLI failed to dexopt clientLibPkgs"); 6581 } 6582 } 6583 } 6584 } 6585 6586 // Also need to kill any apps that are dependent on the library. 6587 if (clientLibPkgs != null) { 6588 for (int i=0; i<clientLibPkgs.size(); i++) { 6589 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6590 killApplication(clientPkg.applicationInfo.packageName, 6591 clientPkg.applicationInfo.uid, "update lib"); 6592 } 6593 } 6594 6595 // writer 6596 synchronized (mPackages) { 6597 // We don't expect installation to fail beyond this point 6598 6599 // Add the new setting to mSettings 6600 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6601 // Add the new setting to mPackages 6602 mPackages.put(pkg.applicationInfo.packageName, pkg); 6603 // Make sure we don't accidentally delete its data. 6604 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6605 while (iter.hasNext()) { 6606 PackageCleanItem item = iter.next(); 6607 if (pkgName.equals(item.packageName)) { 6608 iter.remove(); 6609 } 6610 } 6611 6612 // Take care of first install / last update times. 6613 if (currentTime != 0) { 6614 if (pkgSetting.firstInstallTime == 0) { 6615 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6616 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6617 pkgSetting.lastUpdateTime = currentTime; 6618 } 6619 } else if (pkgSetting.firstInstallTime == 0) { 6620 // We need *something*. Take time time stamp of the file. 6621 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6622 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6623 if (scanFileTime != pkgSetting.timeStamp) { 6624 // A package on the system image has changed; consider this 6625 // to be an update. 6626 pkgSetting.lastUpdateTime = scanFileTime; 6627 } 6628 } 6629 6630 // Add the package's KeySets to the global KeySetManagerService 6631 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6632 try { 6633 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6634 if (pkg.mKeySetMapping != null) { 6635 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6636 if (pkg.mUpgradeKeySets != null) { 6637 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6638 } 6639 } 6640 } catch (NullPointerException e) { 6641 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6642 } catch (IllegalArgumentException e) { 6643 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6644 } 6645 6646 int N = pkg.providers.size(); 6647 StringBuilder r = null; 6648 int i; 6649 for (i=0; i<N; i++) { 6650 PackageParser.Provider p = pkg.providers.get(i); 6651 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6652 p.info.processName, pkg.applicationInfo.uid); 6653 mProviders.addProvider(p); 6654 p.syncable = p.info.isSyncable; 6655 if (p.info.authority != null) { 6656 String names[] = p.info.authority.split(";"); 6657 p.info.authority = null; 6658 for (int j = 0; j < names.length; j++) { 6659 if (j == 1 && p.syncable) { 6660 // We only want the first authority for a provider to possibly be 6661 // syncable, so if we already added this provider using a different 6662 // authority clear the syncable flag. We copy the provider before 6663 // changing it because the mProviders object contains a reference 6664 // to a provider that we don't want to change. 6665 // Only do this for the second authority since the resulting provider 6666 // object can be the same for all future authorities for this provider. 6667 p = new PackageParser.Provider(p); 6668 p.syncable = false; 6669 } 6670 if (!mProvidersByAuthority.containsKey(names[j])) { 6671 mProvidersByAuthority.put(names[j], p); 6672 if (p.info.authority == null) { 6673 p.info.authority = names[j]; 6674 } else { 6675 p.info.authority = p.info.authority + ";" + names[j]; 6676 } 6677 if (DEBUG_PACKAGE_SCANNING) { 6678 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6679 Log.d(TAG, "Registered content provider: " + names[j] 6680 + ", className = " + p.info.name + ", isSyncable = " 6681 + p.info.isSyncable); 6682 } 6683 } else { 6684 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6685 Slog.w(TAG, "Skipping provider name " + names[j] + 6686 " (in package " + pkg.applicationInfo.packageName + 6687 "): name already used by " 6688 + ((other != null && other.getComponentName() != null) 6689 ? other.getComponentName().getPackageName() : "?")); 6690 } 6691 } 6692 } 6693 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6694 if (r == null) { 6695 r = new StringBuilder(256); 6696 } else { 6697 r.append(' '); 6698 } 6699 r.append(p.info.name); 6700 } 6701 } 6702 if (r != null) { 6703 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6704 } 6705 6706 N = pkg.services.size(); 6707 r = null; 6708 for (i=0; i<N; i++) { 6709 PackageParser.Service s = pkg.services.get(i); 6710 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6711 s.info.processName, pkg.applicationInfo.uid); 6712 mServices.addService(s); 6713 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6714 if (r == null) { 6715 r = new StringBuilder(256); 6716 } else { 6717 r.append(' '); 6718 } 6719 r.append(s.info.name); 6720 } 6721 } 6722 if (r != null) { 6723 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6724 } 6725 6726 N = pkg.receivers.size(); 6727 r = null; 6728 for (i=0; i<N; i++) { 6729 PackageParser.Activity a = pkg.receivers.get(i); 6730 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6731 a.info.processName, pkg.applicationInfo.uid); 6732 mReceivers.addActivity(a, "receiver"); 6733 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6734 if (r == null) { 6735 r = new StringBuilder(256); 6736 } else { 6737 r.append(' '); 6738 } 6739 r.append(a.info.name); 6740 } 6741 } 6742 if (r != null) { 6743 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6744 } 6745 6746 N = pkg.activities.size(); 6747 r = null; 6748 for (i=0; i<N; i++) { 6749 PackageParser.Activity a = pkg.activities.get(i); 6750 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6751 a.info.processName, pkg.applicationInfo.uid); 6752 mActivities.addActivity(a, "activity"); 6753 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6754 if (r == null) { 6755 r = new StringBuilder(256); 6756 } else { 6757 r.append(' '); 6758 } 6759 r.append(a.info.name); 6760 } 6761 } 6762 if (r != null) { 6763 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6764 } 6765 6766 N = pkg.permissionGroups.size(); 6767 r = null; 6768 for (i=0; i<N; i++) { 6769 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6770 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6771 if (cur == null) { 6772 mPermissionGroups.put(pg.info.name, pg); 6773 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6774 if (r == null) { 6775 r = new StringBuilder(256); 6776 } else { 6777 r.append(' '); 6778 } 6779 r.append(pg.info.name); 6780 } 6781 } else { 6782 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6783 + pg.info.packageName + " ignored: original from " 6784 + cur.info.packageName); 6785 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6786 if (r == null) { 6787 r = new StringBuilder(256); 6788 } else { 6789 r.append(' '); 6790 } 6791 r.append("DUP:"); 6792 r.append(pg.info.name); 6793 } 6794 } 6795 } 6796 if (r != null) { 6797 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6798 } 6799 6800 N = pkg.permissions.size(); 6801 r = null; 6802 for (i=0; i<N; i++) { 6803 PackageParser.Permission p = pkg.permissions.get(i); 6804 6805 // Now that permission groups have a special meaning, we ignore permission 6806 // groups for legacy apps to prevent unexpected behavior. In particular, 6807 // permissions for one app being granted to someone just becuase they happen 6808 // to be in a group defined by another app (before this had no implications). 6809 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6810 p.group = mPermissionGroups.get(p.info.group); 6811 // Warn for a permission in an unknown group. 6812 if (p.info.group != null && p.group == null) { 6813 Slog.w(TAG, "Permission " + p.info.name + " from package " 6814 + p.info.packageName + " in an unknown group " + p.info.group); 6815 } 6816 } 6817 6818 ArrayMap<String, BasePermission> permissionMap = 6819 p.tree ? mSettings.mPermissionTrees 6820 : mSettings.mPermissions; 6821 BasePermission bp = permissionMap.get(p.info.name); 6822 6823 // Allow system apps to redefine non-system permissions 6824 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6825 final boolean currentOwnerIsSystem = (bp.perm != null 6826 && isSystemApp(bp.perm.owner)); 6827 if (isSystemApp(p.owner)) { 6828 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6829 // It's a built-in permission and no owner, take ownership now 6830 bp.packageSetting = pkgSetting; 6831 bp.perm = p; 6832 bp.uid = pkg.applicationInfo.uid; 6833 bp.sourcePackage = p.info.packageName; 6834 } else if (!currentOwnerIsSystem) { 6835 String msg = "New decl " + p.owner + " of permission " 6836 + p.info.name + " is system; overriding " + bp.sourcePackage; 6837 reportSettingsProblem(Log.WARN, msg); 6838 bp = null; 6839 } 6840 } 6841 } 6842 6843 if (bp == null) { 6844 bp = new BasePermission(p.info.name, p.info.packageName, 6845 BasePermission.TYPE_NORMAL); 6846 permissionMap.put(p.info.name, bp); 6847 } 6848 6849 if (bp.perm == null) { 6850 if (bp.sourcePackage == null 6851 || bp.sourcePackage.equals(p.info.packageName)) { 6852 BasePermission tree = findPermissionTreeLP(p.info.name); 6853 if (tree == null 6854 || tree.sourcePackage.equals(p.info.packageName)) { 6855 bp.packageSetting = pkgSetting; 6856 bp.perm = p; 6857 bp.uid = pkg.applicationInfo.uid; 6858 bp.sourcePackage = p.info.packageName; 6859 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6860 if (r == null) { 6861 r = new StringBuilder(256); 6862 } else { 6863 r.append(' '); 6864 } 6865 r.append(p.info.name); 6866 } 6867 } else { 6868 Slog.w(TAG, "Permission " + p.info.name + " from package " 6869 + p.info.packageName + " ignored: base tree " 6870 + tree.name + " is from package " 6871 + tree.sourcePackage); 6872 } 6873 } else { 6874 Slog.w(TAG, "Permission " + p.info.name + " from package " 6875 + p.info.packageName + " ignored: original from " 6876 + bp.sourcePackage); 6877 } 6878 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6879 if (r == null) { 6880 r = new StringBuilder(256); 6881 } else { 6882 r.append(' '); 6883 } 6884 r.append("DUP:"); 6885 r.append(p.info.name); 6886 } 6887 if (bp.perm == p) { 6888 bp.protectionLevel = p.info.protectionLevel; 6889 } 6890 } 6891 6892 if (r != null) { 6893 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6894 } 6895 6896 N = pkg.instrumentation.size(); 6897 r = null; 6898 for (i=0; i<N; i++) { 6899 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6900 a.info.packageName = pkg.applicationInfo.packageName; 6901 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6902 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6903 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6904 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6905 a.info.dataDir = pkg.applicationInfo.dataDir; 6906 6907 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6908 // need other information about the application, like the ABI and what not ? 6909 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6910 mInstrumentation.put(a.getComponentName(), a); 6911 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6912 if (r == null) { 6913 r = new StringBuilder(256); 6914 } else { 6915 r.append(' '); 6916 } 6917 r.append(a.info.name); 6918 } 6919 } 6920 if (r != null) { 6921 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6922 } 6923 6924 if (pkg.protectedBroadcasts != null) { 6925 N = pkg.protectedBroadcasts.size(); 6926 for (i=0; i<N; i++) { 6927 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6928 } 6929 } 6930 6931 pkgSetting.setTimeStamp(scanFileTime); 6932 6933 // Create idmap files for pairs of (packages, overlay packages). 6934 // Note: "android", ie framework-res.apk, is handled by native layers. 6935 if (pkg.mOverlayTarget != null) { 6936 // This is an overlay package. 6937 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6938 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6939 mOverlays.put(pkg.mOverlayTarget, 6940 new ArrayMap<String, PackageParser.Package>()); 6941 } 6942 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6943 map.put(pkg.packageName, pkg); 6944 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6945 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6946 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6947 "scanPackageLI failed to createIdmap"); 6948 } 6949 } 6950 } else if (mOverlays.containsKey(pkg.packageName) && 6951 !pkg.packageName.equals("android")) { 6952 // This is a regular package, with one or more known overlay packages. 6953 createIdmapsForPackageLI(pkg); 6954 } 6955 } 6956 6957 return pkg; 6958 } 6959 6960 /** 6961 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6962 * is derived purely on the basis of the contents of {@code scanFile} and 6963 * {@code cpuAbiOverride}. 6964 * 6965 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6966 */ 6967 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6968 String cpuAbiOverride, boolean extractLibs) 6969 throws PackageManagerException { 6970 // TODO: We can probably be smarter about this stuff. For installed apps, 6971 // we can calculate this information at install time once and for all. For 6972 // system apps, we can probably assume that this information doesn't change 6973 // after the first boot scan. As things stand, we do lots of unnecessary work. 6974 6975 // Give ourselves some initial paths; we'll come back for another 6976 // pass once we've determined ABI below. 6977 setNativeLibraryPaths(pkg); 6978 6979 // We would never need to extract libs for forward-locked and external packages, 6980 // since the container service will do it for us. We shouldn't attempt to 6981 // extract libs from system app when it was not updated. 6982 if (pkg.isForwardLocked() || isExternal(pkg) || 6983 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 6984 extractLibs = false; 6985 } 6986 6987 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6988 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6989 6990 NativeLibraryHelper.Handle handle = null; 6991 try { 6992 handle = NativeLibraryHelper.Handle.create(scanFile); 6993 // TODO(multiArch): This can be null for apps that didn't go through the 6994 // usual installation process. We can calculate it again, like we 6995 // do during install time. 6996 // 6997 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6998 // unnecessary. 6999 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 7000 7001 // Null out the abis so that they can be recalculated. 7002 pkg.applicationInfo.primaryCpuAbi = null; 7003 pkg.applicationInfo.secondaryCpuAbi = null; 7004 if (isMultiArch(pkg.applicationInfo)) { 7005 // Warn if we've set an abiOverride for multi-lib packages.. 7006 // By definition, we need to copy both 32 and 64 bit libraries for 7007 // such packages. 7008 if (pkg.cpuAbiOverride != null 7009 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7010 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7011 } 7012 7013 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7014 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7015 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7016 if (extractLibs) { 7017 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7018 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7019 useIsaSpecificSubdirs); 7020 } else { 7021 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7022 } 7023 } 7024 7025 maybeThrowExceptionForMultiArchCopy( 7026 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7027 7028 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7029 if (extractLibs) { 7030 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7031 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7032 useIsaSpecificSubdirs); 7033 } else { 7034 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7035 } 7036 } 7037 7038 maybeThrowExceptionForMultiArchCopy( 7039 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7040 7041 if (abi64 >= 0) { 7042 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7043 } 7044 7045 if (abi32 >= 0) { 7046 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7047 if (abi64 >= 0) { 7048 pkg.applicationInfo.secondaryCpuAbi = abi; 7049 } else { 7050 pkg.applicationInfo.primaryCpuAbi = abi; 7051 } 7052 } 7053 } else { 7054 String[] abiList = (cpuAbiOverride != null) ? 7055 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7056 7057 // Enable gross and lame hacks for apps that are built with old 7058 // SDK tools. We must scan their APKs for renderscript bitcode and 7059 // not launch them if it's present. Don't bother checking on devices 7060 // that don't have 64 bit support. 7061 boolean needsRenderScriptOverride = false; 7062 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7063 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7064 abiList = Build.SUPPORTED_32_BIT_ABIS; 7065 needsRenderScriptOverride = true; 7066 } 7067 7068 final int copyRet; 7069 if (extractLibs) { 7070 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7071 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7072 } else { 7073 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7074 } 7075 7076 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7077 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7078 "Error unpackaging native libs for app, errorCode=" + copyRet); 7079 } 7080 7081 if (copyRet >= 0) { 7082 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7083 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7084 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7085 } else if (needsRenderScriptOverride) { 7086 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7087 } 7088 } 7089 } catch (IOException ioe) { 7090 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7091 } finally { 7092 IoUtils.closeQuietly(handle); 7093 } 7094 7095 // Now that we've calculated the ABIs and determined if it's an internal app, 7096 // we will go ahead and populate the nativeLibraryPath. 7097 setNativeLibraryPaths(pkg); 7098 } 7099 7100 /** 7101 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7102 * i.e, so that all packages can be run inside a single process if required. 7103 * 7104 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7105 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7106 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7107 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7108 * updating a package that belongs to a shared user. 7109 * 7110 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7111 * adds unnecessary complexity. 7112 */ 7113 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7114 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7115 String requiredInstructionSet = null; 7116 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7117 requiredInstructionSet = VMRuntime.getInstructionSet( 7118 scannedPackage.applicationInfo.primaryCpuAbi); 7119 } 7120 7121 PackageSetting requirer = null; 7122 for (PackageSetting ps : packagesForUser) { 7123 // If packagesForUser contains scannedPackage, we skip it. This will happen 7124 // when scannedPackage is an update of an existing package. Without this check, 7125 // we will never be able to change the ABI of any package belonging to a shared 7126 // user, even if it's compatible with other packages. 7127 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7128 if (ps.primaryCpuAbiString == null) { 7129 continue; 7130 } 7131 7132 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7133 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7134 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7135 // this but there's not much we can do. 7136 String errorMessage = "Instruction set mismatch, " 7137 + ((requirer == null) ? "[caller]" : requirer) 7138 + " requires " + requiredInstructionSet + " whereas " + ps 7139 + " requires " + instructionSet; 7140 Slog.w(TAG, errorMessage); 7141 } 7142 7143 if (requiredInstructionSet == null) { 7144 requiredInstructionSet = instructionSet; 7145 requirer = ps; 7146 } 7147 } 7148 } 7149 7150 if (requiredInstructionSet != null) { 7151 String adjustedAbi; 7152 if (requirer != null) { 7153 // requirer != null implies that either scannedPackage was null or that scannedPackage 7154 // did not require an ABI, in which case we have to adjust scannedPackage to match 7155 // the ABI of the set (which is the same as requirer's ABI) 7156 adjustedAbi = requirer.primaryCpuAbiString; 7157 if (scannedPackage != null) { 7158 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7159 } 7160 } else { 7161 // requirer == null implies that we're updating all ABIs in the set to 7162 // match scannedPackage. 7163 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7164 } 7165 7166 for (PackageSetting ps : packagesForUser) { 7167 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7168 if (ps.primaryCpuAbiString != null) { 7169 continue; 7170 } 7171 7172 ps.primaryCpuAbiString = adjustedAbi; 7173 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7174 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7175 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7176 7177 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7178 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7179 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7180 ps.primaryCpuAbiString = null; 7181 ps.pkg.applicationInfo.primaryCpuAbi = null; 7182 return; 7183 } else { 7184 mInstaller.rmdex(ps.codePathString, 7185 getDexCodeInstructionSet(getPreferredInstructionSet())); 7186 } 7187 } 7188 } 7189 } 7190 } 7191 } 7192 7193 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7194 synchronized (mPackages) { 7195 mResolverReplaced = true; 7196 // Set up information for custom user intent resolution activity. 7197 mResolveActivity.applicationInfo = pkg.applicationInfo; 7198 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7199 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7200 mResolveActivity.processName = pkg.applicationInfo.packageName; 7201 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7202 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7203 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7204 mResolveActivity.theme = 0; 7205 mResolveActivity.exported = true; 7206 mResolveActivity.enabled = true; 7207 mResolveInfo.activityInfo = mResolveActivity; 7208 mResolveInfo.priority = 0; 7209 mResolveInfo.preferredOrder = 0; 7210 mResolveInfo.match = 0; 7211 mResolveComponentName = mCustomResolverComponentName; 7212 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7213 mResolveComponentName); 7214 } 7215 } 7216 7217 private static String calculateBundledApkRoot(final String codePathString) { 7218 final File codePath = new File(codePathString); 7219 final File codeRoot; 7220 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7221 codeRoot = Environment.getRootDirectory(); 7222 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7223 codeRoot = Environment.getOemDirectory(); 7224 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7225 codeRoot = Environment.getVendorDirectory(); 7226 } else { 7227 // Unrecognized code path; take its top real segment as the apk root: 7228 // e.g. /something/app/blah.apk => /something 7229 try { 7230 File f = codePath.getCanonicalFile(); 7231 File parent = f.getParentFile(); // non-null because codePath is a file 7232 File tmp; 7233 while ((tmp = parent.getParentFile()) != null) { 7234 f = parent; 7235 parent = tmp; 7236 } 7237 codeRoot = f; 7238 Slog.w(TAG, "Unrecognized code path " 7239 + codePath + " - using " + codeRoot); 7240 } catch (IOException e) { 7241 // Can't canonicalize the code path -- shenanigans? 7242 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7243 return Environment.getRootDirectory().getPath(); 7244 } 7245 } 7246 return codeRoot.getPath(); 7247 } 7248 7249 /** 7250 * Derive and set the location of native libraries for the given package, 7251 * which varies depending on where and how the package was installed. 7252 */ 7253 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7254 final ApplicationInfo info = pkg.applicationInfo; 7255 final String codePath = pkg.codePath; 7256 final File codeFile = new File(codePath); 7257 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7258 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7259 7260 info.nativeLibraryRootDir = null; 7261 info.nativeLibraryRootRequiresIsa = false; 7262 info.nativeLibraryDir = null; 7263 info.secondaryNativeLibraryDir = null; 7264 7265 if (isApkFile(codeFile)) { 7266 // Monolithic install 7267 if (bundledApp) { 7268 // If "/system/lib64/apkname" exists, assume that is the per-package 7269 // native library directory to use; otherwise use "/system/lib/apkname". 7270 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7271 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7272 getPrimaryInstructionSet(info)); 7273 7274 // This is a bundled system app so choose the path based on the ABI. 7275 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7276 // is just the default path. 7277 final String apkName = deriveCodePathName(codePath); 7278 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7279 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7280 apkName).getAbsolutePath(); 7281 7282 if (info.secondaryCpuAbi != null) { 7283 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7284 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7285 secondaryLibDir, apkName).getAbsolutePath(); 7286 } 7287 } else if (asecApp) { 7288 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7289 .getAbsolutePath(); 7290 } else { 7291 final String apkName = deriveCodePathName(codePath); 7292 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7293 .getAbsolutePath(); 7294 } 7295 7296 info.nativeLibraryRootRequiresIsa = false; 7297 info.nativeLibraryDir = info.nativeLibraryRootDir; 7298 } else { 7299 // Cluster install 7300 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7301 info.nativeLibraryRootRequiresIsa = true; 7302 7303 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7304 getPrimaryInstructionSet(info)).getAbsolutePath(); 7305 7306 if (info.secondaryCpuAbi != null) { 7307 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7308 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7309 } 7310 } 7311 } 7312 7313 /** 7314 * Calculate the abis and roots for a bundled app. These can uniquely 7315 * be determined from the contents of the system partition, i.e whether 7316 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7317 * of this information, and instead assume that the system was built 7318 * sensibly. 7319 */ 7320 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7321 PackageSetting pkgSetting) { 7322 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7323 7324 // If "/system/lib64/apkname" exists, assume that is the per-package 7325 // native library directory to use; otherwise use "/system/lib/apkname". 7326 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7327 setBundledAppAbi(pkg, apkRoot, apkName); 7328 // pkgSetting might be null during rescan following uninstall of updates 7329 // to a bundled app, so accommodate that possibility. The settings in 7330 // that case will be established later from the parsed package. 7331 // 7332 // If the settings aren't null, sync them up with what we've just derived. 7333 // note that apkRoot isn't stored in the package settings. 7334 if (pkgSetting != null) { 7335 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7336 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7337 } 7338 } 7339 7340 /** 7341 * Deduces the ABI of a bundled app and sets the relevant fields on the 7342 * parsed pkg object. 7343 * 7344 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7345 * under which system libraries are installed. 7346 * @param apkName the name of the installed package. 7347 */ 7348 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7349 final File codeFile = new File(pkg.codePath); 7350 7351 final boolean has64BitLibs; 7352 final boolean has32BitLibs; 7353 if (isApkFile(codeFile)) { 7354 // Monolithic install 7355 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7356 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7357 } else { 7358 // Cluster install 7359 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7360 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7361 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7362 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7363 has64BitLibs = (new File(rootDir, isa)).exists(); 7364 } else { 7365 has64BitLibs = false; 7366 } 7367 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7368 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7369 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7370 has32BitLibs = (new File(rootDir, isa)).exists(); 7371 } else { 7372 has32BitLibs = false; 7373 } 7374 } 7375 7376 if (has64BitLibs && !has32BitLibs) { 7377 // The package has 64 bit libs, but not 32 bit libs. Its primary 7378 // ABI should be 64 bit. We can safely assume here that the bundled 7379 // native libraries correspond to the most preferred ABI in the list. 7380 7381 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7382 pkg.applicationInfo.secondaryCpuAbi = null; 7383 } else if (has32BitLibs && !has64BitLibs) { 7384 // The package has 32 bit libs but not 64 bit libs. Its primary 7385 // ABI should be 32 bit. 7386 7387 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7388 pkg.applicationInfo.secondaryCpuAbi = null; 7389 } else if (has32BitLibs && has64BitLibs) { 7390 // The application has both 64 and 32 bit bundled libraries. We check 7391 // here that the app declares multiArch support, and warn if it doesn't. 7392 // 7393 // We will be lenient here and record both ABIs. The primary will be the 7394 // ABI that's higher on the list, i.e, a device that's configured to prefer 7395 // 64 bit apps will see a 64 bit primary ABI, 7396 7397 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7398 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7399 } 7400 7401 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7402 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7403 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7404 } else { 7405 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7406 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7407 } 7408 } else { 7409 pkg.applicationInfo.primaryCpuAbi = null; 7410 pkg.applicationInfo.secondaryCpuAbi = null; 7411 } 7412 } 7413 7414 private void killApplication(String pkgName, int appId, String reason) { 7415 // Request the ActivityManager to kill the process(only for existing packages) 7416 // so that we do not end up in a confused state while the user is still using the older 7417 // version of the application while the new one gets installed. 7418 IActivityManager am = ActivityManagerNative.getDefault(); 7419 if (am != null) { 7420 try { 7421 am.killApplicationWithAppId(pkgName, appId, reason); 7422 } catch (RemoteException e) { 7423 } 7424 } 7425 } 7426 7427 void removePackageLI(PackageSetting ps, boolean chatty) { 7428 if (DEBUG_INSTALL) { 7429 if (chatty) 7430 Log.d(TAG, "Removing package " + ps.name); 7431 } 7432 7433 // writer 7434 synchronized (mPackages) { 7435 mPackages.remove(ps.name); 7436 final PackageParser.Package pkg = ps.pkg; 7437 if (pkg != null) { 7438 cleanPackageDataStructuresLILPw(pkg, chatty); 7439 } 7440 } 7441 } 7442 7443 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7444 if (DEBUG_INSTALL) { 7445 if (chatty) 7446 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7447 } 7448 7449 // writer 7450 synchronized (mPackages) { 7451 mPackages.remove(pkg.applicationInfo.packageName); 7452 cleanPackageDataStructuresLILPw(pkg, chatty); 7453 } 7454 } 7455 7456 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7457 int N = pkg.providers.size(); 7458 StringBuilder r = null; 7459 int i; 7460 for (i=0; i<N; i++) { 7461 PackageParser.Provider p = pkg.providers.get(i); 7462 mProviders.removeProvider(p); 7463 if (p.info.authority == null) { 7464 7465 /* There was another ContentProvider with this authority when 7466 * this app was installed so this authority is null, 7467 * Ignore it as we don't have to unregister the provider. 7468 */ 7469 continue; 7470 } 7471 String names[] = p.info.authority.split(";"); 7472 for (int j = 0; j < names.length; j++) { 7473 if (mProvidersByAuthority.get(names[j]) == p) { 7474 mProvidersByAuthority.remove(names[j]); 7475 if (DEBUG_REMOVE) { 7476 if (chatty) 7477 Log.d(TAG, "Unregistered content provider: " + names[j] 7478 + ", className = " + p.info.name + ", isSyncable = " 7479 + p.info.isSyncable); 7480 } 7481 } 7482 } 7483 if (DEBUG_REMOVE && chatty) { 7484 if (r == null) { 7485 r = new StringBuilder(256); 7486 } else { 7487 r.append(' '); 7488 } 7489 r.append(p.info.name); 7490 } 7491 } 7492 if (r != null) { 7493 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7494 } 7495 7496 N = pkg.services.size(); 7497 r = null; 7498 for (i=0; i<N; i++) { 7499 PackageParser.Service s = pkg.services.get(i); 7500 mServices.removeService(s); 7501 if (chatty) { 7502 if (r == null) { 7503 r = new StringBuilder(256); 7504 } else { 7505 r.append(' '); 7506 } 7507 r.append(s.info.name); 7508 } 7509 } 7510 if (r != null) { 7511 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7512 } 7513 7514 N = pkg.receivers.size(); 7515 r = null; 7516 for (i=0; i<N; i++) { 7517 PackageParser.Activity a = pkg.receivers.get(i); 7518 mReceivers.removeActivity(a, "receiver"); 7519 if (DEBUG_REMOVE && chatty) { 7520 if (r == null) { 7521 r = new StringBuilder(256); 7522 } else { 7523 r.append(' '); 7524 } 7525 r.append(a.info.name); 7526 } 7527 } 7528 if (r != null) { 7529 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7530 } 7531 7532 N = pkg.activities.size(); 7533 r = null; 7534 for (i=0; i<N; i++) { 7535 PackageParser.Activity a = pkg.activities.get(i); 7536 mActivities.removeActivity(a, "activity"); 7537 if (DEBUG_REMOVE && chatty) { 7538 if (r == null) { 7539 r = new StringBuilder(256); 7540 } else { 7541 r.append(' '); 7542 } 7543 r.append(a.info.name); 7544 } 7545 } 7546 if (r != null) { 7547 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7548 } 7549 7550 N = pkg.permissions.size(); 7551 r = null; 7552 for (i=0; i<N; i++) { 7553 PackageParser.Permission p = pkg.permissions.get(i); 7554 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7555 if (bp == null) { 7556 bp = mSettings.mPermissionTrees.get(p.info.name); 7557 } 7558 if (bp != null && bp.perm == p) { 7559 bp.perm = null; 7560 if (DEBUG_REMOVE && chatty) { 7561 if (r == null) { 7562 r = new StringBuilder(256); 7563 } else { 7564 r.append(' '); 7565 } 7566 r.append(p.info.name); 7567 } 7568 } 7569 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7570 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7571 if (appOpPerms != null) { 7572 appOpPerms.remove(pkg.packageName); 7573 } 7574 } 7575 } 7576 if (r != null) { 7577 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7578 } 7579 7580 N = pkg.requestedPermissions.size(); 7581 r = null; 7582 for (i=0; i<N; i++) { 7583 String perm = pkg.requestedPermissions.get(i); 7584 BasePermission bp = mSettings.mPermissions.get(perm); 7585 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7586 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7587 if (appOpPerms != null) { 7588 appOpPerms.remove(pkg.packageName); 7589 if (appOpPerms.isEmpty()) { 7590 mAppOpPermissionPackages.remove(perm); 7591 } 7592 } 7593 } 7594 } 7595 if (r != null) { 7596 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7597 } 7598 7599 N = pkg.instrumentation.size(); 7600 r = null; 7601 for (i=0; i<N; i++) { 7602 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7603 mInstrumentation.remove(a.getComponentName()); 7604 if (DEBUG_REMOVE && chatty) { 7605 if (r == null) { 7606 r = new StringBuilder(256); 7607 } else { 7608 r.append(' '); 7609 } 7610 r.append(a.info.name); 7611 } 7612 } 7613 if (r != null) { 7614 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7615 } 7616 7617 r = null; 7618 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7619 // Only system apps can hold shared libraries. 7620 if (pkg.libraryNames != null) { 7621 for (i=0; i<pkg.libraryNames.size(); i++) { 7622 String name = pkg.libraryNames.get(i); 7623 SharedLibraryEntry cur = mSharedLibraries.get(name); 7624 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7625 mSharedLibraries.remove(name); 7626 if (DEBUG_REMOVE && chatty) { 7627 if (r == null) { 7628 r = new StringBuilder(256); 7629 } else { 7630 r.append(' '); 7631 } 7632 r.append(name); 7633 } 7634 } 7635 } 7636 } 7637 } 7638 if (r != null) { 7639 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7640 } 7641 } 7642 7643 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7644 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7645 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7646 return true; 7647 } 7648 } 7649 return false; 7650 } 7651 7652 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7653 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7654 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7655 7656 private void updatePermissionsLPw(String changingPkg, 7657 PackageParser.Package pkgInfo, int flags) { 7658 // Make sure there are no dangling permission trees. 7659 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7660 while (it.hasNext()) { 7661 final BasePermission bp = it.next(); 7662 if (bp.packageSetting == null) { 7663 // We may not yet have parsed the package, so just see if 7664 // we still know about its settings. 7665 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7666 } 7667 if (bp.packageSetting == null) { 7668 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7669 + " from package " + bp.sourcePackage); 7670 it.remove(); 7671 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7672 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7673 Slog.i(TAG, "Removing old permission tree: " + bp.name 7674 + " from package " + bp.sourcePackage); 7675 flags |= UPDATE_PERMISSIONS_ALL; 7676 it.remove(); 7677 } 7678 } 7679 } 7680 7681 // Make sure all dynamic permissions have been assigned to a package, 7682 // and make sure there are no dangling permissions. 7683 it = mSettings.mPermissions.values().iterator(); 7684 while (it.hasNext()) { 7685 final BasePermission bp = it.next(); 7686 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7687 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7688 + bp.name + " pkg=" + bp.sourcePackage 7689 + " info=" + bp.pendingInfo); 7690 if (bp.packageSetting == null && bp.pendingInfo != null) { 7691 final BasePermission tree = findPermissionTreeLP(bp.name); 7692 if (tree != null && tree.perm != null) { 7693 bp.packageSetting = tree.packageSetting; 7694 bp.perm = new PackageParser.Permission(tree.perm.owner, 7695 new PermissionInfo(bp.pendingInfo)); 7696 bp.perm.info.packageName = tree.perm.info.packageName; 7697 bp.perm.info.name = bp.name; 7698 bp.uid = tree.uid; 7699 } 7700 } 7701 } 7702 if (bp.packageSetting == null) { 7703 // We may not yet have parsed the package, so just see if 7704 // we still know about its settings. 7705 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7706 } 7707 if (bp.packageSetting == null) { 7708 Slog.w(TAG, "Removing dangling permission: " + bp.name 7709 + " from package " + bp.sourcePackage); 7710 it.remove(); 7711 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7712 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7713 Slog.i(TAG, "Removing old permission: " + bp.name 7714 + " from package " + bp.sourcePackage); 7715 flags |= UPDATE_PERMISSIONS_ALL; 7716 it.remove(); 7717 } 7718 } 7719 } 7720 7721 // Now update the permissions for all packages, in particular 7722 // replace the granted permissions of the system packages. 7723 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7724 for (PackageParser.Package pkg : mPackages.values()) { 7725 if (pkg != pkgInfo) { 7726 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7727 changingPkg); 7728 } 7729 } 7730 } 7731 7732 if (pkgInfo != null) { 7733 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7734 } 7735 } 7736 7737 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7738 String packageOfInterest) { 7739 // IMPORTANT: There are two types of permissions: install and runtime. 7740 // Install time permissions are granted when the app is installed to 7741 // all device users and users added in the future. Runtime permissions 7742 // are granted at runtime explicitly to specific users. Normal and signature 7743 // protected permissions are install time permissions. Dangerous permissions 7744 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7745 // otherwise they are runtime permissions. This function does not manage 7746 // runtime permissions except for the case an app targeting Lollipop MR1 7747 // being upgraded to target a newer SDK, in which case dangerous permissions 7748 // are transformed from install time to runtime ones. 7749 7750 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7751 if (ps == null) { 7752 return; 7753 } 7754 7755 PermissionsState permissionsState = ps.getPermissionsState(); 7756 PermissionsState origPermissions = permissionsState; 7757 7758 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7759 7760 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7761 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7762 7763 boolean changedInstallPermission = false; 7764 7765 if (replace) { 7766 ps.installPermissionsFixed = false; 7767 if (!ps.isSharedUser()) { 7768 origPermissions = new PermissionsState(permissionsState); 7769 permissionsState.reset(); 7770 } 7771 } 7772 7773 permissionsState.setGlobalGids(mGlobalGids); 7774 7775 final int N = pkg.requestedPermissions.size(); 7776 for (int i=0; i<N; i++) { 7777 final String name = pkg.requestedPermissions.get(i); 7778 final BasePermission bp = mSettings.mPermissions.get(name); 7779 7780 if (DEBUG_INSTALL) { 7781 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7782 } 7783 7784 if (bp == null || bp.packageSetting == null) { 7785 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7786 Slog.w(TAG, "Unknown permission " + name 7787 + " in package " + pkg.packageName); 7788 } 7789 continue; 7790 } 7791 7792 final String perm = bp.name; 7793 boolean allowedSig = false; 7794 int grant = GRANT_DENIED; 7795 7796 // Keep track of app op permissions. 7797 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7798 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7799 if (pkgs == null) { 7800 pkgs = new ArraySet<>(); 7801 mAppOpPermissionPackages.put(bp.name, pkgs); 7802 } 7803 pkgs.add(pkg.packageName); 7804 } 7805 7806 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7807 switch (level) { 7808 case PermissionInfo.PROTECTION_NORMAL: { 7809 // For all apps normal permissions are install time ones. 7810 grant = GRANT_INSTALL; 7811 } break; 7812 7813 case PermissionInfo.PROTECTION_DANGEROUS: { 7814 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7815 // For legacy apps dangerous permissions are install time ones. 7816 grant = GRANT_INSTALL_LEGACY; 7817 } else if (ps.isSystem()) { 7818 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7819 if (origPermissions.hasInstallPermission(bp.name)) { 7820 // If a system app had an install permission, then the app was 7821 // upgraded and we grant the permissions as runtime to all users. 7822 grant = GRANT_UPGRADE; 7823 upgradeUserIds = currentUserIds; 7824 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7825 // If users changed since the last permissions update for a 7826 // system app, we grant the permission as runtime to the new users. 7827 grant = GRANT_UPGRADE; 7828 upgradeUserIds = currentUserIds; 7829 for (int userId : updatedUserIds) { 7830 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7831 } 7832 } else { 7833 // Otherwise, we grant the permission as runtime if the app 7834 // already had it, i.e. we preserve runtime permissions. 7835 grant = GRANT_RUNTIME; 7836 } 7837 } else if (origPermissions.hasInstallPermission(bp.name)) { 7838 // For legacy apps that became modern, install becomes runtime. 7839 grant = GRANT_UPGRADE; 7840 upgradeUserIds = currentUserIds; 7841 } else if (replace) { 7842 // For upgraded modern apps keep runtime permissions unchanged. 7843 grant = GRANT_RUNTIME; 7844 } 7845 } break; 7846 7847 case PermissionInfo.PROTECTION_SIGNATURE: { 7848 // For all apps signature permissions are install time ones. 7849 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7850 if (allowedSig) { 7851 grant = GRANT_INSTALL; 7852 } 7853 } break; 7854 } 7855 7856 if (DEBUG_INSTALL) { 7857 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7858 } 7859 7860 if (grant != GRANT_DENIED) { 7861 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7862 // If this is an existing, non-system package, then 7863 // we can't add any new permissions to it. 7864 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7865 // Except... if this is a permission that was added 7866 // to the platform (note: need to only do this when 7867 // updating the platform). 7868 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7869 grant = GRANT_DENIED; 7870 } 7871 } 7872 } 7873 7874 switch (grant) { 7875 case GRANT_INSTALL: { 7876 // Revoke this as runtime permission to handle the case of 7877 // a runtime permssion being downgraded to an install one. 7878 for (int userId : UserManagerService.getInstance().getUserIds()) { 7879 if (origPermissions.getRuntimePermissionState( 7880 bp.name, userId) != null) { 7881 // Revoke the runtime permission and clear the flags. 7882 origPermissions.revokeRuntimePermission(bp, userId); 7883 origPermissions.updatePermissionFlags(bp, userId, 7884 PackageManager.MASK_PERMISSION_FLAGS, 0); 7885 // If we revoked a permission permission, we have to write. 7886 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7887 changedRuntimePermissionUserIds, userId); 7888 } 7889 } 7890 // Grant an install permission. 7891 if (permissionsState.grantInstallPermission(bp) != 7892 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7893 changedInstallPermission = true; 7894 } 7895 } break; 7896 7897 case GRANT_INSTALL_LEGACY: { 7898 // Grant an install permission. 7899 if (permissionsState.grantInstallPermission(bp) != 7900 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7901 changedInstallPermission = true; 7902 } 7903 } break; 7904 7905 case GRANT_RUNTIME: { 7906 // Grant previously granted runtime permissions. 7907 for (int userId : UserManagerService.getInstance().getUserIds()) { 7908 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7909 PermissionState permissionState = origPermissions 7910 .getRuntimePermissionState(bp.name, userId); 7911 final int flags = permissionState.getFlags(); 7912 if (permissionsState.grantRuntimePermission(bp, userId) == 7913 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7914 // If we cannot put the permission as it was, we have to write. 7915 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7916 changedRuntimePermissionUserIds, userId); 7917 } else { 7918 // System components not only get the permissions but 7919 // they are also fixed, so nothing can change that. 7920 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7921 ? flags 7922 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7923 // Propagate the permission flags. 7924 permissionsState.updatePermissionFlags(bp, userId, 7925 newFlags, newFlags); 7926 } 7927 } 7928 } 7929 } break; 7930 7931 case GRANT_UPGRADE: { 7932 // Grant runtime permissions for a previously held install permission. 7933 PermissionState permissionState = origPermissions 7934 .getInstallPermissionState(bp.name); 7935 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7936 7937 origPermissions.revokeInstallPermission(bp); 7938 // We will be transferring the permission flags, so clear them. 7939 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7940 PackageManager.MASK_PERMISSION_FLAGS, 0); 7941 7942 // If the permission is not to be promoted to runtime we ignore it and 7943 // also its other flags as they are not applicable to install permissions. 7944 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7945 for (int userId : upgradeUserIds) { 7946 if (permissionsState.grantRuntimePermission(bp, userId) != 7947 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7948 // System components not only get the permissions but 7949 // they are also fixed so nothing can change that. 7950 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7951 ? flags 7952 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7953 // Transfer the permission flags. 7954 permissionsState.updatePermissionFlags(bp, userId, 7955 newFlags, newFlags); 7956 // If we granted the permission, we have to write. 7957 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7958 changedRuntimePermissionUserIds, userId); 7959 } 7960 } 7961 } 7962 } break; 7963 7964 default: { 7965 if (packageOfInterest == null 7966 || packageOfInterest.equals(pkg.packageName)) { 7967 Slog.w(TAG, "Not granting permission " + perm 7968 + " to package " + pkg.packageName 7969 + " because it was previously installed without"); 7970 } 7971 } break; 7972 } 7973 } else { 7974 if (permissionsState.revokeInstallPermission(bp) != 7975 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7976 // Also drop the permission flags. 7977 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7978 PackageManager.MASK_PERMISSION_FLAGS, 0); 7979 changedInstallPermission = true; 7980 Slog.i(TAG, "Un-granting permission " + perm 7981 + " from package " + pkg.packageName 7982 + " (protectionLevel=" + bp.protectionLevel 7983 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7984 + ")"); 7985 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7986 // Don't print warning for app op permissions, since it is fine for them 7987 // not to be granted, there is a UI for the user to decide. 7988 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7989 Slog.w(TAG, "Not granting permission " + perm 7990 + " to package " + pkg.packageName 7991 + " (protectionLevel=" + bp.protectionLevel 7992 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7993 + ")"); 7994 } 7995 } 7996 } 7997 } 7998 7999 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 8000 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 8001 // This is the first that we have heard about this package, so the 8002 // permissions we have now selected are fixed until explicitly 8003 // changed. 8004 ps.installPermissionsFixed = true; 8005 } 8006 8007 ps.setPermissionsUpdatedForUserIds(currentUserIds); 8008 8009 // Persist the runtime permissions state for users with changes. 8010 for (int userId : changedRuntimePermissionUserIds) { 8011 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 8012 } 8013 } 8014 8015 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8016 boolean allowed = false; 8017 final int NP = PackageParser.NEW_PERMISSIONS.length; 8018 for (int ip=0; ip<NP; ip++) { 8019 final PackageParser.NewPermissionInfo npi 8020 = PackageParser.NEW_PERMISSIONS[ip]; 8021 if (npi.name.equals(perm) 8022 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8023 allowed = true; 8024 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8025 + pkg.packageName); 8026 break; 8027 } 8028 } 8029 return allowed; 8030 } 8031 8032 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8033 BasePermission bp, PermissionsState origPermissions) { 8034 boolean allowed; 8035 allowed = (compareSignatures( 8036 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8037 == PackageManager.SIGNATURE_MATCH) 8038 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8039 == PackageManager.SIGNATURE_MATCH); 8040 if (!allowed && (bp.protectionLevel 8041 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8042 if (isSystemApp(pkg)) { 8043 // For updated system applications, a system permission 8044 // is granted only if it had been defined by the original application. 8045 if (pkg.isUpdatedSystemApp()) { 8046 final PackageSetting sysPs = mSettings 8047 .getDisabledSystemPkgLPr(pkg.packageName); 8048 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8049 // If the original was granted this permission, we take 8050 // that grant decision as read and propagate it to the 8051 // update. 8052 if (sysPs.isPrivileged()) { 8053 allowed = true; 8054 } 8055 } else { 8056 // The system apk may have been updated with an older 8057 // version of the one on the data partition, but which 8058 // granted a new system permission that it didn't have 8059 // before. In this case we do want to allow the app to 8060 // now get the new permission if the ancestral apk is 8061 // privileged to get it. 8062 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8063 for (int j=0; 8064 j<sysPs.pkg.requestedPermissions.size(); j++) { 8065 if (perm.equals( 8066 sysPs.pkg.requestedPermissions.get(j))) { 8067 allowed = true; 8068 break; 8069 } 8070 } 8071 } 8072 } 8073 } else { 8074 allowed = isPrivilegedApp(pkg); 8075 } 8076 } 8077 } 8078 if (!allowed && (bp.protectionLevel 8079 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8080 // For development permissions, a development permission 8081 // is granted only if it was already granted. 8082 allowed = origPermissions.hasInstallPermission(perm); 8083 } 8084 return allowed; 8085 } 8086 8087 final class ActivityIntentResolver 8088 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8089 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8090 boolean defaultOnly, int userId) { 8091 if (!sUserManager.exists(userId)) return null; 8092 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8093 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8094 } 8095 8096 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8097 int userId) { 8098 if (!sUserManager.exists(userId)) return null; 8099 mFlags = flags; 8100 return super.queryIntent(intent, resolvedType, 8101 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8102 } 8103 8104 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8105 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8106 if (!sUserManager.exists(userId)) return null; 8107 if (packageActivities == null) { 8108 return null; 8109 } 8110 mFlags = flags; 8111 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8112 final int N = packageActivities.size(); 8113 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8114 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8115 8116 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8117 for (int i = 0; i < N; ++i) { 8118 intentFilters = packageActivities.get(i).intents; 8119 if (intentFilters != null && intentFilters.size() > 0) { 8120 PackageParser.ActivityIntentInfo[] array = 8121 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8122 intentFilters.toArray(array); 8123 listCut.add(array); 8124 } 8125 } 8126 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8127 } 8128 8129 public final void addActivity(PackageParser.Activity a, String type) { 8130 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8131 mActivities.put(a.getComponentName(), a); 8132 if (DEBUG_SHOW_INFO) 8133 Log.v( 8134 TAG, " " + type + " " + 8135 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8136 if (DEBUG_SHOW_INFO) 8137 Log.v(TAG, " Class=" + a.info.name); 8138 final int NI = a.intents.size(); 8139 for (int j=0; j<NI; j++) { 8140 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8141 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8142 intent.setPriority(0); 8143 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8144 + a.className + " with priority > 0, forcing to 0"); 8145 } 8146 if (DEBUG_SHOW_INFO) { 8147 Log.v(TAG, " IntentFilter:"); 8148 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8149 } 8150 if (!intent.debugCheck()) { 8151 Log.w(TAG, "==> For Activity " + a.info.name); 8152 } 8153 addFilter(intent); 8154 } 8155 } 8156 8157 public final void removeActivity(PackageParser.Activity a, String type) { 8158 mActivities.remove(a.getComponentName()); 8159 if (DEBUG_SHOW_INFO) { 8160 Log.v(TAG, " " + type + " " 8161 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8162 : a.info.name) + ":"); 8163 Log.v(TAG, " Class=" + a.info.name); 8164 } 8165 final int NI = a.intents.size(); 8166 for (int j=0; j<NI; j++) { 8167 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8168 if (DEBUG_SHOW_INFO) { 8169 Log.v(TAG, " IntentFilter:"); 8170 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8171 } 8172 removeFilter(intent); 8173 } 8174 } 8175 8176 @Override 8177 protected boolean allowFilterResult( 8178 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8179 ActivityInfo filterAi = filter.activity.info; 8180 for (int i=dest.size()-1; i>=0; i--) { 8181 ActivityInfo destAi = dest.get(i).activityInfo; 8182 if (destAi.name == filterAi.name 8183 && destAi.packageName == filterAi.packageName) { 8184 return false; 8185 } 8186 } 8187 return true; 8188 } 8189 8190 @Override 8191 protected ActivityIntentInfo[] newArray(int size) { 8192 return new ActivityIntentInfo[size]; 8193 } 8194 8195 @Override 8196 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8197 if (!sUserManager.exists(userId)) return true; 8198 PackageParser.Package p = filter.activity.owner; 8199 if (p != null) { 8200 PackageSetting ps = (PackageSetting)p.mExtras; 8201 if (ps != null) { 8202 // System apps are never considered stopped for purposes of 8203 // filtering, because there may be no way for the user to 8204 // actually re-launch them. 8205 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8206 && ps.getStopped(userId); 8207 } 8208 } 8209 return false; 8210 } 8211 8212 @Override 8213 protected boolean isPackageForFilter(String packageName, 8214 PackageParser.ActivityIntentInfo info) { 8215 return packageName.equals(info.activity.owner.packageName); 8216 } 8217 8218 @Override 8219 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8220 int match, int userId) { 8221 if (!sUserManager.exists(userId)) return null; 8222 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8223 return null; 8224 } 8225 final PackageParser.Activity activity = info.activity; 8226 if (mSafeMode && (activity.info.applicationInfo.flags 8227 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8228 return null; 8229 } 8230 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8231 if (ps == null) { 8232 return null; 8233 } 8234 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8235 ps.readUserState(userId), userId); 8236 if (ai == null) { 8237 return null; 8238 } 8239 final ResolveInfo res = new ResolveInfo(); 8240 res.activityInfo = ai; 8241 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8242 res.filter = info; 8243 } 8244 if (info != null) { 8245 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8246 } 8247 res.priority = info.getPriority(); 8248 res.preferredOrder = activity.owner.mPreferredOrder; 8249 //System.out.println("Result: " + res.activityInfo.className + 8250 // " = " + res.priority); 8251 res.match = match; 8252 res.isDefault = info.hasDefault; 8253 res.labelRes = info.labelRes; 8254 res.nonLocalizedLabel = info.nonLocalizedLabel; 8255 if (userNeedsBadging(userId)) { 8256 res.noResourceId = true; 8257 } else { 8258 res.icon = info.icon; 8259 } 8260 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8261 return res; 8262 } 8263 8264 @Override 8265 protected void sortResults(List<ResolveInfo> results) { 8266 Collections.sort(results, mResolvePrioritySorter); 8267 } 8268 8269 @Override 8270 protected void dumpFilter(PrintWriter out, String prefix, 8271 PackageParser.ActivityIntentInfo filter) { 8272 out.print(prefix); out.print( 8273 Integer.toHexString(System.identityHashCode(filter.activity))); 8274 out.print(' '); 8275 filter.activity.printComponentShortName(out); 8276 out.print(" filter "); 8277 out.println(Integer.toHexString(System.identityHashCode(filter))); 8278 } 8279 8280 @Override 8281 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8282 return filter.activity; 8283 } 8284 8285 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8286 PackageParser.Activity activity = (PackageParser.Activity)label; 8287 out.print(prefix); out.print( 8288 Integer.toHexString(System.identityHashCode(activity))); 8289 out.print(' '); 8290 activity.printComponentShortName(out); 8291 if (count > 1) { 8292 out.print(" ("); out.print(count); out.print(" filters)"); 8293 } 8294 out.println(); 8295 } 8296 8297// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8298// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8299// final List<ResolveInfo> retList = Lists.newArrayList(); 8300// while (i.hasNext()) { 8301// final ResolveInfo resolveInfo = i.next(); 8302// if (isEnabledLP(resolveInfo.activityInfo)) { 8303// retList.add(resolveInfo); 8304// } 8305// } 8306// return retList; 8307// } 8308 8309 // Keys are String (activity class name), values are Activity. 8310 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8311 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8312 private int mFlags; 8313 } 8314 8315 private final class ServiceIntentResolver 8316 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8317 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8318 boolean defaultOnly, int userId) { 8319 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8320 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8321 } 8322 8323 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8324 int userId) { 8325 if (!sUserManager.exists(userId)) return null; 8326 mFlags = flags; 8327 return super.queryIntent(intent, resolvedType, 8328 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8329 } 8330 8331 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8332 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8333 if (!sUserManager.exists(userId)) return null; 8334 if (packageServices == null) { 8335 return null; 8336 } 8337 mFlags = flags; 8338 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8339 final int N = packageServices.size(); 8340 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8341 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8342 8343 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8344 for (int i = 0; i < N; ++i) { 8345 intentFilters = packageServices.get(i).intents; 8346 if (intentFilters != null && intentFilters.size() > 0) { 8347 PackageParser.ServiceIntentInfo[] array = 8348 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8349 intentFilters.toArray(array); 8350 listCut.add(array); 8351 } 8352 } 8353 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8354 } 8355 8356 public final void addService(PackageParser.Service s) { 8357 mServices.put(s.getComponentName(), s); 8358 if (DEBUG_SHOW_INFO) { 8359 Log.v(TAG, " " 8360 + (s.info.nonLocalizedLabel != null 8361 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8362 Log.v(TAG, " Class=" + s.info.name); 8363 } 8364 final int NI = s.intents.size(); 8365 int j; 8366 for (j=0; j<NI; j++) { 8367 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8368 if (DEBUG_SHOW_INFO) { 8369 Log.v(TAG, " IntentFilter:"); 8370 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8371 } 8372 if (!intent.debugCheck()) { 8373 Log.w(TAG, "==> For Service " + s.info.name); 8374 } 8375 addFilter(intent); 8376 } 8377 } 8378 8379 public final void removeService(PackageParser.Service s) { 8380 mServices.remove(s.getComponentName()); 8381 if (DEBUG_SHOW_INFO) { 8382 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8383 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8384 Log.v(TAG, " Class=" + s.info.name); 8385 } 8386 final int NI = s.intents.size(); 8387 int j; 8388 for (j=0; j<NI; j++) { 8389 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8390 if (DEBUG_SHOW_INFO) { 8391 Log.v(TAG, " IntentFilter:"); 8392 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8393 } 8394 removeFilter(intent); 8395 } 8396 } 8397 8398 @Override 8399 protected boolean allowFilterResult( 8400 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8401 ServiceInfo filterSi = filter.service.info; 8402 for (int i=dest.size()-1; i>=0; i--) { 8403 ServiceInfo destAi = dest.get(i).serviceInfo; 8404 if (destAi.name == filterSi.name 8405 && destAi.packageName == filterSi.packageName) { 8406 return false; 8407 } 8408 } 8409 return true; 8410 } 8411 8412 @Override 8413 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8414 return new PackageParser.ServiceIntentInfo[size]; 8415 } 8416 8417 @Override 8418 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8419 if (!sUserManager.exists(userId)) return true; 8420 PackageParser.Package p = filter.service.owner; 8421 if (p != null) { 8422 PackageSetting ps = (PackageSetting)p.mExtras; 8423 if (ps != null) { 8424 // System apps are never considered stopped for purposes of 8425 // filtering, because there may be no way for the user to 8426 // actually re-launch them. 8427 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8428 && ps.getStopped(userId); 8429 } 8430 } 8431 return false; 8432 } 8433 8434 @Override 8435 protected boolean isPackageForFilter(String packageName, 8436 PackageParser.ServiceIntentInfo info) { 8437 return packageName.equals(info.service.owner.packageName); 8438 } 8439 8440 @Override 8441 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8442 int match, int userId) { 8443 if (!sUserManager.exists(userId)) return null; 8444 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8445 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8446 return null; 8447 } 8448 final PackageParser.Service service = info.service; 8449 if (mSafeMode && (service.info.applicationInfo.flags 8450 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8451 return null; 8452 } 8453 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8454 if (ps == null) { 8455 return null; 8456 } 8457 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8458 ps.readUserState(userId), userId); 8459 if (si == null) { 8460 return null; 8461 } 8462 final ResolveInfo res = new ResolveInfo(); 8463 res.serviceInfo = si; 8464 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8465 res.filter = filter; 8466 } 8467 res.priority = info.getPriority(); 8468 res.preferredOrder = service.owner.mPreferredOrder; 8469 res.match = match; 8470 res.isDefault = info.hasDefault; 8471 res.labelRes = info.labelRes; 8472 res.nonLocalizedLabel = info.nonLocalizedLabel; 8473 res.icon = info.icon; 8474 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8475 return res; 8476 } 8477 8478 @Override 8479 protected void sortResults(List<ResolveInfo> results) { 8480 Collections.sort(results, mResolvePrioritySorter); 8481 } 8482 8483 @Override 8484 protected void dumpFilter(PrintWriter out, String prefix, 8485 PackageParser.ServiceIntentInfo filter) { 8486 out.print(prefix); out.print( 8487 Integer.toHexString(System.identityHashCode(filter.service))); 8488 out.print(' '); 8489 filter.service.printComponentShortName(out); 8490 out.print(" filter "); 8491 out.println(Integer.toHexString(System.identityHashCode(filter))); 8492 } 8493 8494 @Override 8495 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8496 return filter.service; 8497 } 8498 8499 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8500 PackageParser.Service service = (PackageParser.Service)label; 8501 out.print(prefix); out.print( 8502 Integer.toHexString(System.identityHashCode(service))); 8503 out.print(' '); 8504 service.printComponentShortName(out); 8505 if (count > 1) { 8506 out.print(" ("); out.print(count); out.print(" filters)"); 8507 } 8508 out.println(); 8509 } 8510 8511// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8512// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8513// final List<ResolveInfo> retList = Lists.newArrayList(); 8514// while (i.hasNext()) { 8515// final ResolveInfo resolveInfo = (ResolveInfo) i; 8516// if (isEnabledLP(resolveInfo.serviceInfo)) { 8517// retList.add(resolveInfo); 8518// } 8519// } 8520// return retList; 8521// } 8522 8523 // Keys are String (activity class name), values are Activity. 8524 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8525 = new ArrayMap<ComponentName, PackageParser.Service>(); 8526 private int mFlags; 8527 }; 8528 8529 private final class ProviderIntentResolver 8530 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8531 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8532 boolean defaultOnly, int userId) { 8533 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8534 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8535 } 8536 8537 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8538 int userId) { 8539 if (!sUserManager.exists(userId)) 8540 return null; 8541 mFlags = flags; 8542 return super.queryIntent(intent, resolvedType, 8543 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8544 } 8545 8546 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8547 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8548 if (!sUserManager.exists(userId)) 8549 return null; 8550 if (packageProviders == null) { 8551 return null; 8552 } 8553 mFlags = flags; 8554 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8555 final int N = packageProviders.size(); 8556 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8557 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8558 8559 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8560 for (int i = 0; i < N; ++i) { 8561 intentFilters = packageProviders.get(i).intents; 8562 if (intentFilters != null && intentFilters.size() > 0) { 8563 PackageParser.ProviderIntentInfo[] array = 8564 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8565 intentFilters.toArray(array); 8566 listCut.add(array); 8567 } 8568 } 8569 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8570 } 8571 8572 public final void addProvider(PackageParser.Provider p) { 8573 if (mProviders.containsKey(p.getComponentName())) { 8574 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8575 return; 8576 } 8577 8578 mProviders.put(p.getComponentName(), p); 8579 if (DEBUG_SHOW_INFO) { 8580 Log.v(TAG, " " 8581 + (p.info.nonLocalizedLabel != null 8582 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8583 Log.v(TAG, " Class=" + p.info.name); 8584 } 8585 final int NI = p.intents.size(); 8586 int j; 8587 for (j = 0; j < NI; j++) { 8588 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8589 if (DEBUG_SHOW_INFO) { 8590 Log.v(TAG, " IntentFilter:"); 8591 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8592 } 8593 if (!intent.debugCheck()) { 8594 Log.w(TAG, "==> For Provider " + p.info.name); 8595 } 8596 addFilter(intent); 8597 } 8598 } 8599 8600 public final void removeProvider(PackageParser.Provider p) { 8601 mProviders.remove(p.getComponentName()); 8602 if (DEBUG_SHOW_INFO) { 8603 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8604 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8605 Log.v(TAG, " Class=" + p.info.name); 8606 } 8607 final int NI = p.intents.size(); 8608 int j; 8609 for (j = 0; j < NI; j++) { 8610 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8611 if (DEBUG_SHOW_INFO) { 8612 Log.v(TAG, " IntentFilter:"); 8613 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8614 } 8615 removeFilter(intent); 8616 } 8617 } 8618 8619 @Override 8620 protected boolean allowFilterResult( 8621 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8622 ProviderInfo filterPi = filter.provider.info; 8623 for (int i = dest.size() - 1; i >= 0; i--) { 8624 ProviderInfo destPi = dest.get(i).providerInfo; 8625 if (destPi.name == filterPi.name 8626 && destPi.packageName == filterPi.packageName) { 8627 return false; 8628 } 8629 } 8630 return true; 8631 } 8632 8633 @Override 8634 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8635 return new PackageParser.ProviderIntentInfo[size]; 8636 } 8637 8638 @Override 8639 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8640 if (!sUserManager.exists(userId)) 8641 return true; 8642 PackageParser.Package p = filter.provider.owner; 8643 if (p != null) { 8644 PackageSetting ps = (PackageSetting) p.mExtras; 8645 if (ps != null) { 8646 // System apps are never considered stopped for purposes of 8647 // filtering, because there may be no way for the user to 8648 // actually re-launch them. 8649 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8650 && ps.getStopped(userId); 8651 } 8652 } 8653 return false; 8654 } 8655 8656 @Override 8657 protected boolean isPackageForFilter(String packageName, 8658 PackageParser.ProviderIntentInfo info) { 8659 return packageName.equals(info.provider.owner.packageName); 8660 } 8661 8662 @Override 8663 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8664 int match, int userId) { 8665 if (!sUserManager.exists(userId)) 8666 return null; 8667 final PackageParser.ProviderIntentInfo info = filter; 8668 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8669 return null; 8670 } 8671 final PackageParser.Provider provider = info.provider; 8672 if (mSafeMode && (provider.info.applicationInfo.flags 8673 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8674 return null; 8675 } 8676 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8677 if (ps == null) { 8678 return null; 8679 } 8680 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8681 ps.readUserState(userId), userId); 8682 if (pi == null) { 8683 return null; 8684 } 8685 final ResolveInfo res = new ResolveInfo(); 8686 res.providerInfo = pi; 8687 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8688 res.filter = filter; 8689 } 8690 res.priority = info.getPriority(); 8691 res.preferredOrder = provider.owner.mPreferredOrder; 8692 res.match = match; 8693 res.isDefault = info.hasDefault; 8694 res.labelRes = info.labelRes; 8695 res.nonLocalizedLabel = info.nonLocalizedLabel; 8696 res.icon = info.icon; 8697 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8698 return res; 8699 } 8700 8701 @Override 8702 protected void sortResults(List<ResolveInfo> results) { 8703 Collections.sort(results, mResolvePrioritySorter); 8704 } 8705 8706 @Override 8707 protected void dumpFilter(PrintWriter out, String prefix, 8708 PackageParser.ProviderIntentInfo filter) { 8709 out.print(prefix); 8710 out.print( 8711 Integer.toHexString(System.identityHashCode(filter.provider))); 8712 out.print(' '); 8713 filter.provider.printComponentShortName(out); 8714 out.print(" filter "); 8715 out.println(Integer.toHexString(System.identityHashCode(filter))); 8716 } 8717 8718 @Override 8719 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8720 return filter.provider; 8721 } 8722 8723 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8724 PackageParser.Provider provider = (PackageParser.Provider)label; 8725 out.print(prefix); out.print( 8726 Integer.toHexString(System.identityHashCode(provider))); 8727 out.print(' '); 8728 provider.printComponentShortName(out); 8729 if (count > 1) { 8730 out.print(" ("); out.print(count); out.print(" filters)"); 8731 } 8732 out.println(); 8733 } 8734 8735 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8736 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8737 private int mFlags; 8738 }; 8739 8740 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8741 new Comparator<ResolveInfo>() { 8742 public int compare(ResolveInfo r1, ResolveInfo r2) { 8743 int v1 = r1.priority; 8744 int v2 = r2.priority; 8745 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8746 if (v1 != v2) { 8747 return (v1 > v2) ? -1 : 1; 8748 } 8749 v1 = r1.preferredOrder; 8750 v2 = r2.preferredOrder; 8751 if (v1 != v2) { 8752 return (v1 > v2) ? -1 : 1; 8753 } 8754 if (r1.isDefault != r2.isDefault) { 8755 return r1.isDefault ? -1 : 1; 8756 } 8757 v1 = r1.match; 8758 v2 = r2.match; 8759 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8760 if (v1 != v2) { 8761 return (v1 > v2) ? -1 : 1; 8762 } 8763 if (r1.system != r2.system) { 8764 return r1.system ? -1 : 1; 8765 } 8766 return 0; 8767 } 8768 }; 8769 8770 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8771 new Comparator<ProviderInfo>() { 8772 public int compare(ProviderInfo p1, ProviderInfo p2) { 8773 final int v1 = p1.initOrder; 8774 final int v2 = p2.initOrder; 8775 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8776 } 8777 }; 8778 8779 final void sendPackageBroadcast(final String action, final String pkg, 8780 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8781 final int[] userIds) { 8782 mHandler.post(new Runnable() { 8783 @Override 8784 public void run() { 8785 try { 8786 final IActivityManager am = ActivityManagerNative.getDefault(); 8787 if (am == null) return; 8788 final int[] resolvedUserIds; 8789 if (userIds == null) { 8790 resolvedUserIds = am.getRunningUserIds(); 8791 } else { 8792 resolvedUserIds = userIds; 8793 } 8794 for (int id : resolvedUserIds) { 8795 final Intent intent = new Intent(action, 8796 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8797 if (extras != null) { 8798 intent.putExtras(extras); 8799 } 8800 if (targetPkg != null) { 8801 intent.setPackage(targetPkg); 8802 } 8803 // Modify the UID when posting to other users 8804 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8805 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8806 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8807 intent.putExtra(Intent.EXTRA_UID, uid); 8808 } 8809 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8810 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8811 if (DEBUG_BROADCASTS) { 8812 RuntimeException here = new RuntimeException("here"); 8813 here.fillInStackTrace(); 8814 Slog.d(TAG, "Sending to user " + id + ": " 8815 + intent.toShortString(false, true, false, false) 8816 + " " + intent.getExtras(), here); 8817 } 8818 am.broadcastIntent(null, intent, null, finishedReceiver, 8819 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8820 finishedReceiver != null, false, id); 8821 } 8822 } catch (RemoteException ex) { 8823 } 8824 } 8825 }); 8826 } 8827 8828 /** 8829 * Check if the external storage media is available. This is true if there 8830 * is a mounted external storage medium or if the external storage is 8831 * emulated. 8832 */ 8833 private boolean isExternalMediaAvailable() { 8834 return mMediaMounted || Environment.isExternalStorageEmulated(); 8835 } 8836 8837 @Override 8838 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8839 // writer 8840 synchronized (mPackages) { 8841 if (!isExternalMediaAvailable()) { 8842 // If the external storage is no longer mounted at this point, 8843 // the caller may not have been able to delete all of this 8844 // packages files and can not delete any more. Bail. 8845 return null; 8846 } 8847 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8848 if (lastPackage != null) { 8849 pkgs.remove(lastPackage); 8850 } 8851 if (pkgs.size() > 0) { 8852 return pkgs.get(0); 8853 } 8854 } 8855 return null; 8856 } 8857 8858 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8859 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8860 userId, andCode ? 1 : 0, packageName); 8861 if (mSystemReady) { 8862 msg.sendToTarget(); 8863 } else { 8864 if (mPostSystemReadyMessages == null) { 8865 mPostSystemReadyMessages = new ArrayList<>(); 8866 } 8867 mPostSystemReadyMessages.add(msg); 8868 } 8869 } 8870 8871 void startCleaningPackages() { 8872 // reader 8873 synchronized (mPackages) { 8874 if (!isExternalMediaAvailable()) { 8875 return; 8876 } 8877 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8878 return; 8879 } 8880 } 8881 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8882 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8883 IActivityManager am = ActivityManagerNative.getDefault(); 8884 if (am != null) { 8885 try { 8886 am.startService(null, intent, null, UserHandle.USER_OWNER); 8887 } catch (RemoteException e) { 8888 } 8889 } 8890 } 8891 8892 @Override 8893 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8894 int installFlags, String installerPackageName, VerificationParams verificationParams, 8895 String packageAbiOverride) { 8896 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8897 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8898 } 8899 8900 @Override 8901 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8902 int installFlags, String installerPackageName, VerificationParams verificationParams, 8903 String packageAbiOverride, int userId) { 8904 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8905 8906 final int callingUid = Binder.getCallingUid(); 8907 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8908 8909 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8910 try { 8911 if (observer != null) { 8912 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8913 } 8914 } catch (RemoteException re) { 8915 } 8916 return; 8917 } 8918 8919 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8920 installFlags |= PackageManager.INSTALL_FROM_ADB; 8921 8922 } else { 8923 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8924 // about installerPackageName. 8925 8926 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8927 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8928 } 8929 8930 UserHandle user; 8931 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8932 user = UserHandle.ALL; 8933 } else { 8934 user = new UserHandle(userId); 8935 } 8936 8937 // Only system components can circumvent runtime permissions when installing. 8938 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8939 && mContext.checkCallingOrSelfPermission(Manifest.permission 8940 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8941 throw new SecurityException("You need the " 8942 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8943 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8944 } 8945 8946 verificationParams.setInstallerUid(callingUid); 8947 8948 final File originFile = new File(originPath); 8949 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8950 8951 final Message msg = mHandler.obtainMessage(INIT_COPY); 8952 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8953 null, verificationParams, user, packageAbiOverride); 8954 mHandler.sendMessage(msg); 8955 } 8956 8957 void installStage(String packageName, File stagedDir, String stagedCid, 8958 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8959 String installerPackageName, int installerUid, UserHandle user) { 8960 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8961 params.referrerUri, installerUid, null); 8962 8963 final OriginInfo origin; 8964 if (stagedDir != null) { 8965 origin = OriginInfo.fromStagedFile(stagedDir); 8966 } else { 8967 origin = OriginInfo.fromStagedContainer(stagedCid); 8968 } 8969 8970 final Message msg = mHandler.obtainMessage(INIT_COPY); 8971 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8972 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8973 mHandler.sendMessage(msg); 8974 } 8975 8976 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8977 Bundle extras = new Bundle(1); 8978 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8979 8980 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8981 packageName, extras, null, null, new int[] {userId}); 8982 try { 8983 IActivityManager am = ActivityManagerNative.getDefault(); 8984 final boolean isSystem = 8985 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8986 if (isSystem && am.isUserRunning(userId, false)) { 8987 // The just-installed/enabled app is bundled on the system, so presumed 8988 // to be able to run automatically without needing an explicit launch. 8989 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8990 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8991 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8992 .setPackage(packageName); 8993 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8994 android.app.AppOpsManager.OP_NONE, false, false, userId); 8995 } 8996 } catch (RemoteException e) { 8997 // shouldn't happen 8998 Slog.w(TAG, "Unable to bootstrap installed package", e); 8999 } 9000 } 9001 9002 @Override 9003 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9004 int userId) { 9005 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9006 PackageSetting pkgSetting; 9007 final int uid = Binder.getCallingUid(); 9008 enforceCrossUserPermission(uid, userId, true, true, 9009 "setApplicationHiddenSetting for user " + userId); 9010 9011 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9012 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9013 return false; 9014 } 9015 9016 long callingId = Binder.clearCallingIdentity(); 9017 try { 9018 boolean sendAdded = false; 9019 boolean sendRemoved = false; 9020 // writer 9021 synchronized (mPackages) { 9022 pkgSetting = mSettings.mPackages.get(packageName); 9023 if (pkgSetting == null) { 9024 return false; 9025 } 9026 if (pkgSetting.getHidden(userId) != hidden) { 9027 pkgSetting.setHidden(hidden, userId); 9028 mSettings.writePackageRestrictionsLPr(userId); 9029 if (hidden) { 9030 sendRemoved = true; 9031 } else { 9032 sendAdded = true; 9033 } 9034 } 9035 } 9036 if (sendAdded) { 9037 sendPackageAddedForUser(packageName, pkgSetting, userId); 9038 return true; 9039 } 9040 if (sendRemoved) { 9041 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9042 "hiding pkg"); 9043 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9044 } 9045 } finally { 9046 Binder.restoreCallingIdentity(callingId); 9047 } 9048 return false; 9049 } 9050 9051 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9052 int userId) { 9053 final PackageRemovedInfo info = new PackageRemovedInfo(); 9054 info.removedPackage = packageName; 9055 info.removedUsers = new int[] {userId}; 9056 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9057 info.sendBroadcast(false, false, false); 9058 } 9059 9060 /** 9061 * Returns true if application is not found or there was an error. Otherwise it returns 9062 * the hidden state of the package for the given user. 9063 */ 9064 @Override 9065 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9066 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9067 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9068 false, "getApplicationHidden for user " + userId); 9069 PackageSetting pkgSetting; 9070 long callingId = Binder.clearCallingIdentity(); 9071 try { 9072 // writer 9073 synchronized (mPackages) { 9074 pkgSetting = mSettings.mPackages.get(packageName); 9075 if (pkgSetting == null) { 9076 return true; 9077 } 9078 return pkgSetting.getHidden(userId); 9079 } 9080 } finally { 9081 Binder.restoreCallingIdentity(callingId); 9082 } 9083 } 9084 9085 /** 9086 * @hide 9087 */ 9088 @Override 9089 public int installExistingPackageAsUser(String packageName, int userId) { 9090 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9091 null); 9092 PackageSetting pkgSetting; 9093 final int uid = Binder.getCallingUid(); 9094 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9095 + userId); 9096 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9097 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9098 } 9099 9100 long callingId = Binder.clearCallingIdentity(); 9101 try { 9102 boolean sendAdded = false; 9103 9104 // writer 9105 synchronized (mPackages) { 9106 pkgSetting = mSettings.mPackages.get(packageName); 9107 if (pkgSetting == null) { 9108 return PackageManager.INSTALL_FAILED_INVALID_URI; 9109 } 9110 if (!pkgSetting.getInstalled(userId)) { 9111 pkgSetting.setInstalled(true, userId); 9112 pkgSetting.setHidden(false, userId); 9113 mSettings.writePackageRestrictionsLPr(userId); 9114 sendAdded = true; 9115 } 9116 } 9117 9118 if (sendAdded) { 9119 sendPackageAddedForUser(packageName, pkgSetting, userId); 9120 } 9121 } finally { 9122 Binder.restoreCallingIdentity(callingId); 9123 } 9124 9125 return PackageManager.INSTALL_SUCCEEDED; 9126 } 9127 9128 boolean isUserRestricted(int userId, String restrictionKey) { 9129 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9130 if (restrictions.getBoolean(restrictionKey, false)) { 9131 Log.w(TAG, "User is restricted: " + restrictionKey); 9132 return true; 9133 } 9134 return false; 9135 } 9136 9137 @Override 9138 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9139 mContext.enforceCallingOrSelfPermission( 9140 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9141 "Only package verification agents can verify applications"); 9142 9143 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9144 final PackageVerificationResponse response = new PackageVerificationResponse( 9145 verificationCode, Binder.getCallingUid()); 9146 msg.arg1 = id; 9147 msg.obj = response; 9148 mHandler.sendMessage(msg); 9149 } 9150 9151 @Override 9152 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9153 long millisecondsToDelay) { 9154 mContext.enforceCallingOrSelfPermission( 9155 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9156 "Only package verification agents can extend verification timeouts"); 9157 9158 final PackageVerificationState state = mPendingVerification.get(id); 9159 final PackageVerificationResponse response = new PackageVerificationResponse( 9160 verificationCodeAtTimeout, Binder.getCallingUid()); 9161 9162 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9163 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9164 } 9165 if (millisecondsToDelay < 0) { 9166 millisecondsToDelay = 0; 9167 } 9168 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9169 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9170 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9171 } 9172 9173 if ((state != null) && !state.timeoutExtended()) { 9174 state.extendTimeout(); 9175 9176 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9177 msg.arg1 = id; 9178 msg.obj = response; 9179 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9180 } 9181 } 9182 9183 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9184 int verificationCode, UserHandle user) { 9185 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9186 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9187 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9188 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9189 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9190 9191 mContext.sendBroadcastAsUser(intent, user, 9192 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9193 } 9194 9195 private ComponentName matchComponentForVerifier(String packageName, 9196 List<ResolveInfo> receivers) { 9197 ActivityInfo targetReceiver = null; 9198 9199 final int NR = receivers.size(); 9200 for (int i = 0; i < NR; i++) { 9201 final ResolveInfo info = receivers.get(i); 9202 if (info.activityInfo == null) { 9203 continue; 9204 } 9205 9206 if (packageName.equals(info.activityInfo.packageName)) { 9207 targetReceiver = info.activityInfo; 9208 break; 9209 } 9210 } 9211 9212 if (targetReceiver == null) { 9213 return null; 9214 } 9215 9216 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9217 } 9218 9219 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9220 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9221 if (pkgInfo.verifiers.length == 0) { 9222 return null; 9223 } 9224 9225 final int N = pkgInfo.verifiers.length; 9226 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9227 for (int i = 0; i < N; i++) { 9228 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9229 9230 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9231 receivers); 9232 if (comp == null) { 9233 continue; 9234 } 9235 9236 final int verifierUid = getUidForVerifier(verifierInfo); 9237 if (verifierUid == -1) { 9238 continue; 9239 } 9240 9241 if (DEBUG_VERIFY) { 9242 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9243 + " with the correct signature"); 9244 } 9245 sufficientVerifiers.add(comp); 9246 verificationState.addSufficientVerifier(verifierUid); 9247 } 9248 9249 return sufficientVerifiers; 9250 } 9251 9252 private int getUidForVerifier(VerifierInfo verifierInfo) { 9253 synchronized (mPackages) { 9254 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9255 if (pkg == null) { 9256 return -1; 9257 } else if (pkg.mSignatures.length != 1) { 9258 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9259 + " has more than one signature; ignoring"); 9260 return -1; 9261 } 9262 9263 /* 9264 * If the public key of the package's signature does not match 9265 * our expected public key, then this is a different package and 9266 * we should skip. 9267 */ 9268 9269 final byte[] expectedPublicKey; 9270 try { 9271 final Signature verifierSig = pkg.mSignatures[0]; 9272 final PublicKey publicKey = verifierSig.getPublicKey(); 9273 expectedPublicKey = publicKey.getEncoded(); 9274 } catch (CertificateException e) { 9275 return -1; 9276 } 9277 9278 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9279 9280 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9281 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9282 + " does not have the expected public key; ignoring"); 9283 return -1; 9284 } 9285 9286 return pkg.applicationInfo.uid; 9287 } 9288 } 9289 9290 @Override 9291 public void finishPackageInstall(int token) { 9292 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9293 9294 if (DEBUG_INSTALL) { 9295 Slog.v(TAG, "BM finishing package install for " + token); 9296 } 9297 9298 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9299 mHandler.sendMessage(msg); 9300 } 9301 9302 /** 9303 * Get the verification agent timeout. 9304 * 9305 * @return verification timeout in milliseconds 9306 */ 9307 private long getVerificationTimeout() { 9308 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9309 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9310 DEFAULT_VERIFICATION_TIMEOUT); 9311 } 9312 9313 /** 9314 * Get the default verification agent response code. 9315 * 9316 * @return default verification response code 9317 */ 9318 private int getDefaultVerificationResponse() { 9319 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9320 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9321 DEFAULT_VERIFICATION_RESPONSE); 9322 } 9323 9324 /** 9325 * Check whether or not package verification has been enabled. 9326 * 9327 * @return true if verification should be performed 9328 */ 9329 private boolean isVerificationEnabled(int userId, int installFlags) { 9330 if (!DEFAULT_VERIFY_ENABLE) { 9331 return false; 9332 } 9333 9334 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9335 9336 // Check if installing from ADB 9337 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9338 // Do not run verification in a test harness environment 9339 if (ActivityManager.isRunningInTestHarness()) { 9340 return false; 9341 } 9342 if (ensureVerifyAppsEnabled) { 9343 return true; 9344 } 9345 // Check if the developer does not want package verification for ADB installs 9346 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9347 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9348 return false; 9349 } 9350 } 9351 9352 if (ensureVerifyAppsEnabled) { 9353 return true; 9354 } 9355 9356 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9357 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9358 } 9359 9360 @Override 9361 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9362 throws RemoteException { 9363 mContext.enforceCallingOrSelfPermission( 9364 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9365 "Only intentfilter verification agents can verify applications"); 9366 9367 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9368 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9369 Binder.getCallingUid(), verificationCode, failedDomains); 9370 msg.arg1 = id; 9371 msg.obj = response; 9372 mHandler.sendMessage(msg); 9373 } 9374 9375 @Override 9376 public int getIntentVerificationStatus(String packageName, int userId) { 9377 synchronized (mPackages) { 9378 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9379 } 9380 } 9381 9382 @Override 9383 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9384 boolean result = false; 9385 synchronized (mPackages) { 9386 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9387 } 9388 if (result) { 9389 scheduleWritePackageRestrictionsLocked(userId); 9390 } 9391 return result; 9392 } 9393 9394 @Override 9395 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9396 synchronized (mPackages) { 9397 return mSettings.getIntentFilterVerificationsLPr(packageName); 9398 } 9399 } 9400 9401 @Override 9402 public List<IntentFilter> getAllIntentFilters(String packageName) { 9403 if (TextUtils.isEmpty(packageName)) { 9404 return Collections.<IntentFilter>emptyList(); 9405 } 9406 synchronized (mPackages) { 9407 PackageParser.Package pkg = mPackages.get(packageName); 9408 if (pkg == null || pkg.activities == null) { 9409 return Collections.<IntentFilter>emptyList(); 9410 } 9411 final int count = pkg.activities.size(); 9412 ArrayList<IntentFilter> result = new ArrayList<>(); 9413 for (int n=0; n<count; n++) { 9414 PackageParser.Activity activity = pkg.activities.get(n); 9415 if (activity.intents != null || activity.intents.size() > 0) { 9416 result.addAll(activity.intents); 9417 } 9418 } 9419 return result; 9420 } 9421 } 9422 9423 @Override 9424 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9425 synchronized (mPackages) { 9426 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9427 if (packageName != null) { 9428 result |= updateIntentVerificationStatus(packageName, 9429 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9430 UserHandle.myUserId()); 9431 } 9432 return result; 9433 } 9434 } 9435 9436 @Override 9437 public String getDefaultBrowserPackageName(int userId) { 9438 synchronized (mPackages) { 9439 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9440 } 9441 } 9442 9443 /** 9444 * Get the "allow unknown sources" setting. 9445 * 9446 * @return the current "allow unknown sources" setting 9447 */ 9448 private int getUnknownSourcesSettings() { 9449 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9450 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9451 -1); 9452 } 9453 9454 @Override 9455 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9456 final int uid = Binder.getCallingUid(); 9457 // writer 9458 synchronized (mPackages) { 9459 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9460 if (targetPackageSetting == null) { 9461 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9462 } 9463 9464 PackageSetting installerPackageSetting; 9465 if (installerPackageName != null) { 9466 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9467 if (installerPackageSetting == null) { 9468 throw new IllegalArgumentException("Unknown installer package: " 9469 + installerPackageName); 9470 } 9471 } else { 9472 installerPackageSetting = null; 9473 } 9474 9475 Signature[] callerSignature; 9476 Object obj = mSettings.getUserIdLPr(uid); 9477 if (obj != null) { 9478 if (obj instanceof SharedUserSetting) { 9479 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9480 } else if (obj instanceof PackageSetting) { 9481 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9482 } else { 9483 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9484 } 9485 } else { 9486 throw new SecurityException("Unknown calling uid " + uid); 9487 } 9488 9489 // Verify: can't set installerPackageName to a package that is 9490 // not signed with the same cert as the caller. 9491 if (installerPackageSetting != null) { 9492 if (compareSignatures(callerSignature, 9493 installerPackageSetting.signatures.mSignatures) 9494 != PackageManager.SIGNATURE_MATCH) { 9495 throw new SecurityException( 9496 "Caller does not have same cert as new installer package " 9497 + installerPackageName); 9498 } 9499 } 9500 9501 // Verify: if target already has an installer package, it must 9502 // be signed with the same cert as the caller. 9503 if (targetPackageSetting.installerPackageName != null) { 9504 PackageSetting setting = mSettings.mPackages.get( 9505 targetPackageSetting.installerPackageName); 9506 // If the currently set package isn't valid, then it's always 9507 // okay to change it. 9508 if (setting != null) { 9509 if (compareSignatures(callerSignature, 9510 setting.signatures.mSignatures) 9511 != PackageManager.SIGNATURE_MATCH) { 9512 throw new SecurityException( 9513 "Caller does not have same cert as old installer package " 9514 + targetPackageSetting.installerPackageName); 9515 } 9516 } 9517 } 9518 9519 // Okay! 9520 targetPackageSetting.installerPackageName = installerPackageName; 9521 scheduleWriteSettingsLocked(); 9522 } 9523 } 9524 9525 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9526 // Queue up an async operation since the package installation may take a little while. 9527 mHandler.post(new Runnable() { 9528 public void run() { 9529 mHandler.removeCallbacks(this); 9530 // Result object to be returned 9531 PackageInstalledInfo res = new PackageInstalledInfo(); 9532 res.returnCode = currentStatus; 9533 res.uid = -1; 9534 res.pkg = null; 9535 res.removedInfo = new PackageRemovedInfo(); 9536 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9537 args.doPreInstall(res.returnCode); 9538 synchronized (mInstallLock) { 9539 installPackageLI(args, res); 9540 } 9541 args.doPostInstall(res.returnCode, res.uid); 9542 } 9543 9544 // A restore should be performed at this point if (a) the install 9545 // succeeded, (b) the operation is not an update, and (c) the new 9546 // package has not opted out of backup participation. 9547 final boolean update = res.removedInfo.removedPackage != null; 9548 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9549 boolean doRestore = !update 9550 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9551 9552 // Set up the post-install work request bookkeeping. This will be used 9553 // and cleaned up by the post-install event handling regardless of whether 9554 // there's a restore pass performed. Token values are >= 1. 9555 int token; 9556 if (mNextInstallToken < 0) mNextInstallToken = 1; 9557 token = mNextInstallToken++; 9558 9559 PostInstallData data = new PostInstallData(args, res); 9560 mRunningInstalls.put(token, data); 9561 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9562 9563 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9564 // Pass responsibility to the Backup Manager. It will perform a 9565 // restore if appropriate, then pass responsibility back to the 9566 // Package Manager to run the post-install observer callbacks 9567 // and broadcasts. 9568 IBackupManager bm = IBackupManager.Stub.asInterface( 9569 ServiceManager.getService(Context.BACKUP_SERVICE)); 9570 if (bm != null) { 9571 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9572 + " to BM for possible restore"); 9573 try { 9574 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9575 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9576 } else { 9577 doRestore = false; 9578 } 9579 } catch (RemoteException e) { 9580 // can't happen; the backup manager is local 9581 } catch (Exception e) { 9582 Slog.e(TAG, "Exception trying to enqueue restore", e); 9583 doRestore = false; 9584 } 9585 } else { 9586 Slog.e(TAG, "Backup Manager not found!"); 9587 doRestore = false; 9588 } 9589 } 9590 9591 if (!doRestore) { 9592 // No restore possible, or the Backup Manager was mysteriously not 9593 // available -- just fire the post-install work request directly. 9594 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9595 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9596 mHandler.sendMessage(msg); 9597 } 9598 } 9599 }); 9600 } 9601 9602 private abstract class HandlerParams { 9603 private static final int MAX_RETRIES = 4; 9604 9605 /** 9606 * Number of times startCopy() has been attempted and had a non-fatal 9607 * error. 9608 */ 9609 private int mRetries = 0; 9610 9611 /** User handle for the user requesting the information or installation. */ 9612 private final UserHandle mUser; 9613 9614 HandlerParams(UserHandle user) { 9615 mUser = user; 9616 } 9617 9618 UserHandle getUser() { 9619 return mUser; 9620 } 9621 9622 final boolean startCopy() { 9623 boolean res; 9624 try { 9625 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9626 9627 if (++mRetries > MAX_RETRIES) { 9628 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9629 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9630 handleServiceError(); 9631 return false; 9632 } else { 9633 handleStartCopy(); 9634 res = true; 9635 } 9636 } catch (RemoteException e) { 9637 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9638 mHandler.sendEmptyMessage(MCS_RECONNECT); 9639 res = false; 9640 } 9641 handleReturnCode(); 9642 return res; 9643 } 9644 9645 final void serviceError() { 9646 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9647 handleServiceError(); 9648 handleReturnCode(); 9649 } 9650 9651 abstract void handleStartCopy() throws RemoteException; 9652 abstract void handleServiceError(); 9653 abstract void handleReturnCode(); 9654 } 9655 9656 class MeasureParams extends HandlerParams { 9657 private final PackageStats mStats; 9658 private boolean mSuccess; 9659 9660 private final IPackageStatsObserver mObserver; 9661 9662 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9663 super(new UserHandle(stats.userHandle)); 9664 mObserver = observer; 9665 mStats = stats; 9666 } 9667 9668 @Override 9669 public String toString() { 9670 return "MeasureParams{" 9671 + Integer.toHexString(System.identityHashCode(this)) 9672 + " " + mStats.packageName + "}"; 9673 } 9674 9675 @Override 9676 void handleStartCopy() throws RemoteException { 9677 synchronized (mInstallLock) { 9678 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9679 } 9680 9681 if (mSuccess) { 9682 final boolean mounted; 9683 if (Environment.isExternalStorageEmulated()) { 9684 mounted = true; 9685 } else { 9686 final String status = Environment.getExternalStorageState(); 9687 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9688 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9689 } 9690 9691 if (mounted) { 9692 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9693 9694 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9695 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9696 9697 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9698 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9699 9700 // Always subtract cache size, since it's a subdirectory 9701 mStats.externalDataSize -= mStats.externalCacheSize; 9702 9703 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9704 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9705 9706 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9707 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9708 } 9709 } 9710 } 9711 9712 @Override 9713 void handleReturnCode() { 9714 if (mObserver != null) { 9715 try { 9716 mObserver.onGetStatsCompleted(mStats, mSuccess); 9717 } catch (RemoteException e) { 9718 Slog.i(TAG, "Observer no longer exists."); 9719 } 9720 } 9721 } 9722 9723 @Override 9724 void handleServiceError() { 9725 Slog.e(TAG, "Could not measure application " + mStats.packageName 9726 + " external storage"); 9727 } 9728 } 9729 9730 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9731 throws RemoteException { 9732 long result = 0; 9733 for (File path : paths) { 9734 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9735 } 9736 return result; 9737 } 9738 9739 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9740 for (File path : paths) { 9741 try { 9742 mcs.clearDirectory(path.getAbsolutePath()); 9743 } catch (RemoteException e) { 9744 } 9745 } 9746 } 9747 9748 static class OriginInfo { 9749 /** 9750 * Location where install is coming from, before it has been 9751 * copied/renamed into place. This could be a single monolithic APK 9752 * file, or a cluster directory. This location may be untrusted. 9753 */ 9754 final File file; 9755 final String cid; 9756 9757 /** 9758 * Flag indicating that {@link #file} or {@link #cid} has already been 9759 * staged, meaning downstream users don't need to defensively copy the 9760 * contents. 9761 */ 9762 final boolean staged; 9763 9764 /** 9765 * Flag indicating that {@link #file} or {@link #cid} is an already 9766 * installed app that is being moved. 9767 */ 9768 final boolean existing; 9769 9770 final String resolvedPath; 9771 final File resolvedFile; 9772 9773 static OriginInfo fromNothing() { 9774 return new OriginInfo(null, null, false, false); 9775 } 9776 9777 static OriginInfo fromUntrustedFile(File file) { 9778 return new OriginInfo(file, null, false, false); 9779 } 9780 9781 static OriginInfo fromExistingFile(File file) { 9782 return new OriginInfo(file, null, false, true); 9783 } 9784 9785 static OriginInfo fromStagedFile(File file) { 9786 return new OriginInfo(file, null, true, false); 9787 } 9788 9789 static OriginInfo fromStagedContainer(String cid) { 9790 return new OriginInfo(null, cid, true, false); 9791 } 9792 9793 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9794 this.file = file; 9795 this.cid = cid; 9796 this.staged = staged; 9797 this.existing = existing; 9798 9799 if (cid != null) { 9800 resolvedPath = PackageHelper.getSdDir(cid); 9801 resolvedFile = new File(resolvedPath); 9802 } else if (file != null) { 9803 resolvedPath = file.getAbsolutePath(); 9804 resolvedFile = file; 9805 } else { 9806 resolvedPath = null; 9807 resolvedFile = null; 9808 } 9809 } 9810 } 9811 9812 class MoveInfo { 9813 final int moveId; 9814 final String fromUuid; 9815 final String toUuid; 9816 final String packageName; 9817 final String dataAppName; 9818 final int appId; 9819 final String seinfo; 9820 9821 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9822 String dataAppName, int appId, String seinfo) { 9823 this.moveId = moveId; 9824 this.fromUuid = fromUuid; 9825 this.toUuid = toUuid; 9826 this.packageName = packageName; 9827 this.dataAppName = dataAppName; 9828 this.appId = appId; 9829 this.seinfo = seinfo; 9830 } 9831 } 9832 9833 class InstallParams extends HandlerParams { 9834 final OriginInfo origin; 9835 final MoveInfo move; 9836 final IPackageInstallObserver2 observer; 9837 int installFlags; 9838 final String installerPackageName; 9839 final String volumeUuid; 9840 final VerificationParams verificationParams; 9841 private InstallArgs mArgs; 9842 private int mRet; 9843 final String packageAbiOverride; 9844 9845 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9846 int installFlags, String installerPackageName, String volumeUuid, 9847 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9848 super(user); 9849 this.origin = origin; 9850 this.move = move; 9851 this.observer = observer; 9852 this.installFlags = installFlags; 9853 this.installerPackageName = installerPackageName; 9854 this.volumeUuid = volumeUuid; 9855 this.verificationParams = verificationParams; 9856 this.packageAbiOverride = packageAbiOverride; 9857 } 9858 9859 @Override 9860 public String toString() { 9861 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9862 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9863 } 9864 9865 public ManifestDigest getManifestDigest() { 9866 if (verificationParams == null) { 9867 return null; 9868 } 9869 return verificationParams.getManifestDigest(); 9870 } 9871 9872 private int installLocationPolicy(PackageInfoLite pkgLite) { 9873 String packageName = pkgLite.packageName; 9874 int installLocation = pkgLite.installLocation; 9875 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9876 // reader 9877 synchronized (mPackages) { 9878 PackageParser.Package pkg = mPackages.get(packageName); 9879 if (pkg != null) { 9880 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9881 // Check for downgrading. 9882 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9883 try { 9884 checkDowngrade(pkg, pkgLite); 9885 } catch (PackageManagerException e) { 9886 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9887 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9888 } 9889 } 9890 // Check for updated system application. 9891 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9892 if (onSd) { 9893 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9894 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9895 } 9896 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9897 } else { 9898 if (onSd) { 9899 // Install flag overrides everything. 9900 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9901 } 9902 // If current upgrade specifies particular preference 9903 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9904 // Application explicitly specified internal. 9905 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9906 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9907 // App explictly prefers external. Let policy decide 9908 } else { 9909 // Prefer previous location 9910 if (isExternal(pkg)) { 9911 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9912 } 9913 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9914 } 9915 } 9916 } else { 9917 // Invalid install. Return error code 9918 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9919 } 9920 } 9921 } 9922 // All the special cases have been taken care of. 9923 // Return result based on recommended install location. 9924 if (onSd) { 9925 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9926 } 9927 return pkgLite.recommendedInstallLocation; 9928 } 9929 9930 /* 9931 * Invoke remote method to get package information and install 9932 * location values. Override install location based on default 9933 * policy if needed and then create install arguments based 9934 * on the install location. 9935 */ 9936 public void handleStartCopy() throws RemoteException { 9937 int ret = PackageManager.INSTALL_SUCCEEDED; 9938 9939 // If we're already staged, we've firmly committed to an install location 9940 if (origin.staged) { 9941 if (origin.file != null) { 9942 installFlags |= PackageManager.INSTALL_INTERNAL; 9943 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9944 } else if (origin.cid != null) { 9945 installFlags |= PackageManager.INSTALL_EXTERNAL; 9946 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9947 } else { 9948 throw new IllegalStateException("Invalid stage location"); 9949 } 9950 } 9951 9952 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9953 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9954 9955 PackageInfoLite pkgLite = null; 9956 9957 if (onInt && onSd) { 9958 // Check if both bits are set. 9959 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9960 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9961 } else { 9962 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9963 packageAbiOverride); 9964 9965 /* 9966 * If we have too little free space, try to free cache 9967 * before giving up. 9968 */ 9969 if (!origin.staged && pkgLite.recommendedInstallLocation 9970 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9971 // TODO: focus freeing disk space on the target device 9972 final StorageManager storage = StorageManager.from(mContext); 9973 final long lowThreshold = storage.getStorageLowBytes( 9974 Environment.getDataDirectory()); 9975 9976 final long sizeBytes = mContainerService.calculateInstalledSize( 9977 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9978 9979 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9980 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9981 installFlags, packageAbiOverride); 9982 } 9983 9984 /* 9985 * The cache free must have deleted the file we 9986 * downloaded to install. 9987 * 9988 * TODO: fix the "freeCache" call to not delete 9989 * the file we care about. 9990 */ 9991 if (pkgLite.recommendedInstallLocation 9992 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9993 pkgLite.recommendedInstallLocation 9994 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9995 } 9996 } 9997 } 9998 9999 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10000 int loc = pkgLite.recommendedInstallLocation; 10001 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 10002 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10003 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10004 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10005 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10006 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10007 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10008 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10009 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10010 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10011 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10012 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10013 } else { 10014 // Override with defaults if needed. 10015 loc = installLocationPolicy(pkgLite); 10016 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10017 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10018 } else if (!onSd && !onInt) { 10019 // Override install location with flags 10020 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10021 // Set the flag to install on external media. 10022 installFlags |= PackageManager.INSTALL_EXTERNAL; 10023 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10024 } else { 10025 // Make sure the flag for installing on external 10026 // media is unset 10027 installFlags |= PackageManager.INSTALL_INTERNAL; 10028 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10029 } 10030 } 10031 } 10032 } 10033 10034 final InstallArgs args = createInstallArgs(this); 10035 mArgs = args; 10036 10037 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10038 /* 10039 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10040 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10041 */ 10042 int userIdentifier = getUser().getIdentifier(); 10043 if (userIdentifier == UserHandle.USER_ALL 10044 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10045 userIdentifier = UserHandle.USER_OWNER; 10046 } 10047 10048 /* 10049 * Determine if we have any installed package verifiers. If we 10050 * do, then we'll defer to them to verify the packages. 10051 */ 10052 final int requiredUid = mRequiredVerifierPackage == null ? -1 10053 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10054 if (!origin.existing && requiredUid != -1 10055 && isVerificationEnabled(userIdentifier, installFlags)) { 10056 final Intent verification = new Intent( 10057 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10058 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10059 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10060 PACKAGE_MIME_TYPE); 10061 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10062 10063 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10064 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10065 0 /* TODO: Which userId? */); 10066 10067 if (DEBUG_VERIFY) { 10068 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10069 + verification.toString() + " with " + pkgLite.verifiers.length 10070 + " optional verifiers"); 10071 } 10072 10073 final int verificationId = mPendingVerificationToken++; 10074 10075 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10076 10077 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10078 installerPackageName); 10079 10080 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10081 installFlags); 10082 10083 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10084 pkgLite.packageName); 10085 10086 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10087 pkgLite.versionCode); 10088 10089 if (verificationParams != null) { 10090 if (verificationParams.getVerificationURI() != null) { 10091 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10092 verificationParams.getVerificationURI()); 10093 } 10094 if (verificationParams.getOriginatingURI() != null) { 10095 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10096 verificationParams.getOriginatingURI()); 10097 } 10098 if (verificationParams.getReferrer() != null) { 10099 verification.putExtra(Intent.EXTRA_REFERRER, 10100 verificationParams.getReferrer()); 10101 } 10102 if (verificationParams.getOriginatingUid() >= 0) { 10103 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10104 verificationParams.getOriginatingUid()); 10105 } 10106 if (verificationParams.getInstallerUid() >= 0) { 10107 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10108 verificationParams.getInstallerUid()); 10109 } 10110 } 10111 10112 final PackageVerificationState verificationState = new PackageVerificationState( 10113 requiredUid, args); 10114 10115 mPendingVerification.append(verificationId, verificationState); 10116 10117 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10118 receivers, verificationState); 10119 10120 /* 10121 * If any sufficient verifiers were listed in the package 10122 * manifest, attempt to ask them. 10123 */ 10124 if (sufficientVerifiers != null) { 10125 final int N = sufficientVerifiers.size(); 10126 if (N == 0) { 10127 Slog.i(TAG, "Additional verifiers required, but none installed."); 10128 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10129 } else { 10130 for (int i = 0; i < N; i++) { 10131 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10132 10133 final Intent sufficientIntent = new Intent(verification); 10134 sufficientIntent.setComponent(verifierComponent); 10135 10136 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10137 } 10138 } 10139 } 10140 10141 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10142 mRequiredVerifierPackage, receivers); 10143 if (ret == PackageManager.INSTALL_SUCCEEDED 10144 && mRequiredVerifierPackage != null) { 10145 /* 10146 * Send the intent to the required verification agent, 10147 * but only start the verification timeout after the 10148 * target BroadcastReceivers have run. 10149 */ 10150 verification.setComponent(requiredVerifierComponent); 10151 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10152 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10153 new BroadcastReceiver() { 10154 @Override 10155 public void onReceive(Context context, Intent intent) { 10156 final Message msg = mHandler 10157 .obtainMessage(CHECK_PENDING_VERIFICATION); 10158 msg.arg1 = verificationId; 10159 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10160 } 10161 }, null, 0, null, null); 10162 10163 /* 10164 * We don't want the copy to proceed until verification 10165 * succeeds, so null out this field. 10166 */ 10167 mArgs = null; 10168 } 10169 } else { 10170 /* 10171 * No package verification is enabled, so immediately start 10172 * the remote call to initiate copy using temporary file. 10173 */ 10174 ret = args.copyApk(mContainerService, true); 10175 } 10176 } 10177 10178 mRet = ret; 10179 } 10180 10181 @Override 10182 void handleReturnCode() { 10183 // If mArgs is null, then MCS couldn't be reached. When it 10184 // reconnects, it will try again to install. At that point, this 10185 // will succeed. 10186 if (mArgs != null) { 10187 processPendingInstall(mArgs, mRet); 10188 } 10189 } 10190 10191 @Override 10192 void handleServiceError() { 10193 mArgs = createInstallArgs(this); 10194 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10195 } 10196 10197 public boolean isForwardLocked() { 10198 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10199 } 10200 } 10201 10202 /** 10203 * Used during creation of InstallArgs 10204 * 10205 * @param installFlags package installation flags 10206 * @return true if should be installed on external storage 10207 */ 10208 private static boolean installOnExternalAsec(int installFlags) { 10209 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10210 return false; 10211 } 10212 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10213 return true; 10214 } 10215 return false; 10216 } 10217 10218 /** 10219 * Used during creation of InstallArgs 10220 * 10221 * @param installFlags package installation flags 10222 * @return true if should be installed as forward locked 10223 */ 10224 private static boolean installForwardLocked(int installFlags) { 10225 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10226 } 10227 10228 private InstallArgs createInstallArgs(InstallParams params) { 10229 if (params.move != null) { 10230 return new MoveInstallArgs(params); 10231 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10232 return new AsecInstallArgs(params); 10233 } else { 10234 return new FileInstallArgs(params); 10235 } 10236 } 10237 10238 /** 10239 * Create args that describe an existing installed package. Typically used 10240 * when cleaning up old installs, or used as a move source. 10241 */ 10242 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10243 String resourcePath, String[] instructionSets) { 10244 final boolean isInAsec; 10245 if (installOnExternalAsec(installFlags)) { 10246 /* Apps on SD card are always in ASEC containers. */ 10247 isInAsec = true; 10248 } else if (installForwardLocked(installFlags) 10249 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10250 /* 10251 * Forward-locked apps are only in ASEC containers if they're the 10252 * new style 10253 */ 10254 isInAsec = true; 10255 } else { 10256 isInAsec = false; 10257 } 10258 10259 if (isInAsec) { 10260 return new AsecInstallArgs(codePath, instructionSets, 10261 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10262 } else { 10263 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10264 } 10265 } 10266 10267 static abstract class InstallArgs { 10268 /** @see InstallParams#origin */ 10269 final OriginInfo origin; 10270 /** @see InstallParams#move */ 10271 final MoveInfo move; 10272 10273 final IPackageInstallObserver2 observer; 10274 // Always refers to PackageManager flags only 10275 final int installFlags; 10276 final String installerPackageName; 10277 final String volumeUuid; 10278 final ManifestDigest manifestDigest; 10279 final UserHandle user; 10280 final String abiOverride; 10281 10282 // The list of instruction sets supported by this app. This is currently 10283 // only used during the rmdex() phase to clean up resources. We can get rid of this 10284 // if we move dex files under the common app path. 10285 /* nullable */ String[] instructionSets; 10286 10287 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10288 int installFlags, String installerPackageName, String volumeUuid, 10289 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10290 String abiOverride) { 10291 this.origin = origin; 10292 this.move = move; 10293 this.installFlags = installFlags; 10294 this.observer = observer; 10295 this.installerPackageName = installerPackageName; 10296 this.volumeUuid = volumeUuid; 10297 this.manifestDigest = manifestDigest; 10298 this.user = user; 10299 this.instructionSets = instructionSets; 10300 this.abiOverride = abiOverride; 10301 } 10302 10303 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10304 abstract int doPreInstall(int status); 10305 10306 /** 10307 * Rename package into final resting place. All paths on the given 10308 * scanned package should be updated to reflect the rename. 10309 */ 10310 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10311 abstract int doPostInstall(int status, int uid); 10312 10313 /** @see PackageSettingBase#codePathString */ 10314 abstract String getCodePath(); 10315 /** @see PackageSettingBase#resourcePathString */ 10316 abstract String getResourcePath(); 10317 10318 // Need installer lock especially for dex file removal. 10319 abstract void cleanUpResourcesLI(); 10320 abstract boolean doPostDeleteLI(boolean delete); 10321 10322 /** 10323 * Called before the source arguments are copied. This is used mostly 10324 * for MoveParams when it needs to read the source file to put it in the 10325 * destination. 10326 */ 10327 int doPreCopy() { 10328 return PackageManager.INSTALL_SUCCEEDED; 10329 } 10330 10331 /** 10332 * Called after the source arguments are copied. This is used mostly for 10333 * MoveParams when it needs to read the source file to put it in the 10334 * destination. 10335 * 10336 * @return 10337 */ 10338 int doPostCopy(int uid) { 10339 return PackageManager.INSTALL_SUCCEEDED; 10340 } 10341 10342 protected boolean isFwdLocked() { 10343 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10344 } 10345 10346 protected boolean isExternalAsec() { 10347 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10348 } 10349 10350 UserHandle getUser() { 10351 return user; 10352 } 10353 } 10354 10355 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10356 if (!allCodePaths.isEmpty()) { 10357 if (instructionSets == null) { 10358 throw new IllegalStateException("instructionSet == null"); 10359 } 10360 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10361 for (String codePath : allCodePaths) { 10362 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10363 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10364 if (retCode < 0) { 10365 Slog.w(TAG, "Couldn't remove dex file for package: " 10366 + " at location " + codePath + ", retcode=" + retCode); 10367 // we don't consider this to be a failure of the core package deletion 10368 } 10369 } 10370 } 10371 } 10372 } 10373 10374 /** 10375 * Logic to handle installation of non-ASEC applications, including copying 10376 * and renaming logic. 10377 */ 10378 class FileInstallArgs extends InstallArgs { 10379 private File codeFile; 10380 private File resourceFile; 10381 10382 // Example topology: 10383 // /data/app/com.example/base.apk 10384 // /data/app/com.example/split_foo.apk 10385 // /data/app/com.example/lib/arm/libfoo.so 10386 // /data/app/com.example/lib/arm64/libfoo.so 10387 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10388 10389 /** New install */ 10390 FileInstallArgs(InstallParams params) { 10391 super(params.origin, params.move, params.observer, params.installFlags, 10392 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10393 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10394 if (isFwdLocked()) { 10395 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10396 } 10397 } 10398 10399 /** Existing install */ 10400 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10401 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10402 null); 10403 this.codeFile = (codePath != null) ? new File(codePath) : null; 10404 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10405 } 10406 10407 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10408 if (origin.staged) { 10409 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10410 codeFile = origin.file; 10411 resourceFile = origin.file; 10412 return PackageManager.INSTALL_SUCCEEDED; 10413 } 10414 10415 try { 10416 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10417 codeFile = tempDir; 10418 resourceFile = tempDir; 10419 } catch (IOException e) { 10420 Slog.w(TAG, "Failed to create copy file: " + e); 10421 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10422 } 10423 10424 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10425 @Override 10426 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10427 if (!FileUtils.isValidExtFilename(name)) { 10428 throw new IllegalArgumentException("Invalid filename: " + name); 10429 } 10430 try { 10431 final File file = new File(codeFile, name); 10432 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10433 O_RDWR | O_CREAT, 0644); 10434 Os.chmod(file.getAbsolutePath(), 0644); 10435 return new ParcelFileDescriptor(fd); 10436 } catch (ErrnoException e) { 10437 throw new RemoteException("Failed to open: " + e.getMessage()); 10438 } 10439 } 10440 }; 10441 10442 int ret = PackageManager.INSTALL_SUCCEEDED; 10443 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10444 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10445 Slog.e(TAG, "Failed to copy package"); 10446 return ret; 10447 } 10448 10449 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10450 NativeLibraryHelper.Handle handle = null; 10451 try { 10452 handle = NativeLibraryHelper.Handle.create(codeFile); 10453 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10454 abiOverride); 10455 } catch (IOException e) { 10456 Slog.e(TAG, "Copying native libraries failed", e); 10457 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10458 } finally { 10459 IoUtils.closeQuietly(handle); 10460 } 10461 10462 return ret; 10463 } 10464 10465 int doPreInstall(int status) { 10466 if (status != PackageManager.INSTALL_SUCCEEDED) { 10467 cleanUp(); 10468 } 10469 return status; 10470 } 10471 10472 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10473 if (status != PackageManager.INSTALL_SUCCEEDED) { 10474 cleanUp(); 10475 return false; 10476 } 10477 10478 final File targetDir = codeFile.getParentFile(); 10479 final File beforeCodeFile = codeFile; 10480 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10481 10482 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10483 try { 10484 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10485 } catch (ErrnoException e) { 10486 Slog.w(TAG, "Failed to rename", e); 10487 return false; 10488 } 10489 10490 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10491 Slog.w(TAG, "Failed to restorecon"); 10492 return false; 10493 } 10494 10495 // Reflect the rename internally 10496 codeFile = afterCodeFile; 10497 resourceFile = afterCodeFile; 10498 10499 // Reflect the rename in scanned details 10500 pkg.codePath = afterCodeFile.getAbsolutePath(); 10501 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10502 pkg.baseCodePath); 10503 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10504 pkg.splitCodePaths); 10505 10506 // Reflect the rename in app info 10507 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10508 pkg.applicationInfo.setCodePath(pkg.codePath); 10509 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10510 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10511 pkg.applicationInfo.setResourcePath(pkg.codePath); 10512 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10513 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10514 10515 return true; 10516 } 10517 10518 int doPostInstall(int status, int uid) { 10519 if (status != PackageManager.INSTALL_SUCCEEDED) { 10520 cleanUp(); 10521 } 10522 return status; 10523 } 10524 10525 @Override 10526 String getCodePath() { 10527 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10528 } 10529 10530 @Override 10531 String getResourcePath() { 10532 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10533 } 10534 10535 private boolean cleanUp() { 10536 if (codeFile == null || !codeFile.exists()) { 10537 return false; 10538 } 10539 10540 if (codeFile.isDirectory()) { 10541 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10542 } else { 10543 codeFile.delete(); 10544 } 10545 10546 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10547 resourceFile.delete(); 10548 } 10549 10550 return true; 10551 } 10552 10553 void cleanUpResourcesLI() { 10554 // Try enumerating all code paths before deleting 10555 List<String> allCodePaths = Collections.EMPTY_LIST; 10556 if (codeFile != null && codeFile.exists()) { 10557 try { 10558 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10559 allCodePaths = pkg.getAllCodePaths(); 10560 } catch (PackageParserException e) { 10561 // Ignored; we tried our best 10562 } 10563 } 10564 10565 cleanUp(); 10566 removeDexFiles(allCodePaths, instructionSets); 10567 } 10568 10569 boolean doPostDeleteLI(boolean delete) { 10570 // XXX err, shouldn't we respect the delete flag? 10571 cleanUpResourcesLI(); 10572 return true; 10573 } 10574 } 10575 10576 private boolean isAsecExternal(String cid) { 10577 final String asecPath = PackageHelper.getSdFilesystem(cid); 10578 return !asecPath.startsWith(mAsecInternalPath); 10579 } 10580 10581 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10582 PackageManagerException { 10583 if (copyRet < 0) { 10584 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10585 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10586 throw new PackageManagerException(copyRet, message); 10587 } 10588 } 10589 } 10590 10591 /** 10592 * Extract the MountService "container ID" from the full code path of an 10593 * .apk. 10594 */ 10595 static String cidFromCodePath(String fullCodePath) { 10596 int eidx = fullCodePath.lastIndexOf("/"); 10597 String subStr1 = fullCodePath.substring(0, eidx); 10598 int sidx = subStr1.lastIndexOf("/"); 10599 return subStr1.substring(sidx+1, eidx); 10600 } 10601 10602 /** 10603 * Logic to handle installation of ASEC applications, including copying and 10604 * renaming logic. 10605 */ 10606 class AsecInstallArgs extends InstallArgs { 10607 static final String RES_FILE_NAME = "pkg.apk"; 10608 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10609 10610 String cid; 10611 String packagePath; 10612 String resourcePath; 10613 10614 /** New install */ 10615 AsecInstallArgs(InstallParams params) { 10616 super(params.origin, params.move, params.observer, params.installFlags, 10617 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10618 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10619 } 10620 10621 /** Existing install */ 10622 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10623 boolean isExternal, boolean isForwardLocked) { 10624 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10625 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10626 instructionSets, null); 10627 // Hackily pretend we're still looking at a full code path 10628 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10629 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10630 } 10631 10632 // Extract cid from fullCodePath 10633 int eidx = fullCodePath.lastIndexOf("/"); 10634 String subStr1 = fullCodePath.substring(0, eidx); 10635 int sidx = subStr1.lastIndexOf("/"); 10636 cid = subStr1.substring(sidx+1, eidx); 10637 setMountPath(subStr1); 10638 } 10639 10640 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10641 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10642 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10643 instructionSets, null); 10644 this.cid = cid; 10645 setMountPath(PackageHelper.getSdDir(cid)); 10646 } 10647 10648 void createCopyFile() { 10649 cid = mInstallerService.allocateExternalStageCidLegacy(); 10650 } 10651 10652 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10653 if (origin.staged) { 10654 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10655 cid = origin.cid; 10656 setMountPath(PackageHelper.getSdDir(cid)); 10657 return PackageManager.INSTALL_SUCCEEDED; 10658 } 10659 10660 if (temp) { 10661 createCopyFile(); 10662 } else { 10663 /* 10664 * Pre-emptively destroy the container since it's destroyed if 10665 * copying fails due to it existing anyway. 10666 */ 10667 PackageHelper.destroySdDir(cid); 10668 } 10669 10670 final String newMountPath = imcs.copyPackageToContainer( 10671 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10672 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10673 10674 if (newMountPath != null) { 10675 setMountPath(newMountPath); 10676 return PackageManager.INSTALL_SUCCEEDED; 10677 } else { 10678 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10679 } 10680 } 10681 10682 @Override 10683 String getCodePath() { 10684 return packagePath; 10685 } 10686 10687 @Override 10688 String getResourcePath() { 10689 return resourcePath; 10690 } 10691 10692 int doPreInstall(int status) { 10693 if (status != PackageManager.INSTALL_SUCCEEDED) { 10694 // Destroy container 10695 PackageHelper.destroySdDir(cid); 10696 } else { 10697 boolean mounted = PackageHelper.isContainerMounted(cid); 10698 if (!mounted) { 10699 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10700 Process.SYSTEM_UID); 10701 if (newMountPath != null) { 10702 setMountPath(newMountPath); 10703 } else { 10704 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10705 } 10706 } 10707 } 10708 return status; 10709 } 10710 10711 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10712 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10713 String newMountPath = null; 10714 if (PackageHelper.isContainerMounted(cid)) { 10715 // Unmount the container 10716 if (!PackageHelper.unMountSdDir(cid)) { 10717 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10718 return false; 10719 } 10720 } 10721 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10722 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10723 " which might be stale. Will try to clean up."); 10724 // Clean up the stale container and proceed to recreate. 10725 if (!PackageHelper.destroySdDir(newCacheId)) { 10726 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10727 return false; 10728 } 10729 // Successfully cleaned up stale container. Try to rename again. 10730 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10731 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10732 + " inspite of cleaning it up."); 10733 return false; 10734 } 10735 } 10736 if (!PackageHelper.isContainerMounted(newCacheId)) { 10737 Slog.w(TAG, "Mounting container " + newCacheId); 10738 newMountPath = PackageHelper.mountSdDir(newCacheId, 10739 getEncryptKey(), Process.SYSTEM_UID); 10740 } else { 10741 newMountPath = PackageHelper.getSdDir(newCacheId); 10742 } 10743 if (newMountPath == null) { 10744 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10745 return false; 10746 } 10747 Log.i(TAG, "Succesfully renamed " + cid + 10748 " to " + newCacheId + 10749 " at new path: " + newMountPath); 10750 cid = newCacheId; 10751 10752 final File beforeCodeFile = new File(packagePath); 10753 setMountPath(newMountPath); 10754 final File afterCodeFile = new File(packagePath); 10755 10756 // Reflect the rename in scanned details 10757 pkg.codePath = afterCodeFile.getAbsolutePath(); 10758 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10759 pkg.baseCodePath); 10760 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10761 pkg.splitCodePaths); 10762 10763 // Reflect the rename in app info 10764 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10765 pkg.applicationInfo.setCodePath(pkg.codePath); 10766 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10767 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10768 pkg.applicationInfo.setResourcePath(pkg.codePath); 10769 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10770 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10771 10772 return true; 10773 } 10774 10775 private void setMountPath(String mountPath) { 10776 final File mountFile = new File(mountPath); 10777 10778 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10779 if (monolithicFile.exists()) { 10780 packagePath = monolithicFile.getAbsolutePath(); 10781 if (isFwdLocked()) { 10782 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10783 } else { 10784 resourcePath = packagePath; 10785 } 10786 } else { 10787 packagePath = mountFile.getAbsolutePath(); 10788 resourcePath = packagePath; 10789 } 10790 } 10791 10792 int doPostInstall(int status, int uid) { 10793 if (status != PackageManager.INSTALL_SUCCEEDED) { 10794 cleanUp(); 10795 } else { 10796 final int groupOwner; 10797 final String protectedFile; 10798 if (isFwdLocked()) { 10799 groupOwner = UserHandle.getSharedAppGid(uid); 10800 protectedFile = RES_FILE_NAME; 10801 } else { 10802 groupOwner = -1; 10803 protectedFile = null; 10804 } 10805 10806 if (uid < Process.FIRST_APPLICATION_UID 10807 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10808 Slog.e(TAG, "Failed to finalize " + cid); 10809 PackageHelper.destroySdDir(cid); 10810 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10811 } 10812 10813 boolean mounted = PackageHelper.isContainerMounted(cid); 10814 if (!mounted) { 10815 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10816 } 10817 } 10818 return status; 10819 } 10820 10821 private void cleanUp() { 10822 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10823 10824 // Destroy secure container 10825 PackageHelper.destroySdDir(cid); 10826 } 10827 10828 private List<String> getAllCodePaths() { 10829 final File codeFile = new File(getCodePath()); 10830 if (codeFile != null && codeFile.exists()) { 10831 try { 10832 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10833 return pkg.getAllCodePaths(); 10834 } catch (PackageParserException e) { 10835 // Ignored; we tried our best 10836 } 10837 } 10838 return Collections.EMPTY_LIST; 10839 } 10840 10841 void cleanUpResourcesLI() { 10842 // Enumerate all code paths before deleting 10843 cleanUpResourcesLI(getAllCodePaths()); 10844 } 10845 10846 private void cleanUpResourcesLI(List<String> allCodePaths) { 10847 cleanUp(); 10848 removeDexFiles(allCodePaths, instructionSets); 10849 } 10850 10851 String getPackageName() { 10852 return getAsecPackageName(cid); 10853 } 10854 10855 boolean doPostDeleteLI(boolean delete) { 10856 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10857 final List<String> allCodePaths = getAllCodePaths(); 10858 boolean mounted = PackageHelper.isContainerMounted(cid); 10859 if (mounted) { 10860 // Unmount first 10861 if (PackageHelper.unMountSdDir(cid)) { 10862 mounted = false; 10863 } 10864 } 10865 if (!mounted && delete) { 10866 cleanUpResourcesLI(allCodePaths); 10867 } 10868 return !mounted; 10869 } 10870 10871 @Override 10872 int doPreCopy() { 10873 if (isFwdLocked()) { 10874 if (!PackageHelper.fixSdPermissions(cid, 10875 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10876 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10877 } 10878 } 10879 10880 return PackageManager.INSTALL_SUCCEEDED; 10881 } 10882 10883 @Override 10884 int doPostCopy(int uid) { 10885 if (isFwdLocked()) { 10886 if (uid < Process.FIRST_APPLICATION_UID 10887 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10888 RES_FILE_NAME)) { 10889 Slog.e(TAG, "Failed to finalize " + cid); 10890 PackageHelper.destroySdDir(cid); 10891 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10892 } 10893 } 10894 10895 return PackageManager.INSTALL_SUCCEEDED; 10896 } 10897 } 10898 10899 /** 10900 * Logic to handle movement of existing installed applications. 10901 */ 10902 class MoveInstallArgs extends InstallArgs { 10903 private File codeFile; 10904 private File resourceFile; 10905 10906 /** New install */ 10907 MoveInstallArgs(InstallParams params) { 10908 super(params.origin, params.move, params.observer, params.installFlags, 10909 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10910 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10911 } 10912 10913 int copyApk(IMediaContainerService imcs, boolean temp) { 10914 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10915 + move.fromUuid + " to " + move.toUuid); 10916 synchronized (mInstaller) { 10917 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10918 move.dataAppName, move.appId, move.seinfo) != 0) { 10919 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10920 } 10921 } 10922 10923 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10924 resourceFile = codeFile; 10925 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10926 10927 return PackageManager.INSTALL_SUCCEEDED; 10928 } 10929 10930 int doPreInstall(int status) { 10931 if (status != PackageManager.INSTALL_SUCCEEDED) { 10932 cleanUp(); 10933 } 10934 return status; 10935 } 10936 10937 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10938 if (status != PackageManager.INSTALL_SUCCEEDED) { 10939 cleanUp(); 10940 return false; 10941 } 10942 10943 // Reflect the move in app info 10944 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10945 pkg.applicationInfo.setCodePath(pkg.codePath); 10946 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10947 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10948 pkg.applicationInfo.setResourcePath(pkg.codePath); 10949 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10950 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10951 10952 return true; 10953 } 10954 10955 int doPostInstall(int status, int uid) { 10956 if (status != PackageManager.INSTALL_SUCCEEDED) { 10957 cleanUp(); 10958 } 10959 return status; 10960 } 10961 10962 @Override 10963 String getCodePath() { 10964 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10965 } 10966 10967 @Override 10968 String getResourcePath() { 10969 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10970 } 10971 10972 private boolean cleanUp() { 10973 if (codeFile == null || !codeFile.exists()) { 10974 return false; 10975 } 10976 10977 if (codeFile.isDirectory()) { 10978 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10979 } else { 10980 codeFile.delete(); 10981 } 10982 10983 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10984 resourceFile.delete(); 10985 } 10986 10987 return true; 10988 } 10989 10990 void cleanUpResourcesLI() { 10991 cleanUp(); 10992 } 10993 10994 boolean doPostDeleteLI(boolean delete) { 10995 // XXX err, shouldn't we respect the delete flag? 10996 cleanUpResourcesLI(); 10997 return true; 10998 } 10999 } 11000 11001 static String getAsecPackageName(String packageCid) { 11002 int idx = packageCid.lastIndexOf("-"); 11003 if (idx == -1) { 11004 return packageCid; 11005 } 11006 return packageCid.substring(0, idx); 11007 } 11008 11009 // Utility method used to create code paths based on package name and available index. 11010 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11011 String idxStr = ""; 11012 int idx = 1; 11013 // Fall back to default value of idx=1 if prefix is not 11014 // part of oldCodePath 11015 if (oldCodePath != null) { 11016 String subStr = oldCodePath; 11017 // Drop the suffix right away 11018 if (suffix != null && subStr.endsWith(suffix)) { 11019 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11020 } 11021 // If oldCodePath already contains prefix find out the 11022 // ending index to either increment or decrement. 11023 int sidx = subStr.lastIndexOf(prefix); 11024 if (sidx != -1) { 11025 subStr = subStr.substring(sidx + prefix.length()); 11026 if (subStr != null) { 11027 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11028 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11029 } 11030 try { 11031 idx = Integer.parseInt(subStr); 11032 if (idx <= 1) { 11033 idx++; 11034 } else { 11035 idx--; 11036 } 11037 } catch(NumberFormatException e) { 11038 } 11039 } 11040 } 11041 } 11042 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11043 return prefix + idxStr; 11044 } 11045 11046 private File getNextCodePath(File targetDir, String packageName) { 11047 int suffix = 1; 11048 File result; 11049 do { 11050 result = new File(targetDir, packageName + "-" + suffix); 11051 suffix++; 11052 } while (result.exists()); 11053 return result; 11054 } 11055 11056 // Utility method that returns the relative package path with respect 11057 // to the installation directory. Like say for /data/data/com.test-1.apk 11058 // string com.test-1 is returned. 11059 static String deriveCodePathName(String codePath) { 11060 if (codePath == null) { 11061 return null; 11062 } 11063 final File codeFile = new File(codePath); 11064 final String name = codeFile.getName(); 11065 if (codeFile.isDirectory()) { 11066 return name; 11067 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11068 final int lastDot = name.lastIndexOf('.'); 11069 return name.substring(0, lastDot); 11070 } else { 11071 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11072 return null; 11073 } 11074 } 11075 11076 class PackageInstalledInfo { 11077 String name; 11078 int uid; 11079 // The set of users that originally had this package installed. 11080 int[] origUsers; 11081 // The set of users that now have this package installed. 11082 int[] newUsers; 11083 PackageParser.Package pkg; 11084 int returnCode; 11085 String returnMsg; 11086 PackageRemovedInfo removedInfo; 11087 11088 public void setError(int code, String msg) { 11089 returnCode = code; 11090 returnMsg = msg; 11091 Slog.w(TAG, msg); 11092 } 11093 11094 public void setError(String msg, PackageParserException e) { 11095 returnCode = e.error; 11096 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11097 Slog.w(TAG, msg, e); 11098 } 11099 11100 public void setError(String msg, PackageManagerException e) { 11101 returnCode = e.error; 11102 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11103 Slog.w(TAG, msg, e); 11104 } 11105 11106 // In some error cases we want to convey more info back to the observer 11107 String origPackage; 11108 String origPermission; 11109 } 11110 11111 /* 11112 * Install a non-existing package. 11113 */ 11114 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11115 UserHandle user, String installerPackageName, String volumeUuid, 11116 PackageInstalledInfo res) { 11117 // Remember this for later, in case we need to rollback this install 11118 String pkgName = pkg.packageName; 11119 11120 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11121 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11122 UserHandle.USER_OWNER).exists(); 11123 synchronized(mPackages) { 11124 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11125 // A package with the same name is already installed, though 11126 // it has been renamed to an older name. The package we 11127 // are trying to install should be installed as an update to 11128 // the existing one, but that has not been requested, so bail. 11129 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11130 + " without first uninstalling package running as " 11131 + mSettings.mRenamedPackages.get(pkgName)); 11132 return; 11133 } 11134 if (mPackages.containsKey(pkgName)) { 11135 // Don't allow installation over an existing package with the same name. 11136 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11137 + " without first uninstalling."); 11138 return; 11139 } 11140 } 11141 11142 try { 11143 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11144 System.currentTimeMillis(), user); 11145 11146 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11147 // delete the partially installed application. the data directory will have to be 11148 // restored if it was already existing 11149 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11150 // remove package from internal structures. Note that we want deletePackageX to 11151 // delete the package data and cache directories that it created in 11152 // scanPackageLocked, unless those directories existed before we even tried to 11153 // install. 11154 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11155 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11156 res.removedInfo, true); 11157 } 11158 11159 } catch (PackageManagerException e) { 11160 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11161 } 11162 } 11163 11164 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11165 // Upgrade keysets are being used. Determine if new package has a superset of the 11166 // required keys. 11167 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11168 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11169 for (int i = 0; i < upgradeKeySets.length; i++) { 11170 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11171 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11172 return true; 11173 } 11174 } 11175 return false; 11176 } 11177 11178 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11179 UserHandle user, String installerPackageName, String volumeUuid, 11180 PackageInstalledInfo res) { 11181 final PackageParser.Package oldPackage; 11182 final String pkgName = pkg.packageName; 11183 final int[] allUsers; 11184 final boolean[] perUserInstalled; 11185 final boolean weFroze; 11186 11187 // First find the old package info and check signatures 11188 synchronized(mPackages) { 11189 oldPackage = mPackages.get(pkgName); 11190 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11191 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11192 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11193 // default to original signature matching 11194 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11195 != PackageManager.SIGNATURE_MATCH) { 11196 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11197 "New package has a different signature: " + pkgName); 11198 return; 11199 } 11200 } else { 11201 if(!checkUpgradeKeySetLP(ps, pkg)) { 11202 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11203 "New package not signed by keys specified by upgrade-keysets: " 11204 + pkgName); 11205 return; 11206 } 11207 } 11208 11209 // In case of rollback, remember per-user/profile install state 11210 allUsers = sUserManager.getUserIds(); 11211 perUserInstalled = new boolean[allUsers.length]; 11212 for (int i = 0; i < allUsers.length; i++) { 11213 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11214 } 11215 11216 // Mark the app as frozen to prevent launching during the upgrade 11217 // process, and then kill all running instances 11218 if (!ps.frozen) { 11219 ps.frozen = true; 11220 weFroze = true; 11221 } else { 11222 weFroze = false; 11223 } 11224 } 11225 11226 // Now that we're guarded by frozen state, kill app during upgrade 11227 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11228 11229 try { 11230 boolean sysPkg = (isSystemApp(oldPackage)); 11231 if (sysPkg) { 11232 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11233 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11234 } else { 11235 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11236 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11237 } 11238 } finally { 11239 // Regardless of success or failure of upgrade steps above, always 11240 // unfreeze the package if we froze it 11241 if (weFroze) { 11242 unfreezePackage(pkgName); 11243 } 11244 } 11245 } 11246 11247 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11248 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11249 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11250 String volumeUuid, PackageInstalledInfo res) { 11251 String pkgName = deletedPackage.packageName; 11252 boolean deletedPkg = true; 11253 boolean updatedSettings = false; 11254 11255 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11256 + deletedPackage); 11257 long origUpdateTime; 11258 if (pkg.mExtras != null) { 11259 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11260 } else { 11261 origUpdateTime = 0; 11262 } 11263 11264 // First delete the existing package while retaining the data directory 11265 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11266 res.removedInfo, true)) { 11267 // If the existing package wasn't successfully deleted 11268 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11269 deletedPkg = false; 11270 } else { 11271 // Successfully deleted the old package; proceed with replace. 11272 11273 // If deleted package lived in a container, give users a chance to 11274 // relinquish resources before killing. 11275 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11276 if (DEBUG_INSTALL) { 11277 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11278 } 11279 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11280 final ArrayList<String> pkgList = new ArrayList<String>(1); 11281 pkgList.add(deletedPackage.applicationInfo.packageName); 11282 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11283 } 11284 11285 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11286 try { 11287 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11288 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11289 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11290 perUserInstalled, res, user); 11291 updatedSettings = true; 11292 } catch (PackageManagerException e) { 11293 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11294 } 11295 } 11296 11297 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11298 // remove package from internal structures. Note that we want deletePackageX to 11299 // delete the package data and cache directories that it created in 11300 // scanPackageLocked, unless those directories existed before we even tried to 11301 // install. 11302 if(updatedSettings) { 11303 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11304 deletePackageLI( 11305 pkgName, null, true, allUsers, perUserInstalled, 11306 PackageManager.DELETE_KEEP_DATA, 11307 res.removedInfo, true); 11308 } 11309 // Since we failed to install the new package we need to restore the old 11310 // package that we deleted. 11311 if (deletedPkg) { 11312 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11313 File restoreFile = new File(deletedPackage.codePath); 11314 // Parse old package 11315 boolean oldExternal = isExternal(deletedPackage); 11316 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11317 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11318 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11319 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11320 try { 11321 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11322 } catch (PackageManagerException e) { 11323 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11324 + e.getMessage()); 11325 return; 11326 } 11327 // Restore of old package succeeded. Update permissions. 11328 // writer 11329 synchronized (mPackages) { 11330 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11331 UPDATE_PERMISSIONS_ALL); 11332 // can downgrade to reader 11333 mSettings.writeLPr(); 11334 } 11335 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11336 } 11337 } 11338 } 11339 11340 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11341 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11342 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11343 String volumeUuid, PackageInstalledInfo res) { 11344 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11345 + ", old=" + deletedPackage); 11346 boolean disabledSystem = false; 11347 boolean updatedSettings = false; 11348 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11349 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11350 != 0) { 11351 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11352 } 11353 String packageName = deletedPackage.packageName; 11354 if (packageName == null) { 11355 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11356 "Attempt to delete null packageName."); 11357 return; 11358 } 11359 PackageParser.Package oldPkg; 11360 PackageSetting oldPkgSetting; 11361 // reader 11362 synchronized (mPackages) { 11363 oldPkg = mPackages.get(packageName); 11364 oldPkgSetting = mSettings.mPackages.get(packageName); 11365 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11366 (oldPkgSetting == null)) { 11367 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11368 "Couldn't find package:" + packageName + " information"); 11369 return; 11370 } 11371 } 11372 11373 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11374 res.removedInfo.removedPackage = packageName; 11375 // Remove existing system package 11376 removePackageLI(oldPkgSetting, true); 11377 // writer 11378 synchronized (mPackages) { 11379 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11380 if (!disabledSystem && deletedPackage != null) { 11381 // We didn't need to disable the .apk as a current system package, 11382 // which means we are replacing another update that is already 11383 // installed. We need to make sure to delete the older one's .apk. 11384 res.removedInfo.args = createInstallArgsForExisting(0, 11385 deletedPackage.applicationInfo.getCodePath(), 11386 deletedPackage.applicationInfo.getResourcePath(), 11387 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11388 } else { 11389 res.removedInfo.args = null; 11390 } 11391 } 11392 11393 // Successfully disabled the old package. Now proceed with re-installation 11394 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11395 11396 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11397 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11398 11399 PackageParser.Package newPackage = null; 11400 try { 11401 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11402 if (newPackage.mExtras != null) { 11403 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11404 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11405 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11406 11407 // is the update attempting to change shared user? that isn't going to work... 11408 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11409 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11410 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11411 + " to " + newPkgSetting.sharedUser); 11412 updatedSettings = true; 11413 } 11414 } 11415 11416 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11417 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11418 perUserInstalled, res, user); 11419 updatedSettings = true; 11420 } 11421 11422 } catch (PackageManagerException e) { 11423 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11424 } 11425 11426 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11427 // Re installation failed. Restore old information 11428 // Remove new pkg information 11429 if (newPackage != null) { 11430 removeInstalledPackageLI(newPackage, true); 11431 } 11432 // Add back the old system package 11433 try { 11434 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11435 } catch (PackageManagerException e) { 11436 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11437 } 11438 // Restore the old system information in Settings 11439 synchronized (mPackages) { 11440 if (disabledSystem) { 11441 mSettings.enableSystemPackageLPw(packageName); 11442 } 11443 if (updatedSettings) { 11444 mSettings.setInstallerPackageName(packageName, 11445 oldPkgSetting.installerPackageName); 11446 } 11447 mSettings.writeLPr(); 11448 } 11449 } 11450 } 11451 11452 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11453 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11454 UserHandle user) { 11455 String pkgName = newPackage.packageName; 11456 synchronized (mPackages) { 11457 //write settings. the installStatus will be incomplete at this stage. 11458 //note that the new package setting would have already been 11459 //added to mPackages. It hasn't been persisted yet. 11460 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11461 mSettings.writeLPr(); 11462 } 11463 11464 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11465 11466 synchronized (mPackages) { 11467 updatePermissionsLPw(newPackage.packageName, newPackage, 11468 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11469 ? UPDATE_PERMISSIONS_ALL : 0)); 11470 // For system-bundled packages, we assume that installing an upgraded version 11471 // of the package implies that the user actually wants to run that new code, 11472 // so we enable the package. 11473 PackageSetting ps = mSettings.mPackages.get(pkgName); 11474 if (ps != null) { 11475 if (isSystemApp(newPackage)) { 11476 // NB: implicit assumption that system package upgrades apply to all users 11477 if (DEBUG_INSTALL) { 11478 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11479 } 11480 if (res.origUsers != null) { 11481 for (int userHandle : res.origUsers) { 11482 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11483 userHandle, installerPackageName); 11484 } 11485 } 11486 // Also convey the prior install/uninstall state 11487 if (allUsers != null && perUserInstalled != null) { 11488 for (int i = 0; i < allUsers.length; i++) { 11489 if (DEBUG_INSTALL) { 11490 Slog.d(TAG, " user " + allUsers[i] 11491 + " => " + perUserInstalled[i]); 11492 } 11493 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11494 } 11495 // these install state changes will be persisted in the 11496 // upcoming call to mSettings.writeLPr(). 11497 } 11498 } 11499 // It's implied that when a user requests installation, they want the app to be 11500 // installed and enabled. 11501 int userId = user.getIdentifier(); 11502 if (userId != UserHandle.USER_ALL) { 11503 ps.setInstalled(true, userId); 11504 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11505 } 11506 } 11507 res.name = pkgName; 11508 res.uid = newPackage.applicationInfo.uid; 11509 res.pkg = newPackage; 11510 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11511 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11512 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11513 //to update install status 11514 mSettings.writeLPr(); 11515 } 11516 } 11517 11518 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11519 final int installFlags = args.installFlags; 11520 final String installerPackageName = args.installerPackageName; 11521 final String volumeUuid = args.volumeUuid; 11522 final File tmpPackageFile = new File(args.getCodePath()); 11523 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11524 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11525 || (args.volumeUuid != null)); 11526 boolean replace = false; 11527 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11528 // Result object to be returned 11529 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11530 11531 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11532 // Retrieve PackageSettings and parse package 11533 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11534 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11535 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11536 PackageParser pp = new PackageParser(); 11537 pp.setSeparateProcesses(mSeparateProcesses); 11538 pp.setDisplayMetrics(mMetrics); 11539 11540 final PackageParser.Package pkg; 11541 try { 11542 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11543 } catch (PackageParserException e) { 11544 res.setError("Failed parse during installPackageLI", e); 11545 return; 11546 } 11547 11548 // Mark that we have an install time CPU ABI override. 11549 pkg.cpuAbiOverride = args.abiOverride; 11550 11551 String pkgName = res.name = pkg.packageName; 11552 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11553 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11554 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11555 return; 11556 } 11557 } 11558 11559 try { 11560 pp.collectCertificates(pkg, parseFlags); 11561 pp.collectManifestDigest(pkg); 11562 } catch (PackageParserException e) { 11563 res.setError("Failed collect during installPackageLI", e); 11564 return; 11565 } 11566 11567 /* If the installer passed in a manifest digest, compare it now. */ 11568 if (args.manifestDigest != null) { 11569 if (DEBUG_INSTALL) { 11570 final String parsedManifest = pkg.manifestDigest == null ? "null" 11571 : pkg.manifestDigest.toString(); 11572 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11573 + parsedManifest); 11574 } 11575 11576 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11577 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11578 return; 11579 } 11580 } else if (DEBUG_INSTALL) { 11581 final String parsedManifest = pkg.manifestDigest == null 11582 ? "null" : pkg.manifestDigest.toString(); 11583 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11584 } 11585 11586 // Get rid of all references to package scan path via parser. 11587 pp = null; 11588 String oldCodePath = null; 11589 boolean systemApp = false; 11590 synchronized (mPackages) { 11591 // Check if installing already existing package 11592 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11593 String oldName = mSettings.mRenamedPackages.get(pkgName); 11594 if (pkg.mOriginalPackages != null 11595 && pkg.mOriginalPackages.contains(oldName) 11596 && mPackages.containsKey(oldName)) { 11597 // This package is derived from an original package, 11598 // and this device has been updating from that original 11599 // name. We must continue using the original name, so 11600 // rename the new package here. 11601 pkg.setPackageName(oldName); 11602 pkgName = pkg.packageName; 11603 replace = true; 11604 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11605 + oldName + " pkgName=" + pkgName); 11606 } else if (mPackages.containsKey(pkgName)) { 11607 // This package, under its official name, already exists 11608 // on the device; we should replace it. 11609 replace = true; 11610 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11611 } 11612 11613 // Prevent apps opting out from runtime permissions 11614 if (replace) { 11615 PackageParser.Package oldPackage = mPackages.get(pkgName); 11616 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11617 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11618 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11619 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11620 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11621 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11622 + " doesn't support runtime permissions but the old" 11623 + " target SDK " + oldTargetSdk + " does."); 11624 return; 11625 } 11626 } 11627 } 11628 11629 PackageSetting ps = mSettings.mPackages.get(pkgName); 11630 if (ps != null) { 11631 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11632 11633 // Quick sanity check that we're signed correctly if updating; 11634 // we'll check this again later when scanning, but we want to 11635 // bail early here before tripping over redefined permissions. 11636 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 11637 try { 11638 verifySignaturesLP(ps, pkg); 11639 } catch (PackageManagerException e) { 11640 res.setError(e.error, e.getMessage()); 11641 return; 11642 } 11643 } else { 11644 if (!checkUpgradeKeySetLP(ps, pkg)) { 11645 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11646 + pkg.packageName + " upgrade keys do not match the " 11647 + "previously installed version"); 11648 return; 11649 } 11650 } 11651 11652 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11653 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11654 systemApp = (ps.pkg.applicationInfo.flags & 11655 ApplicationInfo.FLAG_SYSTEM) != 0; 11656 } 11657 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11658 } 11659 11660 // Check whether the newly-scanned package wants to define an already-defined perm 11661 int N = pkg.permissions.size(); 11662 for (int i = N-1; i >= 0; i--) { 11663 PackageParser.Permission perm = pkg.permissions.get(i); 11664 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11665 if (bp != null) { 11666 // If the defining package is signed with our cert, it's okay. This 11667 // also includes the "updating the same package" case, of course. 11668 // "updating same package" could also involve key-rotation. 11669 final boolean sigsOk; 11670 if (!bp.sourcePackage.equals(pkg.packageName) 11671 || !(bp.packageSetting instanceof PackageSetting) 11672 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 11673 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 11674 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11675 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11676 } else { 11677 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11678 } 11679 if (!sigsOk) { 11680 // If the owning package is the system itself, we log but allow 11681 // install to proceed; we fail the install on all other permission 11682 // redefinitions. 11683 if (!bp.sourcePackage.equals("android")) { 11684 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11685 + pkg.packageName + " attempting to redeclare permission " 11686 + perm.info.name + " already owned by " + bp.sourcePackage); 11687 res.origPermission = perm.info.name; 11688 res.origPackage = bp.sourcePackage; 11689 return; 11690 } else { 11691 Slog.w(TAG, "Package " + pkg.packageName 11692 + " attempting to redeclare system permission " 11693 + perm.info.name + "; ignoring new declaration"); 11694 pkg.permissions.remove(i); 11695 } 11696 } 11697 } 11698 } 11699 11700 } 11701 11702 if (systemApp && onExternal) { 11703 // Disable updates to system apps on sdcard 11704 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11705 "Cannot install updates to system apps on sdcard"); 11706 return; 11707 } 11708 11709 if (args.move != null) { 11710 // We did an in-place move, so dex is ready to roll 11711 scanFlags |= SCAN_NO_DEX; 11712 scanFlags |= SCAN_MOVE; 11713 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11714 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11715 scanFlags |= SCAN_NO_DEX; 11716 11717 try { 11718 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11719 true /* extract libs */); 11720 } catch (PackageManagerException pme) { 11721 Slog.e(TAG, "Error deriving application ABI", pme); 11722 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11723 return; 11724 } 11725 11726 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11727 int result = mPackageDexOptimizer 11728 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11729 false /* defer */, false /* inclDependencies */); 11730 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11731 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11732 return; 11733 } 11734 } 11735 11736 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11737 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11738 return; 11739 } 11740 11741 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11742 11743 if (replace) { 11744 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11745 installerPackageName, volumeUuid, res); 11746 } else { 11747 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11748 args.user, installerPackageName, volumeUuid, res); 11749 } 11750 synchronized (mPackages) { 11751 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11752 if (ps != null) { 11753 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11754 } 11755 } 11756 } 11757 11758 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11759 if (mIntentFilterVerifierComponent == null) { 11760 Slog.w(TAG, "No IntentFilter verification will not be done as " 11761 + "there is no IntentFilterVerifier available!"); 11762 return; 11763 } 11764 11765 final int verifierUid = getPackageUid( 11766 mIntentFilterVerifierComponent.getPackageName(), 11767 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11768 11769 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11770 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11771 msg.obj = pkg; 11772 msg.arg1 = userId; 11773 msg.arg2 = verifierUid; 11774 11775 mHandler.sendMessage(msg); 11776 } 11777 11778 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11779 PackageParser.Package pkg) { 11780 int size = pkg.activities.size(); 11781 if (size == 0) { 11782 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11783 "No activity, so no need to verify any IntentFilter!"); 11784 return; 11785 } 11786 11787 final boolean hasDomainURLs = hasDomainURLs(pkg); 11788 if (!hasDomainURLs) { 11789 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11790 "No domain URLs, so no need to verify any IntentFilter!"); 11791 return; 11792 } 11793 11794 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11795 + " if any IntentFilter from the " + size 11796 + " Activities needs verification ..."); 11797 11798 final int verificationId = mIntentFilterVerificationToken++; 11799 int count = 0; 11800 final String packageName = pkg.packageName; 11801 ArrayList<String> allHosts = new ArrayList<>(); 11802 11803 synchronized (mPackages) { 11804 for (PackageParser.Activity a : pkg.activities) { 11805 for (ActivityIntentInfo filter : a.intents) { 11806 boolean needsFilterVerification = filter.needsVerification(); 11807 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11808 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11809 "Verification needed for IntentFilter:" + filter.toString()); 11810 mIntentFilterVerifier.addOneIntentFilterVerification( 11811 verifierUid, userId, verificationId, filter, packageName); 11812 count++; 11813 } else if (!needsFilterVerification) { 11814 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11815 "No verification needed for IntentFilter:" + filter.toString()); 11816 if (hasValidDomains(filter)) { 11817 ArrayList<String> hosts = filter.getHostsList(); 11818 if (hosts.size() > 0) { 11819 allHosts.addAll(hosts); 11820 } else { 11821 if (allHosts.isEmpty()) { 11822 allHosts.add("*"); 11823 } 11824 } 11825 } 11826 } else { 11827 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11828 "Verification already done for IntentFilter:" + filter.toString()); 11829 } 11830 } 11831 } 11832 } 11833 11834 if (count > 0) { 11835 mIntentFilterVerifier.startVerifications(userId); 11836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Started " + count 11837 + " IntentFilter verification" + (count > 1 ? "s" : "") 11838 + " for userId:" + userId + "!"); 11839 } else { 11840 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11841 "No need to start any IntentFilter verification!"); 11842 if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw( 11843 packageName, allHosts) != null) { 11844 scheduleWriteSettingsLocked(); 11845 } 11846 } 11847 } 11848 11849 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11850 final ComponentName cn = filter.activity.getComponentName(); 11851 final String packageName = cn.getPackageName(); 11852 11853 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11854 packageName); 11855 if (ivi == null) { 11856 return true; 11857 } 11858 int status = ivi.getStatus(); 11859 switch (status) { 11860 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11861 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11862 return true; 11863 11864 default: 11865 // Nothing to do 11866 return false; 11867 } 11868 } 11869 11870 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11871 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11872 || ((pkg.applicationInfo.privateFlags 11873 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11874 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11875 } 11876 11877 private static boolean isMultiArch(PackageSetting ps) { 11878 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11879 } 11880 11881 private static boolean isMultiArch(ApplicationInfo info) { 11882 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11883 } 11884 11885 private static boolean isExternal(PackageParser.Package pkg) { 11886 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11887 } 11888 11889 private static boolean isExternal(PackageSetting ps) { 11890 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11891 } 11892 11893 private static boolean isExternal(ApplicationInfo info) { 11894 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11895 } 11896 11897 private static boolean isSystemApp(PackageParser.Package pkg) { 11898 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11899 } 11900 11901 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11902 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11903 } 11904 11905 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11906 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11907 } 11908 11909 private static boolean isSystemApp(PackageSetting ps) { 11910 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11911 } 11912 11913 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11914 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11915 } 11916 11917 private int packageFlagsToInstallFlags(PackageSetting ps) { 11918 int installFlags = 0; 11919 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11920 // This existing package was an external ASEC install when we have 11921 // the external flag without a UUID 11922 installFlags |= PackageManager.INSTALL_EXTERNAL; 11923 } 11924 if (ps.isForwardLocked()) { 11925 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11926 } 11927 return installFlags; 11928 } 11929 11930 private void deleteTempPackageFiles() { 11931 final FilenameFilter filter = new FilenameFilter() { 11932 public boolean accept(File dir, String name) { 11933 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11934 } 11935 }; 11936 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11937 file.delete(); 11938 } 11939 } 11940 11941 @Override 11942 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11943 int flags) { 11944 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11945 flags); 11946 } 11947 11948 @Override 11949 public void deletePackage(final String packageName, 11950 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11951 mContext.enforceCallingOrSelfPermission( 11952 android.Manifest.permission.DELETE_PACKAGES, null); 11953 final int uid = Binder.getCallingUid(); 11954 if (UserHandle.getUserId(uid) != userId) { 11955 mContext.enforceCallingPermission( 11956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11957 "deletePackage for user " + userId); 11958 } 11959 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11960 try { 11961 observer.onPackageDeleted(packageName, 11962 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11963 } catch (RemoteException re) { 11964 } 11965 return; 11966 } 11967 11968 boolean uninstallBlocked = false; 11969 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11970 int[] users = sUserManager.getUserIds(); 11971 for (int i = 0; i < users.length; ++i) { 11972 if (getBlockUninstallForUser(packageName, users[i])) { 11973 uninstallBlocked = true; 11974 break; 11975 } 11976 } 11977 } else { 11978 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11979 } 11980 if (uninstallBlocked) { 11981 try { 11982 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11983 null); 11984 } catch (RemoteException re) { 11985 } 11986 return; 11987 } 11988 11989 if (DEBUG_REMOVE) { 11990 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 11991 } 11992 // Queue up an async operation since the package deletion may take a little while. 11993 mHandler.post(new Runnable() { 11994 public void run() { 11995 mHandler.removeCallbacks(this); 11996 final int returnCode = deletePackageX(packageName, userId, flags); 11997 if (observer != null) { 11998 try { 11999 observer.onPackageDeleted(packageName, returnCode, null); 12000 } catch (RemoteException e) { 12001 Log.i(TAG, "Observer no longer exists."); 12002 } //end catch 12003 } //end if 12004 } //end run 12005 }); 12006 } 12007 12008 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12009 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12010 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12011 try { 12012 if (dpm != null) { 12013 if (dpm.isDeviceOwner(packageName)) { 12014 return true; 12015 } 12016 int[] users; 12017 if (userId == UserHandle.USER_ALL) { 12018 users = sUserManager.getUserIds(); 12019 } else { 12020 users = new int[]{userId}; 12021 } 12022 for (int i = 0; i < users.length; ++i) { 12023 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12024 return true; 12025 } 12026 } 12027 } 12028 } catch (RemoteException e) { 12029 } 12030 return false; 12031 } 12032 12033 /** 12034 * This method is an internal method that could be get invoked either 12035 * to delete an installed package or to clean up a failed installation. 12036 * After deleting an installed package, a broadcast is sent to notify any 12037 * listeners that the package has been installed. For cleaning up a failed 12038 * installation, the broadcast is not necessary since the package's 12039 * installation wouldn't have sent the initial broadcast either 12040 * The key steps in deleting a package are 12041 * deleting the package information in internal structures like mPackages, 12042 * deleting the packages base directories through installd 12043 * updating mSettings to reflect current status 12044 * persisting settings for later use 12045 * sending a broadcast if necessary 12046 */ 12047 private int deletePackageX(String packageName, int userId, int flags) { 12048 final PackageRemovedInfo info = new PackageRemovedInfo(); 12049 final boolean res; 12050 12051 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12052 ? UserHandle.ALL : new UserHandle(userId); 12053 12054 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12055 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12056 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12057 } 12058 12059 boolean removedForAllUsers = false; 12060 boolean systemUpdate = false; 12061 12062 // for the uninstall-updates case and restricted profiles, remember the per- 12063 // userhandle installed state 12064 int[] allUsers; 12065 boolean[] perUserInstalled; 12066 synchronized (mPackages) { 12067 PackageSetting ps = mSettings.mPackages.get(packageName); 12068 allUsers = sUserManager.getUserIds(); 12069 perUserInstalled = new boolean[allUsers.length]; 12070 for (int i = 0; i < allUsers.length; i++) { 12071 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12072 } 12073 } 12074 12075 synchronized (mInstallLock) { 12076 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12077 res = deletePackageLI(packageName, removeForUser, 12078 true, allUsers, perUserInstalled, 12079 flags | REMOVE_CHATTY, info, true); 12080 systemUpdate = info.isRemovedPackageSystemUpdate; 12081 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12082 removedForAllUsers = true; 12083 } 12084 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12085 + " removedForAllUsers=" + removedForAllUsers); 12086 } 12087 12088 if (res) { 12089 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12090 12091 // If the removed package was a system update, the old system package 12092 // was re-enabled; we need to broadcast this information 12093 if (systemUpdate) { 12094 Bundle extras = new Bundle(1); 12095 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12096 ? info.removedAppId : info.uid); 12097 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12098 12099 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12100 extras, null, null, null); 12101 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12102 extras, null, null, null); 12103 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12104 null, packageName, null, null); 12105 } 12106 } 12107 // Force a gc here. 12108 Runtime.getRuntime().gc(); 12109 // Delete the resources here after sending the broadcast to let 12110 // other processes clean up before deleting resources. 12111 if (info.args != null) { 12112 synchronized (mInstallLock) { 12113 info.args.doPostDeleteLI(true); 12114 } 12115 } 12116 12117 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12118 } 12119 12120 class PackageRemovedInfo { 12121 String removedPackage; 12122 int uid = -1; 12123 int removedAppId = -1; 12124 int[] removedUsers = null; 12125 boolean isRemovedPackageSystemUpdate = false; 12126 // Clean up resources deleted packages. 12127 InstallArgs args = null; 12128 12129 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12130 Bundle extras = new Bundle(1); 12131 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12132 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12133 if (replacing) { 12134 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12135 } 12136 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12137 if (removedPackage != null) { 12138 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12139 extras, null, null, removedUsers); 12140 if (fullRemove && !replacing) { 12141 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12142 extras, null, null, removedUsers); 12143 } 12144 } 12145 if (removedAppId >= 0) { 12146 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12147 removedUsers); 12148 } 12149 } 12150 } 12151 12152 /* 12153 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12154 * flag is not set, the data directory is removed as well. 12155 * make sure this flag is set for partially installed apps. If not its meaningless to 12156 * delete a partially installed application. 12157 */ 12158 private void removePackageDataLI(PackageSetting ps, 12159 int[] allUserHandles, boolean[] perUserInstalled, 12160 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12161 String packageName = ps.name; 12162 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12163 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12164 // Retrieve object to delete permissions for shared user later on 12165 final PackageSetting deletedPs; 12166 // reader 12167 synchronized (mPackages) { 12168 deletedPs = mSettings.mPackages.get(packageName); 12169 if (outInfo != null) { 12170 outInfo.removedPackage = packageName; 12171 outInfo.removedUsers = deletedPs != null 12172 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12173 : null; 12174 } 12175 } 12176 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12177 removeDataDirsLI(ps.volumeUuid, packageName); 12178 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12179 } 12180 // writer 12181 synchronized (mPackages) { 12182 if (deletedPs != null) { 12183 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12184 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12185 clearDefaultBrowserIfNeeded(packageName); 12186 if (outInfo != null) { 12187 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12188 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12189 } 12190 updatePermissionsLPw(deletedPs.name, null, 0); 12191 if (deletedPs.sharedUser != null) { 12192 // Remove permissions associated with package. Since runtime 12193 // permissions are per user we have to kill the removed package 12194 // or packages running under the shared user of the removed 12195 // package if revoking the permissions requested only by the removed 12196 // package is successful and this causes a change in gids. 12197 for (int userId : UserManagerService.getInstance().getUserIds()) { 12198 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12199 userId); 12200 if (userIdToKill == UserHandle.USER_ALL 12201 || userIdToKill >= UserHandle.USER_OWNER) { 12202 // If gids changed for this user, kill all affected packages. 12203 mHandler.post(new Runnable() { 12204 @Override 12205 public void run() { 12206 // This has to happen with no lock held. 12207 killSettingPackagesForUser(deletedPs, userIdToKill, 12208 KILL_APP_REASON_GIDS_CHANGED); 12209 } 12210 }); 12211 break; 12212 } 12213 } 12214 } 12215 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12216 } 12217 // make sure to preserve per-user disabled state if this removal was just 12218 // a downgrade of a system app to the factory package 12219 if (allUserHandles != null && perUserInstalled != null) { 12220 if (DEBUG_REMOVE) { 12221 Slog.d(TAG, "Propagating install state across downgrade"); 12222 } 12223 for (int i = 0; i < allUserHandles.length; i++) { 12224 if (DEBUG_REMOVE) { 12225 Slog.d(TAG, " user " + allUserHandles[i] 12226 + " => " + perUserInstalled[i]); 12227 } 12228 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12229 } 12230 } 12231 } 12232 // can downgrade to reader 12233 if (writeSettings) { 12234 // Save settings now 12235 mSettings.writeLPr(); 12236 } 12237 } 12238 if (outInfo != null) { 12239 // A user ID was deleted here. Go through all users and remove it 12240 // from KeyStore. 12241 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12242 } 12243 } 12244 12245 static boolean locationIsPrivileged(File path) { 12246 try { 12247 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12248 .getCanonicalPath(); 12249 return path.getCanonicalPath().startsWith(privilegedAppDir); 12250 } catch (IOException e) { 12251 Slog.e(TAG, "Unable to access code path " + path); 12252 } 12253 return false; 12254 } 12255 12256 /* 12257 * Tries to delete system package. 12258 */ 12259 private boolean deleteSystemPackageLI(PackageSetting newPs, 12260 int[] allUserHandles, boolean[] perUserInstalled, 12261 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12262 final boolean applyUserRestrictions 12263 = (allUserHandles != null) && (perUserInstalled != null); 12264 PackageSetting disabledPs = null; 12265 // Confirm if the system package has been updated 12266 // An updated system app can be deleted. This will also have to restore 12267 // the system pkg from system partition 12268 // reader 12269 synchronized (mPackages) { 12270 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12271 } 12272 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12273 + " disabledPs=" + disabledPs); 12274 if (disabledPs == null) { 12275 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12276 return false; 12277 } else if (DEBUG_REMOVE) { 12278 Slog.d(TAG, "Deleting system pkg from data partition"); 12279 } 12280 if (DEBUG_REMOVE) { 12281 if (applyUserRestrictions) { 12282 Slog.d(TAG, "Remembering install states:"); 12283 for (int i = 0; i < allUserHandles.length; i++) { 12284 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12285 } 12286 } 12287 } 12288 // Delete the updated package 12289 outInfo.isRemovedPackageSystemUpdate = true; 12290 if (disabledPs.versionCode < newPs.versionCode) { 12291 // Delete data for downgrades 12292 flags &= ~PackageManager.DELETE_KEEP_DATA; 12293 } else { 12294 // Preserve data by setting flag 12295 flags |= PackageManager.DELETE_KEEP_DATA; 12296 } 12297 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12298 allUserHandles, perUserInstalled, outInfo, writeSettings); 12299 if (!ret) { 12300 return false; 12301 } 12302 // writer 12303 synchronized (mPackages) { 12304 // Reinstate the old system package 12305 mSettings.enableSystemPackageLPw(newPs.name); 12306 // Remove any native libraries from the upgraded package. 12307 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12308 } 12309 // Install the system package 12310 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12311 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12312 if (locationIsPrivileged(disabledPs.codePath)) { 12313 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12314 } 12315 12316 final PackageParser.Package newPkg; 12317 try { 12318 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12319 } catch (PackageManagerException e) { 12320 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12321 return false; 12322 } 12323 12324 // writer 12325 synchronized (mPackages) { 12326 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12327 updatePermissionsLPw(newPkg.packageName, newPkg, 12328 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12329 if (applyUserRestrictions) { 12330 if (DEBUG_REMOVE) { 12331 Slog.d(TAG, "Propagating install state across reinstall"); 12332 } 12333 for (int i = 0; i < allUserHandles.length; i++) { 12334 if (DEBUG_REMOVE) { 12335 Slog.d(TAG, " user " + allUserHandles[i] 12336 + " => " + perUserInstalled[i]); 12337 } 12338 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12339 } 12340 // Regardless of writeSettings we need to ensure that this restriction 12341 // state propagation is persisted 12342 mSettings.writeAllUsersPackageRestrictionsLPr(); 12343 } 12344 // can downgrade to reader here 12345 if (writeSettings) { 12346 mSettings.writeLPr(); 12347 } 12348 } 12349 return true; 12350 } 12351 12352 private boolean deleteInstalledPackageLI(PackageSetting ps, 12353 boolean deleteCodeAndResources, int flags, 12354 int[] allUserHandles, boolean[] perUserInstalled, 12355 PackageRemovedInfo outInfo, boolean writeSettings) { 12356 if (outInfo != null) { 12357 outInfo.uid = ps.appId; 12358 } 12359 12360 // Delete package data from internal structures and also remove data if flag is set 12361 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12362 12363 // Delete application code and resources 12364 if (deleteCodeAndResources && (outInfo != null)) { 12365 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12366 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12367 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12368 } 12369 return true; 12370 } 12371 12372 @Override 12373 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12374 int userId) { 12375 mContext.enforceCallingOrSelfPermission( 12376 android.Manifest.permission.DELETE_PACKAGES, null); 12377 synchronized (mPackages) { 12378 PackageSetting ps = mSettings.mPackages.get(packageName); 12379 if (ps == null) { 12380 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12381 return false; 12382 } 12383 if (!ps.getInstalled(userId)) { 12384 // Can't block uninstall for an app that is not installed or enabled. 12385 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12386 return false; 12387 } 12388 ps.setBlockUninstall(blockUninstall, userId); 12389 mSettings.writePackageRestrictionsLPr(userId); 12390 } 12391 return true; 12392 } 12393 12394 @Override 12395 public boolean getBlockUninstallForUser(String packageName, int userId) { 12396 synchronized (mPackages) { 12397 PackageSetting ps = mSettings.mPackages.get(packageName); 12398 if (ps == null) { 12399 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12400 return false; 12401 } 12402 return ps.getBlockUninstall(userId); 12403 } 12404 } 12405 12406 /* 12407 * This method handles package deletion in general 12408 */ 12409 private boolean deletePackageLI(String packageName, UserHandle user, 12410 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12411 int flags, PackageRemovedInfo outInfo, 12412 boolean writeSettings) { 12413 if (packageName == null) { 12414 Slog.w(TAG, "Attempt to delete null packageName."); 12415 return false; 12416 } 12417 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12418 PackageSetting ps; 12419 boolean dataOnly = false; 12420 int removeUser = -1; 12421 int appId = -1; 12422 synchronized (mPackages) { 12423 ps = mSettings.mPackages.get(packageName); 12424 if (ps == null) { 12425 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12426 return false; 12427 } 12428 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12429 && user.getIdentifier() != UserHandle.USER_ALL) { 12430 // The caller is asking that the package only be deleted for a single 12431 // user. To do this, we just mark its uninstalled state and delete 12432 // its data. If this is a system app, we only allow this to happen if 12433 // they have set the special DELETE_SYSTEM_APP which requests different 12434 // semantics than normal for uninstalling system apps. 12435 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12436 ps.setUserState(user.getIdentifier(), 12437 COMPONENT_ENABLED_STATE_DEFAULT, 12438 false, //installed 12439 true, //stopped 12440 true, //notLaunched 12441 false, //hidden 12442 null, null, null, 12443 false, // blockUninstall 12444 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12445 if (!isSystemApp(ps)) { 12446 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12447 // Other user still have this package installed, so all 12448 // we need to do is clear this user's data and save that 12449 // it is uninstalled. 12450 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12451 removeUser = user.getIdentifier(); 12452 appId = ps.appId; 12453 scheduleWritePackageRestrictionsLocked(removeUser); 12454 } else { 12455 // We need to set it back to 'installed' so the uninstall 12456 // broadcasts will be sent correctly. 12457 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12458 ps.setInstalled(true, user.getIdentifier()); 12459 } 12460 } else { 12461 // This is a system app, so we assume that the 12462 // other users still have this package installed, so all 12463 // we need to do is clear this user's data and save that 12464 // it is uninstalled. 12465 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12466 removeUser = user.getIdentifier(); 12467 appId = ps.appId; 12468 scheduleWritePackageRestrictionsLocked(removeUser); 12469 } 12470 } 12471 } 12472 12473 if (removeUser >= 0) { 12474 // From above, we determined that we are deleting this only 12475 // for a single user. Continue the work here. 12476 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12477 if (outInfo != null) { 12478 outInfo.removedPackage = packageName; 12479 outInfo.removedAppId = appId; 12480 outInfo.removedUsers = new int[] {removeUser}; 12481 } 12482 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12483 removeKeystoreDataIfNeeded(removeUser, appId); 12484 schedulePackageCleaning(packageName, removeUser, false); 12485 synchronized (mPackages) { 12486 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12487 scheduleWritePackageRestrictionsLocked(removeUser); 12488 } 12489 } 12490 return true; 12491 } 12492 12493 if (dataOnly) { 12494 // Delete application data first 12495 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12496 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12497 return true; 12498 } 12499 12500 boolean ret = false; 12501 if (isSystemApp(ps)) { 12502 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12503 // When an updated system application is deleted we delete the existing resources as well and 12504 // fall back to existing code in system partition 12505 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12506 flags, outInfo, writeSettings); 12507 } else { 12508 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12509 // Kill application pre-emptively especially for apps on sd. 12510 killApplication(packageName, ps.appId, "uninstall pkg"); 12511 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12512 allUserHandles, perUserInstalled, 12513 outInfo, writeSettings); 12514 } 12515 12516 return ret; 12517 } 12518 12519 private final class ClearStorageConnection implements ServiceConnection { 12520 IMediaContainerService mContainerService; 12521 12522 @Override 12523 public void onServiceConnected(ComponentName name, IBinder service) { 12524 synchronized (this) { 12525 mContainerService = IMediaContainerService.Stub.asInterface(service); 12526 notifyAll(); 12527 } 12528 } 12529 12530 @Override 12531 public void onServiceDisconnected(ComponentName name) { 12532 } 12533 } 12534 12535 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12536 final boolean mounted; 12537 if (Environment.isExternalStorageEmulated()) { 12538 mounted = true; 12539 } else { 12540 final String status = Environment.getExternalStorageState(); 12541 12542 mounted = status.equals(Environment.MEDIA_MOUNTED) 12543 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12544 } 12545 12546 if (!mounted) { 12547 return; 12548 } 12549 12550 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12551 int[] users; 12552 if (userId == UserHandle.USER_ALL) { 12553 users = sUserManager.getUserIds(); 12554 } else { 12555 users = new int[] { userId }; 12556 } 12557 final ClearStorageConnection conn = new ClearStorageConnection(); 12558 if (mContext.bindServiceAsUser( 12559 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12560 try { 12561 for (int curUser : users) { 12562 long timeout = SystemClock.uptimeMillis() + 5000; 12563 synchronized (conn) { 12564 long now = SystemClock.uptimeMillis(); 12565 while (conn.mContainerService == null && now < timeout) { 12566 try { 12567 conn.wait(timeout - now); 12568 } catch (InterruptedException e) { 12569 } 12570 } 12571 } 12572 if (conn.mContainerService == null) { 12573 return; 12574 } 12575 12576 final UserEnvironment userEnv = new UserEnvironment(curUser); 12577 clearDirectory(conn.mContainerService, 12578 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12579 if (allData) { 12580 clearDirectory(conn.mContainerService, 12581 userEnv.buildExternalStorageAppDataDirs(packageName)); 12582 clearDirectory(conn.mContainerService, 12583 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12584 } 12585 } 12586 } finally { 12587 mContext.unbindService(conn); 12588 } 12589 } 12590 } 12591 12592 @Override 12593 public void clearApplicationUserData(final String packageName, 12594 final IPackageDataObserver observer, final int userId) { 12595 mContext.enforceCallingOrSelfPermission( 12596 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12597 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12598 // Queue up an async operation since the package deletion may take a little while. 12599 mHandler.post(new Runnable() { 12600 public void run() { 12601 mHandler.removeCallbacks(this); 12602 final boolean succeeded; 12603 synchronized (mInstallLock) { 12604 succeeded = clearApplicationUserDataLI(packageName, userId); 12605 } 12606 clearExternalStorageDataSync(packageName, userId, true); 12607 if (succeeded) { 12608 // invoke DeviceStorageMonitor's update method to clear any notifications 12609 DeviceStorageMonitorInternal 12610 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12611 if (dsm != null) { 12612 dsm.checkMemory(); 12613 } 12614 } 12615 if(observer != null) { 12616 try { 12617 observer.onRemoveCompleted(packageName, succeeded); 12618 } catch (RemoteException e) { 12619 Log.i(TAG, "Observer no longer exists."); 12620 } 12621 } //end if observer 12622 } //end run 12623 }); 12624 } 12625 12626 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12627 if (packageName == null) { 12628 Slog.w(TAG, "Attempt to delete null packageName."); 12629 return false; 12630 } 12631 12632 // Try finding details about the requested package 12633 PackageParser.Package pkg; 12634 synchronized (mPackages) { 12635 pkg = mPackages.get(packageName); 12636 if (pkg == null) { 12637 final PackageSetting ps = mSettings.mPackages.get(packageName); 12638 if (ps != null) { 12639 pkg = ps.pkg; 12640 } 12641 } 12642 } 12643 12644 if (pkg == null) { 12645 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12646 } 12647 12648 // Always delete data directories for package, even if we found no other 12649 // record of app. This helps users recover from UID mismatches without 12650 // resorting to a full data wipe. 12651 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12652 if (retCode < 0) { 12653 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12654 return false; 12655 } 12656 12657 if (pkg == null) { 12658 return false; 12659 } 12660 12661 if (pkg != null && pkg.applicationInfo != null) { 12662 final int appId = pkg.applicationInfo.uid; 12663 removeKeystoreDataIfNeeded(userId, appId); 12664 } 12665 12666 // Create a native library symlink only if we have native libraries 12667 // and if the native libraries are 32 bit libraries. We do not provide 12668 // this symlink for 64 bit libraries. 12669 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 12670 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12671 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12672 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12673 nativeLibPath, userId) < 0) { 12674 Slog.w(TAG, "Failed linking native library dir"); 12675 return false; 12676 } 12677 } 12678 12679 return true; 12680 } 12681 12682 /** 12683 * Remove entries from the keystore daemon. Will only remove it if the 12684 * {@code appId} is valid. 12685 */ 12686 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12687 if (appId < 0) { 12688 return; 12689 } 12690 12691 final KeyStore keyStore = KeyStore.getInstance(); 12692 if (keyStore != null) { 12693 if (userId == UserHandle.USER_ALL) { 12694 for (final int individual : sUserManager.getUserIds()) { 12695 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12696 } 12697 } else { 12698 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12699 } 12700 } else { 12701 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12702 } 12703 } 12704 12705 @Override 12706 public void deleteApplicationCacheFiles(final String packageName, 12707 final IPackageDataObserver observer) { 12708 mContext.enforceCallingOrSelfPermission( 12709 android.Manifest.permission.DELETE_CACHE_FILES, null); 12710 // Queue up an async operation since the package deletion may take a little while. 12711 final int userId = UserHandle.getCallingUserId(); 12712 mHandler.post(new Runnable() { 12713 public void run() { 12714 mHandler.removeCallbacks(this); 12715 final boolean succeded; 12716 synchronized (mInstallLock) { 12717 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12718 } 12719 clearExternalStorageDataSync(packageName, userId, false); 12720 if (observer != null) { 12721 try { 12722 observer.onRemoveCompleted(packageName, succeded); 12723 } catch (RemoteException e) { 12724 Log.i(TAG, "Observer no longer exists."); 12725 } 12726 } //end if observer 12727 } //end run 12728 }); 12729 } 12730 12731 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12732 if (packageName == null) { 12733 Slog.w(TAG, "Attempt to delete null packageName."); 12734 return false; 12735 } 12736 PackageParser.Package p; 12737 synchronized (mPackages) { 12738 p = mPackages.get(packageName); 12739 } 12740 if (p == null) { 12741 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12742 return false; 12743 } 12744 final ApplicationInfo applicationInfo = p.applicationInfo; 12745 if (applicationInfo == null) { 12746 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12747 return false; 12748 } 12749 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12750 if (retCode < 0) { 12751 Slog.w(TAG, "Couldn't remove cache files for package: " 12752 + packageName + " u" + userId); 12753 return false; 12754 } 12755 return true; 12756 } 12757 12758 @Override 12759 public void getPackageSizeInfo(final String packageName, int userHandle, 12760 final IPackageStatsObserver observer) { 12761 mContext.enforceCallingOrSelfPermission( 12762 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12763 if (packageName == null) { 12764 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12765 } 12766 12767 PackageStats stats = new PackageStats(packageName, userHandle); 12768 12769 /* 12770 * Queue up an async operation since the package measurement may take a 12771 * little while. 12772 */ 12773 Message msg = mHandler.obtainMessage(INIT_COPY); 12774 msg.obj = new MeasureParams(stats, observer); 12775 mHandler.sendMessage(msg); 12776 } 12777 12778 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12779 PackageStats pStats) { 12780 if (packageName == null) { 12781 Slog.w(TAG, "Attempt to get size of null packageName."); 12782 return false; 12783 } 12784 PackageParser.Package p; 12785 boolean dataOnly = false; 12786 String libDirRoot = null; 12787 String asecPath = null; 12788 PackageSetting ps = null; 12789 synchronized (mPackages) { 12790 p = mPackages.get(packageName); 12791 ps = mSettings.mPackages.get(packageName); 12792 if(p == null) { 12793 dataOnly = true; 12794 if((ps == null) || (ps.pkg == null)) { 12795 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12796 return false; 12797 } 12798 p = ps.pkg; 12799 } 12800 if (ps != null) { 12801 libDirRoot = ps.legacyNativeLibraryPathString; 12802 } 12803 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12804 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12805 if (secureContainerId != null) { 12806 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12807 } 12808 } 12809 } 12810 String publicSrcDir = null; 12811 if(!dataOnly) { 12812 final ApplicationInfo applicationInfo = p.applicationInfo; 12813 if (applicationInfo == null) { 12814 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12815 return false; 12816 } 12817 if (p.isForwardLocked()) { 12818 publicSrcDir = applicationInfo.getBaseResourcePath(); 12819 } 12820 } 12821 // TODO: extend to measure size of split APKs 12822 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12823 // not just the first level. 12824 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12825 // just the primary. 12826 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12827 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12828 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12829 if (res < 0) { 12830 return false; 12831 } 12832 12833 // Fix-up for forward-locked applications in ASEC containers. 12834 if (!isExternal(p)) { 12835 pStats.codeSize += pStats.externalCodeSize; 12836 pStats.externalCodeSize = 0L; 12837 } 12838 12839 return true; 12840 } 12841 12842 12843 @Override 12844 public void addPackageToPreferred(String packageName) { 12845 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12846 } 12847 12848 @Override 12849 public void removePackageFromPreferred(String packageName) { 12850 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12851 } 12852 12853 @Override 12854 public List<PackageInfo> getPreferredPackages(int flags) { 12855 return new ArrayList<PackageInfo>(); 12856 } 12857 12858 private int getUidTargetSdkVersionLockedLPr(int uid) { 12859 Object obj = mSettings.getUserIdLPr(uid); 12860 if (obj instanceof SharedUserSetting) { 12861 final SharedUserSetting sus = (SharedUserSetting) obj; 12862 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12863 final Iterator<PackageSetting> it = sus.packages.iterator(); 12864 while (it.hasNext()) { 12865 final PackageSetting ps = it.next(); 12866 if (ps.pkg != null) { 12867 int v = ps.pkg.applicationInfo.targetSdkVersion; 12868 if (v < vers) vers = v; 12869 } 12870 } 12871 return vers; 12872 } else if (obj instanceof PackageSetting) { 12873 final PackageSetting ps = (PackageSetting) obj; 12874 if (ps.pkg != null) { 12875 return ps.pkg.applicationInfo.targetSdkVersion; 12876 } 12877 } 12878 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12879 } 12880 12881 @Override 12882 public void addPreferredActivity(IntentFilter filter, int match, 12883 ComponentName[] set, ComponentName activity, int userId) { 12884 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12885 "Adding preferred"); 12886 } 12887 12888 private void addPreferredActivityInternal(IntentFilter filter, int match, 12889 ComponentName[] set, ComponentName activity, boolean always, int userId, 12890 String opname) { 12891 // writer 12892 int callingUid = Binder.getCallingUid(); 12893 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12894 if (filter.countActions() == 0) { 12895 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12896 return; 12897 } 12898 synchronized (mPackages) { 12899 if (mContext.checkCallingOrSelfPermission( 12900 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12901 != PackageManager.PERMISSION_GRANTED) { 12902 if (getUidTargetSdkVersionLockedLPr(callingUid) 12903 < Build.VERSION_CODES.FROYO) { 12904 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12905 + callingUid); 12906 return; 12907 } 12908 mContext.enforceCallingOrSelfPermission( 12909 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12910 } 12911 12912 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12913 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12914 + userId + ":"); 12915 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12916 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12917 scheduleWritePackageRestrictionsLocked(userId); 12918 } 12919 } 12920 12921 @Override 12922 public void replacePreferredActivity(IntentFilter filter, int match, 12923 ComponentName[] set, ComponentName activity, int userId) { 12924 if (filter.countActions() != 1) { 12925 throw new IllegalArgumentException( 12926 "replacePreferredActivity expects filter to have only 1 action."); 12927 } 12928 if (filter.countDataAuthorities() != 0 12929 || filter.countDataPaths() != 0 12930 || filter.countDataSchemes() > 1 12931 || filter.countDataTypes() != 0) { 12932 throw new IllegalArgumentException( 12933 "replacePreferredActivity expects filter to have no data authorities, " + 12934 "paths, or types; and at most one scheme."); 12935 } 12936 12937 final int callingUid = Binder.getCallingUid(); 12938 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12939 synchronized (mPackages) { 12940 if (mContext.checkCallingOrSelfPermission( 12941 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12942 != PackageManager.PERMISSION_GRANTED) { 12943 if (getUidTargetSdkVersionLockedLPr(callingUid) 12944 < Build.VERSION_CODES.FROYO) { 12945 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12946 + Binder.getCallingUid()); 12947 return; 12948 } 12949 mContext.enforceCallingOrSelfPermission( 12950 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12951 } 12952 12953 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12954 if (pir != null) { 12955 // Get all of the existing entries that exactly match this filter. 12956 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12957 if (existing != null && existing.size() == 1) { 12958 PreferredActivity cur = existing.get(0); 12959 if (DEBUG_PREFERRED) { 12960 Slog.i(TAG, "Checking replace of preferred:"); 12961 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12962 if (!cur.mPref.mAlways) { 12963 Slog.i(TAG, " -- CUR; not mAlways!"); 12964 } else { 12965 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 12966 Slog.i(TAG, " -- CUR: mSet=" 12967 + Arrays.toString(cur.mPref.mSetComponents)); 12968 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 12969 Slog.i(TAG, " -- NEW: mMatch=" 12970 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 12971 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 12972 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 12973 } 12974 } 12975 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 12976 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 12977 && cur.mPref.sameSet(set)) { 12978 // Setting the preferred activity to what it happens to be already 12979 if (DEBUG_PREFERRED) { 12980 Slog.i(TAG, "Replacing with same preferred activity " 12981 + cur.mPref.mShortComponent + " for user " 12982 + userId + ":"); 12983 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12984 } 12985 return; 12986 } 12987 } 12988 12989 if (existing != null) { 12990 if (DEBUG_PREFERRED) { 12991 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 12992 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12993 } 12994 for (int i = 0; i < existing.size(); i++) { 12995 PreferredActivity pa = existing.get(i); 12996 if (DEBUG_PREFERRED) { 12997 Slog.i(TAG, "Removing existing preferred activity " 12998 + pa.mPref.mComponent + ":"); 12999 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13000 } 13001 pir.removeFilter(pa); 13002 } 13003 } 13004 } 13005 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13006 "Replacing preferred"); 13007 } 13008 } 13009 13010 @Override 13011 public void clearPackagePreferredActivities(String packageName) { 13012 final int uid = Binder.getCallingUid(); 13013 // writer 13014 synchronized (mPackages) { 13015 PackageParser.Package pkg = mPackages.get(packageName); 13016 if (pkg == null || pkg.applicationInfo.uid != uid) { 13017 if (mContext.checkCallingOrSelfPermission( 13018 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13019 != PackageManager.PERMISSION_GRANTED) { 13020 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13021 < Build.VERSION_CODES.FROYO) { 13022 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13023 + Binder.getCallingUid()); 13024 return; 13025 } 13026 mContext.enforceCallingOrSelfPermission( 13027 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13028 } 13029 } 13030 13031 int user = UserHandle.getCallingUserId(); 13032 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13033 scheduleWritePackageRestrictionsLocked(user); 13034 } 13035 } 13036 } 13037 13038 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13039 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13040 ArrayList<PreferredActivity> removed = null; 13041 boolean changed = false; 13042 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13043 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13044 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13045 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13046 continue; 13047 } 13048 Iterator<PreferredActivity> it = pir.filterIterator(); 13049 while (it.hasNext()) { 13050 PreferredActivity pa = it.next(); 13051 // Mark entry for removal only if it matches the package name 13052 // and the entry is of type "always". 13053 if (packageName == null || 13054 (pa.mPref.mComponent.getPackageName().equals(packageName) 13055 && pa.mPref.mAlways)) { 13056 if (removed == null) { 13057 removed = new ArrayList<PreferredActivity>(); 13058 } 13059 removed.add(pa); 13060 } 13061 } 13062 if (removed != null) { 13063 for (int j=0; j<removed.size(); j++) { 13064 PreferredActivity pa = removed.get(j); 13065 pir.removeFilter(pa); 13066 } 13067 changed = true; 13068 } 13069 } 13070 return changed; 13071 } 13072 13073 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13074 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13075 if (userId == UserHandle.USER_ALL) { 13076 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13077 sUserManager.getUserIds())) { 13078 for (int oneUserId : sUserManager.getUserIds()) { 13079 scheduleWritePackageRestrictionsLocked(oneUserId); 13080 } 13081 } 13082 } else { 13083 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13084 scheduleWritePackageRestrictionsLocked(userId); 13085 } 13086 } 13087 } 13088 13089 13090 void clearDefaultBrowserIfNeeded(String packageName) { 13091 for (int oneUserId : sUserManager.getUserIds()) { 13092 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13093 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13094 if (packageName.equals(defaultBrowserPackageName)) { 13095 setDefaultBrowserPackageName(null, oneUserId); 13096 } 13097 } 13098 } 13099 13100 @Override 13101 public void resetPreferredActivities(int userId) { 13102 /* TODO: Actually use userId. Why is it being passed in? */ 13103 mContext.enforceCallingOrSelfPermission( 13104 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13105 // writer 13106 synchronized (mPackages) { 13107 int user = UserHandle.getCallingUserId(); 13108 clearPackagePreferredActivitiesLPw(null, user); 13109 mSettings.readDefaultPreferredAppsLPw(this, user); 13110 scheduleWritePackageRestrictionsLocked(user); 13111 } 13112 } 13113 13114 @Override 13115 public int getPreferredActivities(List<IntentFilter> outFilters, 13116 List<ComponentName> outActivities, String packageName) { 13117 13118 int num = 0; 13119 final int userId = UserHandle.getCallingUserId(); 13120 // reader 13121 synchronized (mPackages) { 13122 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13123 if (pir != null) { 13124 final Iterator<PreferredActivity> it = pir.filterIterator(); 13125 while (it.hasNext()) { 13126 final PreferredActivity pa = it.next(); 13127 if (packageName == null 13128 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13129 && pa.mPref.mAlways)) { 13130 if (outFilters != null) { 13131 outFilters.add(new IntentFilter(pa)); 13132 } 13133 if (outActivities != null) { 13134 outActivities.add(pa.mPref.mComponent); 13135 } 13136 } 13137 } 13138 } 13139 } 13140 13141 return num; 13142 } 13143 13144 @Override 13145 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13146 int userId) { 13147 int callingUid = Binder.getCallingUid(); 13148 if (callingUid != Process.SYSTEM_UID) { 13149 throw new SecurityException( 13150 "addPersistentPreferredActivity can only be run by the system"); 13151 } 13152 if (filter.countActions() == 0) { 13153 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13154 return; 13155 } 13156 synchronized (mPackages) { 13157 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13158 " :"); 13159 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13160 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13161 new PersistentPreferredActivity(filter, activity)); 13162 scheduleWritePackageRestrictionsLocked(userId); 13163 } 13164 } 13165 13166 @Override 13167 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13168 int callingUid = Binder.getCallingUid(); 13169 if (callingUid != Process.SYSTEM_UID) { 13170 throw new SecurityException( 13171 "clearPackagePersistentPreferredActivities can only be run by the system"); 13172 } 13173 ArrayList<PersistentPreferredActivity> removed = null; 13174 boolean changed = false; 13175 synchronized (mPackages) { 13176 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13177 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13178 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13179 .valueAt(i); 13180 if (userId != thisUserId) { 13181 continue; 13182 } 13183 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13184 while (it.hasNext()) { 13185 PersistentPreferredActivity ppa = it.next(); 13186 // Mark entry for removal only if it matches the package name. 13187 if (ppa.mComponent.getPackageName().equals(packageName)) { 13188 if (removed == null) { 13189 removed = new ArrayList<PersistentPreferredActivity>(); 13190 } 13191 removed.add(ppa); 13192 } 13193 } 13194 if (removed != null) { 13195 for (int j=0; j<removed.size(); j++) { 13196 PersistentPreferredActivity ppa = removed.get(j); 13197 ppir.removeFilter(ppa); 13198 } 13199 changed = true; 13200 } 13201 } 13202 13203 if (changed) { 13204 scheduleWritePackageRestrictionsLocked(userId); 13205 } 13206 } 13207 } 13208 13209 /** 13210 * Non-Binder method, support for the backup/restore mechanism: write the 13211 * full set of preferred activities in its canonical XML format. Returns true 13212 * on success; false otherwise. 13213 */ 13214 @Override 13215 public byte[] getPreferredActivityBackup(int userId) { 13216 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13217 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13218 } 13219 13220 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13221 try { 13222 final XmlSerializer serializer = new FastXmlSerializer(); 13223 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13224 serializer.startDocument(null, true); 13225 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13226 13227 synchronized (mPackages) { 13228 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13229 } 13230 13231 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13232 serializer.endDocument(); 13233 serializer.flush(); 13234 } catch (Exception e) { 13235 if (DEBUG_BACKUP) { 13236 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13237 } 13238 return null; 13239 } 13240 13241 return dataStream.toByteArray(); 13242 } 13243 13244 @Override 13245 public void restorePreferredActivities(byte[] backup, int userId) { 13246 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13247 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13248 } 13249 13250 try { 13251 final XmlPullParser parser = Xml.newPullParser(); 13252 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13253 13254 int type; 13255 while ((type = parser.next()) != XmlPullParser.START_TAG 13256 && type != XmlPullParser.END_DOCUMENT) { 13257 } 13258 if (type != XmlPullParser.START_TAG) { 13259 // oops didn't find a start tag?! 13260 if (DEBUG_BACKUP) { 13261 Slog.e(TAG, "Didn't find start tag during restore"); 13262 } 13263 return; 13264 } 13265 13266 // this is supposed to be TAG_PREFERRED_BACKUP 13267 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13268 if (DEBUG_BACKUP) { 13269 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13270 } 13271 return; 13272 } 13273 13274 // skip interfering stuff, then we're aligned with the backing implementation 13275 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13276 synchronized (mPackages) { 13277 mSettings.readPreferredActivitiesLPw(parser, userId); 13278 } 13279 } catch (Exception e) { 13280 if (DEBUG_BACKUP) { 13281 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13282 } 13283 } 13284 } 13285 13286 @Override 13287 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13288 int sourceUserId, int targetUserId, int flags) { 13289 mContext.enforceCallingOrSelfPermission( 13290 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13291 int callingUid = Binder.getCallingUid(); 13292 enforceOwnerRights(ownerPackage, callingUid); 13293 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13294 if (intentFilter.countActions() == 0) { 13295 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13296 return; 13297 } 13298 synchronized (mPackages) { 13299 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13300 ownerPackage, targetUserId, flags); 13301 CrossProfileIntentResolver resolver = 13302 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13303 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13304 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13305 if (existing != null) { 13306 int size = existing.size(); 13307 for (int i = 0; i < size; i++) { 13308 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13309 return; 13310 } 13311 } 13312 } 13313 resolver.addFilter(newFilter); 13314 scheduleWritePackageRestrictionsLocked(sourceUserId); 13315 } 13316 } 13317 13318 @Override 13319 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13320 mContext.enforceCallingOrSelfPermission( 13321 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13322 int callingUid = Binder.getCallingUid(); 13323 enforceOwnerRights(ownerPackage, callingUid); 13324 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13325 synchronized (mPackages) { 13326 CrossProfileIntentResolver resolver = 13327 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13328 ArraySet<CrossProfileIntentFilter> set = 13329 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13330 for (CrossProfileIntentFilter filter : set) { 13331 if (filter.getOwnerPackage().equals(ownerPackage)) { 13332 resolver.removeFilter(filter); 13333 } 13334 } 13335 scheduleWritePackageRestrictionsLocked(sourceUserId); 13336 } 13337 } 13338 13339 // Enforcing that callingUid is owning pkg on userId 13340 private void enforceOwnerRights(String pkg, int callingUid) { 13341 // The system owns everything. 13342 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13343 return; 13344 } 13345 int callingUserId = UserHandle.getUserId(callingUid); 13346 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13347 if (pi == null) { 13348 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13349 + callingUserId); 13350 } 13351 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13352 throw new SecurityException("Calling uid " + callingUid 13353 + " does not own package " + pkg); 13354 } 13355 } 13356 13357 @Override 13358 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13359 Intent intent = new Intent(Intent.ACTION_MAIN); 13360 intent.addCategory(Intent.CATEGORY_HOME); 13361 13362 final int callingUserId = UserHandle.getCallingUserId(); 13363 List<ResolveInfo> list = queryIntentActivities(intent, null, 13364 PackageManager.GET_META_DATA, callingUserId); 13365 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13366 true, false, false, callingUserId); 13367 13368 allHomeCandidates.clear(); 13369 if (list != null) { 13370 for (ResolveInfo ri : list) { 13371 allHomeCandidates.add(ri); 13372 } 13373 } 13374 return (preferred == null || preferred.activityInfo == null) 13375 ? null 13376 : new ComponentName(preferred.activityInfo.packageName, 13377 preferred.activityInfo.name); 13378 } 13379 13380 @Override 13381 public void setApplicationEnabledSetting(String appPackageName, 13382 int newState, int flags, int userId, String callingPackage) { 13383 if (!sUserManager.exists(userId)) return; 13384 if (callingPackage == null) { 13385 callingPackage = Integer.toString(Binder.getCallingUid()); 13386 } 13387 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13388 } 13389 13390 @Override 13391 public void setComponentEnabledSetting(ComponentName componentName, 13392 int newState, int flags, int userId) { 13393 if (!sUserManager.exists(userId)) return; 13394 setEnabledSetting(componentName.getPackageName(), 13395 componentName.getClassName(), newState, flags, userId, null); 13396 } 13397 13398 private void setEnabledSetting(final String packageName, String className, int newState, 13399 final int flags, int userId, String callingPackage) { 13400 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13401 || newState == COMPONENT_ENABLED_STATE_ENABLED 13402 || newState == COMPONENT_ENABLED_STATE_DISABLED 13403 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13404 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13405 throw new IllegalArgumentException("Invalid new component state: " 13406 + newState); 13407 } 13408 PackageSetting pkgSetting; 13409 final int uid = Binder.getCallingUid(); 13410 final int permission = mContext.checkCallingOrSelfPermission( 13411 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13412 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13413 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13414 boolean sendNow = false; 13415 boolean isApp = (className == null); 13416 String componentName = isApp ? packageName : className; 13417 int packageUid = -1; 13418 ArrayList<String> components; 13419 13420 // writer 13421 synchronized (mPackages) { 13422 pkgSetting = mSettings.mPackages.get(packageName); 13423 if (pkgSetting == null) { 13424 if (className == null) { 13425 throw new IllegalArgumentException( 13426 "Unknown package: " + packageName); 13427 } 13428 throw new IllegalArgumentException( 13429 "Unknown component: " + packageName 13430 + "/" + className); 13431 } 13432 // Allow root and verify that userId is not being specified by a different user 13433 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13434 throw new SecurityException( 13435 "Permission Denial: attempt to change component state from pid=" 13436 + Binder.getCallingPid() 13437 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13438 } 13439 if (className == null) { 13440 // We're dealing with an application/package level state change 13441 if (pkgSetting.getEnabled(userId) == newState) { 13442 // Nothing to do 13443 return; 13444 } 13445 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13446 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13447 // Don't care about who enables an app. 13448 callingPackage = null; 13449 } 13450 pkgSetting.setEnabled(newState, userId, callingPackage); 13451 // pkgSetting.pkg.mSetEnabled = newState; 13452 } else { 13453 // We're dealing with a component level state change 13454 // First, verify that this is a valid class name. 13455 PackageParser.Package pkg = pkgSetting.pkg; 13456 if (pkg == null || !pkg.hasComponentClassName(className)) { 13457 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13458 throw new IllegalArgumentException("Component class " + className 13459 + " does not exist in " + packageName); 13460 } else { 13461 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13462 + className + " does not exist in " + packageName); 13463 } 13464 } 13465 switch (newState) { 13466 case COMPONENT_ENABLED_STATE_ENABLED: 13467 if (!pkgSetting.enableComponentLPw(className, userId)) { 13468 return; 13469 } 13470 break; 13471 case COMPONENT_ENABLED_STATE_DISABLED: 13472 if (!pkgSetting.disableComponentLPw(className, userId)) { 13473 return; 13474 } 13475 break; 13476 case COMPONENT_ENABLED_STATE_DEFAULT: 13477 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13478 return; 13479 } 13480 break; 13481 default: 13482 Slog.e(TAG, "Invalid new component state: " + newState); 13483 return; 13484 } 13485 } 13486 scheduleWritePackageRestrictionsLocked(userId); 13487 components = mPendingBroadcasts.get(userId, packageName); 13488 final boolean newPackage = components == null; 13489 if (newPackage) { 13490 components = new ArrayList<String>(); 13491 } 13492 if (!components.contains(componentName)) { 13493 components.add(componentName); 13494 } 13495 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13496 sendNow = true; 13497 // Purge entry from pending broadcast list if another one exists already 13498 // since we are sending one right away. 13499 mPendingBroadcasts.remove(userId, packageName); 13500 } else { 13501 if (newPackage) { 13502 mPendingBroadcasts.put(userId, packageName, components); 13503 } 13504 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13505 // Schedule a message 13506 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13507 } 13508 } 13509 } 13510 13511 long callingId = Binder.clearCallingIdentity(); 13512 try { 13513 if (sendNow) { 13514 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13515 sendPackageChangedBroadcast(packageName, 13516 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13517 } 13518 } finally { 13519 Binder.restoreCallingIdentity(callingId); 13520 } 13521 } 13522 13523 private void sendPackageChangedBroadcast(String packageName, 13524 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13525 if (DEBUG_INSTALL) 13526 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13527 + componentNames); 13528 Bundle extras = new Bundle(4); 13529 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13530 String nameList[] = new String[componentNames.size()]; 13531 componentNames.toArray(nameList); 13532 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13533 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13534 extras.putInt(Intent.EXTRA_UID, packageUid); 13535 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13536 new int[] {UserHandle.getUserId(packageUid)}); 13537 } 13538 13539 @Override 13540 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13541 if (!sUserManager.exists(userId)) return; 13542 final int uid = Binder.getCallingUid(); 13543 final int permission = mContext.checkCallingOrSelfPermission( 13544 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13545 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13546 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13547 // writer 13548 synchronized (mPackages) { 13549 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13550 allowedByPermission, uid, userId)) { 13551 scheduleWritePackageRestrictionsLocked(userId); 13552 } 13553 } 13554 } 13555 13556 @Override 13557 public String getInstallerPackageName(String packageName) { 13558 // reader 13559 synchronized (mPackages) { 13560 return mSettings.getInstallerPackageNameLPr(packageName); 13561 } 13562 } 13563 13564 @Override 13565 public int getApplicationEnabledSetting(String packageName, int userId) { 13566 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13567 int uid = Binder.getCallingUid(); 13568 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13569 // reader 13570 synchronized (mPackages) { 13571 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13572 } 13573 } 13574 13575 @Override 13576 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13577 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13578 int uid = Binder.getCallingUid(); 13579 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13580 // reader 13581 synchronized (mPackages) { 13582 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13583 } 13584 } 13585 13586 @Override 13587 public void enterSafeMode() { 13588 enforceSystemOrRoot("Only the system can request entering safe mode"); 13589 13590 if (!mSystemReady) { 13591 mSafeMode = true; 13592 } 13593 } 13594 13595 @Override 13596 public void systemReady() { 13597 mSystemReady = true; 13598 13599 // Read the compatibilty setting when the system is ready. 13600 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13601 mContext.getContentResolver(), 13602 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13603 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13604 if (DEBUG_SETTINGS) { 13605 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13606 } 13607 13608 synchronized (mPackages) { 13609 // Verify that all of the preferred activity components actually 13610 // exist. It is possible for applications to be updated and at 13611 // that point remove a previously declared activity component that 13612 // had been set as a preferred activity. We try to clean this up 13613 // the next time we encounter that preferred activity, but it is 13614 // possible for the user flow to never be able to return to that 13615 // situation so here we do a sanity check to make sure we haven't 13616 // left any junk around. 13617 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13618 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13619 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13620 removed.clear(); 13621 for (PreferredActivity pa : pir.filterSet()) { 13622 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13623 removed.add(pa); 13624 } 13625 } 13626 if (removed.size() > 0) { 13627 for (int r=0; r<removed.size(); r++) { 13628 PreferredActivity pa = removed.get(r); 13629 Slog.w(TAG, "Removing dangling preferred activity: " 13630 + pa.mPref.mComponent); 13631 pir.removeFilter(pa); 13632 } 13633 mSettings.writePackageRestrictionsLPr( 13634 mSettings.mPreferredActivities.keyAt(i)); 13635 } 13636 } 13637 } 13638 sUserManager.systemReady(); 13639 13640 // Kick off any messages waiting for system ready 13641 if (mPostSystemReadyMessages != null) { 13642 for (Message msg : mPostSystemReadyMessages) { 13643 msg.sendToTarget(); 13644 } 13645 mPostSystemReadyMessages = null; 13646 } 13647 13648 // Watch for external volumes that come and go over time 13649 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13650 storage.registerListener(mStorageListener); 13651 13652 mInstallerService.systemReady(); 13653 mPackageDexOptimizer.systemReady(); 13654 } 13655 13656 @Override 13657 public boolean isSafeMode() { 13658 return mSafeMode; 13659 } 13660 13661 @Override 13662 public boolean hasSystemUidErrors() { 13663 return mHasSystemUidErrors; 13664 } 13665 13666 static String arrayToString(int[] array) { 13667 StringBuffer buf = new StringBuffer(128); 13668 buf.append('['); 13669 if (array != null) { 13670 for (int i=0; i<array.length; i++) { 13671 if (i > 0) buf.append(", "); 13672 buf.append(array[i]); 13673 } 13674 } 13675 buf.append(']'); 13676 return buf.toString(); 13677 } 13678 13679 static class DumpState { 13680 public static final int DUMP_LIBS = 1 << 0; 13681 public static final int DUMP_FEATURES = 1 << 1; 13682 public static final int DUMP_RESOLVERS = 1 << 2; 13683 public static final int DUMP_PERMISSIONS = 1 << 3; 13684 public static final int DUMP_PACKAGES = 1 << 4; 13685 public static final int DUMP_SHARED_USERS = 1 << 5; 13686 public static final int DUMP_MESSAGES = 1 << 6; 13687 public static final int DUMP_PROVIDERS = 1 << 7; 13688 public static final int DUMP_VERIFIERS = 1 << 8; 13689 public static final int DUMP_PREFERRED = 1 << 9; 13690 public static final int DUMP_PREFERRED_XML = 1 << 10; 13691 public static final int DUMP_KEYSETS = 1 << 11; 13692 public static final int DUMP_VERSION = 1 << 12; 13693 public static final int DUMP_INSTALLS = 1 << 13; 13694 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13695 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13696 13697 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13698 13699 private int mTypes; 13700 13701 private int mOptions; 13702 13703 private boolean mTitlePrinted; 13704 13705 private SharedUserSetting mSharedUser; 13706 13707 public boolean isDumping(int type) { 13708 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13709 return true; 13710 } 13711 13712 return (mTypes & type) != 0; 13713 } 13714 13715 public void setDump(int type) { 13716 mTypes |= type; 13717 } 13718 13719 public boolean isOptionEnabled(int option) { 13720 return (mOptions & option) != 0; 13721 } 13722 13723 public void setOptionEnabled(int option) { 13724 mOptions |= option; 13725 } 13726 13727 public boolean onTitlePrinted() { 13728 final boolean printed = mTitlePrinted; 13729 mTitlePrinted = true; 13730 return printed; 13731 } 13732 13733 public boolean getTitlePrinted() { 13734 return mTitlePrinted; 13735 } 13736 13737 public void setTitlePrinted(boolean enabled) { 13738 mTitlePrinted = enabled; 13739 } 13740 13741 public SharedUserSetting getSharedUser() { 13742 return mSharedUser; 13743 } 13744 13745 public void setSharedUser(SharedUserSetting user) { 13746 mSharedUser = user; 13747 } 13748 } 13749 13750 @Override 13751 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13752 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13753 != PackageManager.PERMISSION_GRANTED) { 13754 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13755 + Binder.getCallingPid() 13756 + ", uid=" + Binder.getCallingUid() 13757 + " without permission " 13758 + android.Manifest.permission.DUMP); 13759 return; 13760 } 13761 13762 DumpState dumpState = new DumpState(); 13763 boolean fullPreferred = false; 13764 boolean checkin = false; 13765 13766 String packageName = null; 13767 13768 int opti = 0; 13769 while (opti < args.length) { 13770 String opt = args[opti]; 13771 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13772 break; 13773 } 13774 opti++; 13775 13776 if ("-a".equals(opt)) { 13777 // Right now we only know how to print all. 13778 } else if ("-h".equals(opt)) { 13779 pw.println("Package manager dump options:"); 13780 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13781 pw.println(" --checkin: dump for a checkin"); 13782 pw.println(" -f: print details of intent filters"); 13783 pw.println(" -h: print this help"); 13784 pw.println(" cmd may be one of:"); 13785 pw.println(" l[ibraries]: list known shared libraries"); 13786 pw.println(" f[ibraries]: list device features"); 13787 pw.println(" k[eysets]: print known keysets"); 13788 pw.println(" r[esolvers]: dump intent resolvers"); 13789 pw.println(" perm[issions]: dump permissions"); 13790 pw.println(" pref[erred]: print preferred package settings"); 13791 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13792 pw.println(" prov[iders]: dump content providers"); 13793 pw.println(" p[ackages]: dump installed packages"); 13794 pw.println(" s[hared-users]: dump shared user IDs"); 13795 pw.println(" m[essages]: print collected runtime messages"); 13796 pw.println(" v[erifiers]: print package verifier info"); 13797 pw.println(" version: print database version info"); 13798 pw.println(" write: write current settings now"); 13799 pw.println(" <package.name>: info about given package"); 13800 pw.println(" installs: details about install sessions"); 13801 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13802 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13803 return; 13804 } else if ("--checkin".equals(opt)) { 13805 checkin = true; 13806 } else if ("-f".equals(opt)) { 13807 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13808 } else { 13809 pw.println("Unknown argument: " + opt + "; use -h for help"); 13810 } 13811 } 13812 13813 // Is the caller requesting to dump a particular piece of data? 13814 if (opti < args.length) { 13815 String cmd = args[opti]; 13816 opti++; 13817 // Is this a package name? 13818 if ("android".equals(cmd) || cmd.contains(".")) { 13819 packageName = cmd; 13820 // When dumping a single package, we always dump all of its 13821 // filter information since the amount of data will be reasonable. 13822 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13823 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13824 dumpState.setDump(DumpState.DUMP_LIBS); 13825 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13826 dumpState.setDump(DumpState.DUMP_FEATURES); 13827 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13828 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13829 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13830 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13831 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13832 dumpState.setDump(DumpState.DUMP_PREFERRED); 13833 } else if ("preferred-xml".equals(cmd)) { 13834 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13835 if (opti < args.length && "--full".equals(args[opti])) { 13836 fullPreferred = true; 13837 opti++; 13838 } 13839 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13840 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13841 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13842 dumpState.setDump(DumpState.DUMP_PACKAGES); 13843 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13844 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13845 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13846 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13847 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13848 dumpState.setDump(DumpState.DUMP_MESSAGES); 13849 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13850 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13851 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13852 || "intent-filter-verifiers".equals(cmd)) { 13853 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13854 } else if ("version".equals(cmd)) { 13855 dumpState.setDump(DumpState.DUMP_VERSION); 13856 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13857 dumpState.setDump(DumpState.DUMP_KEYSETS); 13858 } else if ("installs".equals(cmd)) { 13859 dumpState.setDump(DumpState.DUMP_INSTALLS); 13860 } else if ("write".equals(cmd)) { 13861 synchronized (mPackages) { 13862 mSettings.writeLPr(); 13863 pw.println("Settings written."); 13864 return; 13865 } 13866 } 13867 } 13868 13869 if (checkin) { 13870 pw.println("vers,1"); 13871 } 13872 13873 // reader 13874 synchronized (mPackages) { 13875 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13876 if (!checkin) { 13877 if (dumpState.onTitlePrinted()) 13878 pw.println(); 13879 pw.println("Database versions:"); 13880 pw.print(" SDK Version:"); 13881 pw.print(" internal="); 13882 pw.print(mSettings.mInternalSdkPlatform); 13883 pw.print(" external="); 13884 pw.println(mSettings.mExternalSdkPlatform); 13885 pw.print(" DB Version:"); 13886 pw.print(" internal="); 13887 pw.print(mSettings.mInternalDatabaseVersion); 13888 pw.print(" external="); 13889 pw.println(mSettings.mExternalDatabaseVersion); 13890 } 13891 } 13892 13893 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13894 if (!checkin) { 13895 if (dumpState.onTitlePrinted()) 13896 pw.println(); 13897 pw.println("Verifiers:"); 13898 pw.print(" Required: "); 13899 pw.print(mRequiredVerifierPackage); 13900 pw.print(" (uid="); 13901 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13902 pw.println(")"); 13903 } else if (mRequiredVerifierPackage != null) { 13904 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13905 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13906 } 13907 } 13908 13909 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13910 packageName == null) { 13911 if (mIntentFilterVerifierComponent != null) { 13912 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13913 if (!checkin) { 13914 if (dumpState.onTitlePrinted()) 13915 pw.println(); 13916 pw.println("Intent Filter Verifier:"); 13917 pw.print(" Using: "); 13918 pw.print(verifierPackageName); 13919 pw.print(" (uid="); 13920 pw.print(getPackageUid(verifierPackageName, 0)); 13921 pw.println(")"); 13922 } else if (verifierPackageName != null) { 13923 pw.print("ifv,"); pw.print(verifierPackageName); 13924 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13925 } 13926 } else { 13927 pw.println(); 13928 pw.println("No Intent Filter Verifier available!"); 13929 } 13930 } 13931 13932 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13933 boolean printedHeader = false; 13934 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13935 while (it.hasNext()) { 13936 String name = it.next(); 13937 SharedLibraryEntry ent = mSharedLibraries.get(name); 13938 if (!checkin) { 13939 if (!printedHeader) { 13940 if (dumpState.onTitlePrinted()) 13941 pw.println(); 13942 pw.println("Libraries:"); 13943 printedHeader = true; 13944 } 13945 pw.print(" "); 13946 } else { 13947 pw.print("lib,"); 13948 } 13949 pw.print(name); 13950 if (!checkin) { 13951 pw.print(" -> "); 13952 } 13953 if (ent.path != null) { 13954 if (!checkin) { 13955 pw.print("(jar) "); 13956 pw.print(ent.path); 13957 } else { 13958 pw.print(",jar,"); 13959 pw.print(ent.path); 13960 } 13961 } else { 13962 if (!checkin) { 13963 pw.print("(apk) "); 13964 pw.print(ent.apk); 13965 } else { 13966 pw.print(",apk,"); 13967 pw.print(ent.apk); 13968 } 13969 } 13970 pw.println(); 13971 } 13972 } 13973 13974 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 13975 if (dumpState.onTitlePrinted()) 13976 pw.println(); 13977 if (!checkin) { 13978 pw.println("Features:"); 13979 } 13980 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 13981 while (it.hasNext()) { 13982 String name = it.next(); 13983 if (!checkin) { 13984 pw.print(" "); 13985 } else { 13986 pw.print("feat,"); 13987 } 13988 pw.println(name); 13989 } 13990 } 13991 13992 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 13993 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 13994 : "Activity Resolver Table:", " ", packageName, 13995 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 13996 dumpState.setTitlePrinted(true); 13997 } 13998 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 13999 : "Receiver Resolver Table:", " ", packageName, 14000 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14001 dumpState.setTitlePrinted(true); 14002 } 14003 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14004 : "Service Resolver Table:", " ", packageName, 14005 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14006 dumpState.setTitlePrinted(true); 14007 } 14008 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14009 : "Provider Resolver Table:", " ", packageName, 14010 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14011 dumpState.setTitlePrinted(true); 14012 } 14013 } 14014 14015 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14016 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14017 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14018 int user = mSettings.mPreferredActivities.keyAt(i); 14019 if (pir.dump(pw, 14020 dumpState.getTitlePrinted() 14021 ? "\nPreferred Activities User " + user + ":" 14022 : "Preferred Activities User " + user + ":", " ", 14023 packageName, true, false)) { 14024 dumpState.setTitlePrinted(true); 14025 } 14026 } 14027 } 14028 14029 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14030 pw.flush(); 14031 FileOutputStream fout = new FileOutputStream(fd); 14032 BufferedOutputStream str = new BufferedOutputStream(fout); 14033 XmlSerializer serializer = new FastXmlSerializer(); 14034 try { 14035 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14036 serializer.startDocument(null, true); 14037 serializer.setFeature( 14038 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14039 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14040 serializer.endDocument(); 14041 serializer.flush(); 14042 } catch (IllegalArgumentException e) { 14043 pw.println("Failed writing: " + e); 14044 } catch (IllegalStateException e) { 14045 pw.println("Failed writing: " + e); 14046 } catch (IOException e) { 14047 pw.println("Failed writing: " + e); 14048 } 14049 } 14050 14051 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 14052 pw.println(); 14053 int count = mSettings.mPackages.size(); 14054 if (count == 0) { 14055 pw.println("No domain preferred apps!"); 14056 pw.println(); 14057 } else { 14058 final String prefix = " "; 14059 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14060 if (allPackageSettings.size() == 0) { 14061 pw.println("No domain preferred apps!"); 14062 pw.println(); 14063 } else { 14064 pw.println("Domain preferred apps status:"); 14065 pw.println(); 14066 count = 0; 14067 for (PackageSetting ps : allPackageSettings) { 14068 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14069 if (ivi == null || ivi.getPackageName() == null) continue; 14070 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14071 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14072 pw.println(prefix + "Status: " + ivi.getStatusString()); 14073 pw.println(); 14074 count++; 14075 } 14076 if (count == 0) { 14077 pw.println(prefix + "No domain preferred app status!"); 14078 pw.println(); 14079 } 14080 for (int userId : sUserManager.getUserIds()) { 14081 pw.println("Domain preferred apps for User " + userId + ":"); 14082 pw.println(); 14083 count = 0; 14084 for (PackageSetting ps : allPackageSettings) { 14085 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14086 if (ivi == null || ivi.getPackageName() == null) { 14087 continue; 14088 } 14089 final int status = ps.getDomainVerificationStatusForUser(userId); 14090 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14091 continue; 14092 } 14093 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14094 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14095 String statusStr = IntentFilterVerificationInfo. 14096 getStatusStringFromValue(status); 14097 pw.println(prefix + "Status: " + statusStr); 14098 pw.println(); 14099 count++; 14100 } 14101 if (count == 0) { 14102 pw.println(prefix + "No domain preferred apps!"); 14103 pw.println(); 14104 } 14105 } 14106 } 14107 } 14108 } 14109 14110 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14111 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14112 if (packageName == null) { 14113 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14114 if (iperm == 0) { 14115 if (dumpState.onTitlePrinted()) 14116 pw.println(); 14117 pw.println("AppOp Permissions:"); 14118 } 14119 pw.print(" AppOp Permission "); 14120 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14121 pw.println(":"); 14122 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14123 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14124 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14125 } 14126 } 14127 } 14128 } 14129 14130 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14131 boolean printedSomething = false; 14132 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14133 if (packageName != null && !packageName.equals(p.info.packageName)) { 14134 continue; 14135 } 14136 if (!printedSomething) { 14137 if (dumpState.onTitlePrinted()) 14138 pw.println(); 14139 pw.println("Registered ContentProviders:"); 14140 printedSomething = true; 14141 } 14142 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14143 pw.print(" "); pw.println(p.toString()); 14144 } 14145 printedSomething = false; 14146 for (Map.Entry<String, PackageParser.Provider> entry : 14147 mProvidersByAuthority.entrySet()) { 14148 PackageParser.Provider p = entry.getValue(); 14149 if (packageName != null && !packageName.equals(p.info.packageName)) { 14150 continue; 14151 } 14152 if (!printedSomething) { 14153 if (dumpState.onTitlePrinted()) 14154 pw.println(); 14155 pw.println("ContentProvider Authorities:"); 14156 printedSomething = true; 14157 } 14158 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14159 pw.print(" "); pw.println(p.toString()); 14160 if (p.info != null && p.info.applicationInfo != null) { 14161 final String appInfo = p.info.applicationInfo.toString(); 14162 pw.print(" applicationInfo="); pw.println(appInfo); 14163 } 14164 } 14165 } 14166 14167 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14168 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14169 } 14170 14171 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14172 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14173 } 14174 14175 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14176 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14177 } 14178 14179 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14180 // XXX should handle packageName != null by dumping only install data that 14181 // the given package is involved with. 14182 if (dumpState.onTitlePrinted()) pw.println(); 14183 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14184 } 14185 14186 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14187 if (dumpState.onTitlePrinted()) pw.println(); 14188 mSettings.dumpReadMessagesLPr(pw, dumpState); 14189 14190 pw.println(); 14191 pw.println("Package warning messages:"); 14192 BufferedReader in = null; 14193 String line = null; 14194 try { 14195 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14196 while ((line = in.readLine()) != null) { 14197 if (line.contains("ignored: updated version")) continue; 14198 pw.println(line); 14199 } 14200 } catch (IOException ignored) { 14201 } finally { 14202 IoUtils.closeQuietly(in); 14203 } 14204 } 14205 14206 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14207 BufferedReader in = null; 14208 String line = null; 14209 try { 14210 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14211 while ((line = in.readLine()) != null) { 14212 if (line.contains("ignored: updated version")) continue; 14213 pw.print("msg,"); 14214 pw.println(line); 14215 } 14216 } catch (IOException ignored) { 14217 } finally { 14218 IoUtils.closeQuietly(in); 14219 } 14220 } 14221 } 14222 } 14223 14224 // ------- apps on sdcard specific code ------- 14225 static final boolean DEBUG_SD_INSTALL = false; 14226 14227 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14228 14229 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14230 14231 private boolean mMediaMounted = false; 14232 14233 static String getEncryptKey() { 14234 try { 14235 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14236 SD_ENCRYPTION_KEYSTORE_NAME); 14237 if (sdEncKey == null) { 14238 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14239 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14240 if (sdEncKey == null) { 14241 Slog.e(TAG, "Failed to create encryption keys"); 14242 return null; 14243 } 14244 } 14245 return sdEncKey; 14246 } catch (NoSuchAlgorithmException nsae) { 14247 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14248 return null; 14249 } catch (IOException ioe) { 14250 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14251 return null; 14252 } 14253 } 14254 14255 /* 14256 * Update media status on PackageManager. 14257 */ 14258 @Override 14259 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14260 int callingUid = Binder.getCallingUid(); 14261 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14262 throw new SecurityException("Media status can only be updated by the system"); 14263 } 14264 // reader; this apparently protects mMediaMounted, but should probably 14265 // be a different lock in that case. 14266 synchronized (mPackages) { 14267 Log.i(TAG, "Updating external media status from " 14268 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14269 + (mediaStatus ? "mounted" : "unmounted")); 14270 if (DEBUG_SD_INSTALL) 14271 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14272 + ", mMediaMounted=" + mMediaMounted); 14273 if (mediaStatus == mMediaMounted) { 14274 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14275 : 0, -1); 14276 mHandler.sendMessage(msg); 14277 return; 14278 } 14279 mMediaMounted = mediaStatus; 14280 } 14281 // Queue up an async operation since the package installation may take a 14282 // little while. 14283 mHandler.post(new Runnable() { 14284 public void run() { 14285 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14286 } 14287 }); 14288 } 14289 14290 /** 14291 * Called by MountService when the initial ASECs to scan are available. 14292 * Should block until all the ASEC containers are finished being scanned. 14293 */ 14294 public void scanAvailableAsecs() { 14295 updateExternalMediaStatusInner(true, false, false); 14296 if (mShouldRestoreconData) { 14297 SELinuxMMAC.setRestoreconDone(); 14298 mShouldRestoreconData = false; 14299 } 14300 } 14301 14302 /* 14303 * Collect information of applications on external media, map them against 14304 * existing containers and update information based on current mount status. 14305 * Please note that we always have to report status if reportStatus has been 14306 * set to true especially when unloading packages. 14307 */ 14308 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14309 boolean externalStorage) { 14310 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14311 int[] uidArr = EmptyArray.INT; 14312 14313 final String[] list = PackageHelper.getSecureContainerList(); 14314 if (ArrayUtils.isEmpty(list)) { 14315 Log.i(TAG, "No secure containers found"); 14316 } else { 14317 // Process list of secure containers and categorize them 14318 // as active or stale based on their package internal state. 14319 14320 // reader 14321 synchronized (mPackages) { 14322 for (String cid : list) { 14323 // Leave stages untouched for now; installer service owns them 14324 if (PackageInstallerService.isStageName(cid)) continue; 14325 14326 if (DEBUG_SD_INSTALL) 14327 Log.i(TAG, "Processing container " + cid); 14328 String pkgName = getAsecPackageName(cid); 14329 if (pkgName == null) { 14330 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14331 continue; 14332 } 14333 if (DEBUG_SD_INSTALL) 14334 Log.i(TAG, "Looking for pkg : " + pkgName); 14335 14336 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14337 if (ps == null) { 14338 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14339 continue; 14340 } 14341 14342 /* 14343 * Skip packages that are not external if we're unmounting 14344 * external storage. 14345 */ 14346 if (externalStorage && !isMounted && !isExternal(ps)) { 14347 continue; 14348 } 14349 14350 final AsecInstallArgs args = new AsecInstallArgs(cid, 14351 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14352 // The package status is changed only if the code path 14353 // matches between settings and the container id. 14354 if (ps.codePathString != null 14355 && ps.codePathString.startsWith(args.getCodePath())) { 14356 if (DEBUG_SD_INSTALL) { 14357 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14358 + " at code path: " + ps.codePathString); 14359 } 14360 14361 // We do have a valid package installed on sdcard 14362 processCids.put(args, ps.codePathString); 14363 final int uid = ps.appId; 14364 if (uid != -1) { 14365 uidArr = ArrayUtils.appendInt(uidArr, uid); 14366 } 14367 } else { 14368 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14369 + ps.codePathString); 14370 } 14371 } 14372 } 14373 14374 Arrays.sort(uidArr); 14375 } 14376 14377 // Process packages with valid entries. 14378 if (isMounted) { 14379 if (DEBUG_SD_INSTALL) 14380 Log.i(TAG, "Loading packages"); 14381 loadMediaPackages(processCids, uidArr); 14382 startCleaningPackages(); 14383 mInstallerService.onSecureContainersAvailable(); 14384 } else { 14385 if (DEBUG_SD_INSTALL) 14386 Log.i(TAG, "Unloading packages"); 14387 unloadMediaPackages(processCids, uidArr, reportStatus); 14388 } 14389 } 14390 14391 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14392 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14393 final int size = infos.size(); 14394 final String[] packageNames = new String[size]; 14395 final int[] packageUids = new int[size]; 14396 for (int i = 0; i < size; i++) { 14397 final ApplicationInfo info = infos.get(i); 14398 packageNames[i] = info.packageName; 14399 packageUids[i] = info.uid; 14400 } 14401 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14402 finishedReceiver); 14403 } 14404 14405 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14406 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14407 sendResourcesChangedBroadcast(mediaStatus, replacing, 14408 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14409 } 14410 14411 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14412 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14413 int size = pkgList.length; 14414 if (size > 0) { 14415 // Send broadcasts here 14416 Bundle extras = new Bundle(); 14417 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14418 if (uidArr != null) { 14419 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14420 } 14421 if (replacing) { 14422 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14423 } 14424 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14425 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14426 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14427 } 14428 } 14429 14430 /* 14431 * Look at potentially valid container ids from processCids If package 14432 * information doesn't match the one on record or package scanning fails, 14433 * the cid is added to list of removeCids. We currently don't delete stale 14434 * containers. 14435 */ 14436 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14437 ArrayList<String> pkgList = new ArrayList<String>(); 14438 Set<AsecInstallArgs> keys = processCids.keySet(); 14439 14440 for (AsecInstallArgs args : keys) { 14441 String codePath = processCids.get(args); 14442 if (DEBUG_SD_INSTALL) 14443 Log.i(TAG, "Loading container : " + args.cid); 14444 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14445 try { 14446 // Make sure there are no container errors first. 14447 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14448 Slog.e(TAG, "Failed to mount cid : " + args.cid 14449 + " when installing from sdcard"); 14450 continue; 14451 } 14452 // Check code path here. 14453 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14454 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14455 + " does not match one in settings " + codePath); 14456 continue; 14457 } 14458 // Parse package 14459 int parseFlags = mDefParseFlags; 14460 if (args.isExternalAsec()) { 14461 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14462 } 14463 if (args.isFwdLocked()) { 14464 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14465 } 14466 14467 synchronized (mInstallLock) { 14468 PackageParser.Package pkg = null; 14469 try { 14470 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14471 } catch (PackageManagerException e) { 14472 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14473 } 14474 // Scan the package 14475 if (pkg != null) { 14476 /* 14477 * TODO why is the lock being held? doPostInstall is 14478 * called in other places without the lock. This needs 14479 * to be straightened out. 14480 */ 14481 // writer 14482 synchronized (mPackages) { 14483 retCode = PackageManager.INSTALL_SUCCEEDED; 14484 pkgList.add(pkg.packageName); 14485 // Post process args 14486 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14487 pkg.applicationInfo.uid); 14488 } 14489 } else { 14490 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14491 } 14492 } 14493 14494 } finally { 14495 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14496 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14497 } 14498 } 14499 } 14500 // writer 14501 synchronized (mPackages) { 14502 // If the platform SDK has changed since the last time we booted, 14503 // we need to re-grant app permission to catch any new ones that 14504 // appear. This is really a hack, and means that apps can in some 14505 // cases get permissions that the user didn't initially explicitly 14506 // allow... it would be nice to have some better way to handle 14507 // this situation. 14508 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14509 if (regrantPermissions) 14510 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14511 + mSdkVersion + "; regranting permissions for external storage"); 14512 mSettings.mExternalSdkPlatform = mSdkVersion; 14513 14514 // Make sure group IDs have been assigned, and any permission 14515 // changes in other apps are accounted for 14516 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14517 | (regrantPermissions 14518 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14519 : 0)); 14520 14521 mSettings.updateExternalDatabaseVersion(); 14522 14523 // can downgrade to reader 14524 // Persist settings 14525 mSettings.writeLPr(); 14526 } 14527 // Send a broadcast to let everyone know we are done processing 14528 if (pkgList.size() > 0) { 14529 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14530 } 14531 } 14532 14533 /* 14534 * Utility method to unload a list of specified containers 14535 */ 14536 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14537 // Just unmount all valid containers. 14538 for (AsecInstallArgs arg : cidArgs) { 14539 synchronized (mInstallLock) { 14540 arg.doPostDeleteLI(false); 14541 } 14542 } 14543 } 14544 14545 /* 14546 * Unload packages mounted on external media. This involves deleting package 14547 * data from internal structures, sending broadcasts about diabled packages, 14548 * gc'ing to free up references, unmounting all secure containers 14549 * corresponding to packages on external media, and posting a 14550 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14551 * that we always have to post this message if status has been requested no 14552 * matter what. 14553 */ 14554 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14555 final boolean reportStatus) { 14556 if (DEBUG_SD_INSTALL) 14557 Log.i(TAG, "unloading media packages"); 14558 ArrayList<String> pkgList = new ArrayList<String>(); 14559 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14560 final Set<AsecInstallArgs> keys = processCids.keySet(); 14561 for (AsecInstallArgs args : keys) { 14562 String pkgName = args.getPackageName(); 14563 if (DEBUG_SD_INSTALL) 14564 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14565 // Delete package internally 14566 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14567 synchronized (mInstallLock) { 14568 boolean res = deletePackageLI(pkgName, null, false, null, null, 14569 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14570 if (res) { 14571 pkgList.add(pkgName); 14572 } else { 14573 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14574 failedList.add(args); 14575 } 14576 } 14577 } 14578 14579 // reader 14580 synchronized (mPackages) { 14581 // We didn't update the settings after removing each package; 14582 // write them now for all packages. 14583 mSettings.writeLPr(); 14584 } 14585 14586 // We have to absolutely send UPDATED_MEDIA_STATUS only 14587 // after confirming that all the receivers processed the ordered 14588 // broadcast when packages get disabled, force a gc to clean things up. 14589 // and unload all the containers. 14590 if (pkgList.size() > 0) { 14591 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14592 new IIntentReceiver.Stub() { 14593 public void performReceive(Intent intent, int resultCode, String data, 14594 Bundle extras, boolean ordered, boolean sticky, 14595 int sendingUser) throws RemoteException { 14596 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14597 reportStatus ? 1 : 0, 1, keys); 14598 mHandler.sendMessage(msg); 14599 } 14600 }); 14601 } else { 14602 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14603 keys); 14604 mHandler.sendMessage(msg); 14605 } 14606 } 14607 14608 private void loadPrivatePackages(VolumeInfo vol) { 14609 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14610 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14611 synchronized (mInstallLock) { 14612 synchronized (mPackages) { 14613 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14614 for (PackageSetting ps : packages) { 14615 final PackageParser.Package pkg; 14616 try { 14617 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14618 loaded.add(pkg.applicationInfo); 14619 } catch (PackageManagerException e) { 14620 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14621 } 14622 } 14623 14624 // TODO: regrant any permissions that changed based since original install 14625 14626 mSettings.writeLPr(); 14627 } 14628 } 14629 14630 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14631 sendResourcesChangedBroadcast(true, false, loaded, null); 14632 } 14633 14634 private void unloadPrivatePackages(VolumeInfo vol) { 14635 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14636 synchronized (mInstallLock) { 14637 synchronized (mPackages) { 14638 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14639 for (PackageSetting ps : packages) { 14640 if (ps.pkg == null) continue; 14641 14642 final ApplicationInfo info = ps.pkg.applicationInfo; 14643 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14644 if (deletePackageLI(ps.name, null, false, null, null, 14645 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14646 unloaded.add(info); 14647 } else { 14648 Slog.w(TAG, "Failed to unload " + ps.codePath); 14649 } 14650 } 14651 14652 mSettings.writeLPr(); 14653 } 14654 } 14655 14656 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14657 sendResourcesChangedBroadcast(false, false, unloaded, null); 14658 } 14659 14660 private void unfreezePackage(String packageName) { 14661 synchronized (mPackages) { 14662 final PackageSetting ps = mSettings.mPackages.get(packageName); 14663 if (ps != null) { 14664 ps.frozen = false; 14665 } 14666 } 14667 } 14668 14669 @Override 14670 public int movePackage(final String packageName, final String volumeUuid) { 14671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14672 14673 final int moveId = mNextMoveId.getAndIncrement(); 14674 try { 14675 movePackageInternal(packageName, volumeUuid, moveId); 14676 } catch (PackageManagerException e) { 14677 Slog.w(TAG, "Failed to move " + packageName, e); 14678 mMoveCallbacks.notifyStatusChanged(moveId, 14679 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14680 } 14681 return moveId; 14682 } 14683 14684 private void movePackageInternal(final String packageName, final String volumeUuid, 14685 final int moveId) throws PackageManagerException { 14686 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14687 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14688 final PackageManager pm = mContext.getPackageManager(); 14689 14690 final boolean currentAsec; 14691 final String currentVolumeUuid; 14692 final File codeFile; 14693 final String installerPackageName; 14694 final String packageAbiOverride; 14695 final int appId; 14696 final String seinfo; 14697 final String label; 14698 14699 // reader 14700 synchronized (mPackages) { 14701 final PackageParser.Package pkg = mPackages.get(packageName); 14702 final PackageSetting ps = mSettings.mPackages.get(packageName); 14703 if (pkg == null || ps == null) { 14704 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14705 } 14706 14707 if (pkg.applicationInfo.isSystemApp()) { 14708 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14709 "Cannot move system application"); 14710 } 14711 14712 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14713 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14714 "Package already moved to " + volumeUuid); 14715 } 14716 14717 final File probe = new File(pkg.codePath); 14718 final File probeOat = new File(probe, "oat"); 14719 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14720 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14721 "Move only supported for modern cluster style installs"); 14722 } 14723 14724 if (ps.frozen) { 14725 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14726 "Failed to move already frozen package"); 14727 } 14728 ps.frozen = true; 14729 14730 currentAsec = pkg.applicationInfo.isForwardLocked() 14731 || pkg.applicationInfo.isExternalAsec(); 14732 currentVolumeUuid = ps.volumeUuid; 14733 codeFile = new File(pkg.codePath); 14734 installerPackageName = ps.installerPackageName; 14735 packageAbiOverride = ps.cpuAbiOverrideString; 14736 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14737 seinfo = pkg.applicationInfo.seinfo; 14738 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14739 } 14740 14741 // Now that we're guarded by frozen state, kill app during move 14742 killApplication(packageName, appId, "move pkg"); 14743 14744 final Bundle extras = new Bundle(); 14745 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14746 extras.putString(Intent.EXTRA_TITLE, label); 14747 mMoveCallbacks.notifyCreated(moveId, extras); 14748 14749 int installFlags; 14750 final boolean moveCompleteApp; 14751 final File measurePath; 14752 14753 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14754 installFlags = INSTALL_INTERNAL; 14755 moveCompleteApp = !currentAsec; 14756 measurePath = Environment.getDataAppDirectory(volumeUuid); 14757 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14758 installFlags = INSTALL_EXTERNAL; 14759 moveCompleteApp = false; 14760 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14761 } else { 14762 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14763 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14764 || !volume.isMountedWritable()) { 14765 unfreezePackage(packageName); 14766 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14767 "Move location not mounted private volume"); 14768 } 14769 14770 Preconditions.checkState(!currentAsec); 14771 14772 installFlags = INSTALL_INTERNAL; 14773 moveCompleteApp = true; 14774 measurePath = Environment.getDataAppDirectory(volumeUuid); 14775 } 14776 14777 final PackageStats stats = new PackageStats(null, -1); 14778 synchronized (mInstaller) { 14779 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14780 unfreezePackage(packageName); 14781 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14782 "Failed to measure package size"); 14783 } 14784 } 14785 14786 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14787 + stats.dataSize); 14788 14789 final long startFreeBytes = measurePath.getFreeSpace(); 14790 final long sizeBytes; 14791 if (moveCompleteApp) { 14792 sizeBytes = stats.codeSize + stats.dataSize; 14793 } else { 14794 sizeBytes = stats.codeSize; 14795 } 14796 14797 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14798 unfreezePackage(packageName); 14799 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14800 "Not enough free space to move"); 14801 } 14802 14803 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14804 14805 final CountDownLatch installedLatch = new CountDownLatch(1); 14806 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14807 @Override 14808 public void onUserActionRequired(Intent intent) throws RemoteException { 14809 throw new IllegalStateException(); 14810 } 14811 14812 @Override 14813 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14814 Bundle extras) throws RemoteException { 14815 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14816 + PackageManager.installStatusToString(returnCode, msg)); 14817 14818 installedLatch.countDown(); 14819 14820 // Regardless of success or failure of the move operation, 14821 // always unfreeze the package 14822 unfreezePackage(packageName); 14823 14824 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14825 switch (status) { 14826 case PackageInstaller.STATUS_SUCCESS: 14827 mMoveCallbacks.notifyStatusChanged(moveId, 14828 PackageManager.MOVE_SUCCEEDED); 14829 break; 14830 case PackageInstaller.STATUS_FAILURE_STORAGE: 14831 mMoveCallbacks.notifyStatusChanged(moveId, 14832 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14833 break; 14834 default: 14835 mMoveCallbacks.notifyStatusChanged(moveId, 14836 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14837 break; 14838 } 14839 } 14840 }; 14841 14842 final MoveInfo move; 14843 if (moveCompleteApp) { 14844 // Kick off a thread to report progress estimates 14845 new Thread() { 14846 @Override 14847 public void run() { 14848 while (true) { 14849 try { 14850 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14851 break; 14852 } 14853 } catch (InterruptedException ignored) { 14854 } 14855 14856 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14857 final int progress = 10 + (int) MathUtils.constrain( 14858 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14859 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14860 } 14861 } 14862 }.start(); 14863 14864 final String dataAppName = codeFile.getName(); 14865 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14866 dataAppName, appId, seinfo); 14867 } else { 14868 move = null; 14869 } 14870 14871 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14872 14873 final Message msg = mHandler.obtainMessage(INIT_COPY); 14874 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14875 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14876 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14877 mHandler.sendMessage(msg); 14878 } 14879 14880 @Override 14881 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14882 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14883 14884 final int realMoveId = mNextMoveId.getAndIncrement(); 14885 final Bundle extras = new Bundle(); 14886 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14887 mMoveCallbacks.notifyCreated(realMoveId, extras); 14888 14889 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14890 @Override 14891 public void onCreated(int moveId, Bundle extras) { 14892 // Ignored 14893 } 14894 14895 @Override 14896 public void onStatusChanged(int moveId, int status, long estMillis) { 14897 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14898 } 14899 }; 14900 14901 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14902 storage.setPrimaryStorageUuid(volumeUuid, callback); 14903 return realMoveId; 14904 } 14905 14906 @Override 14907 public int getMoveStatus(int moveId) { 14908 mContext.enforceCallingOrSelfPermission( 14909 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14910 return mMoveCallbacks.mLastStatus.get(moveId); 14911 } 14912 14913 @Override 14914 public void registerMoveCallback(IPackageMoveObserver callback) { 14915 mContext.enforceCallingOrSelfPermission( 14916 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14917 mMoveCallbacks.register(callback); 14918 } 14919 14920 @Override 14921 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14922 mContext.enforceCallingOrSelfPermission( 14923 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14924 mMoveCallbacks.unregister(callback); 14925 } 14926 14927 @Override 14928 public boolean setInstallLocation(int loc) { 14929 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14930 null); 14931 if (getInstallLocation() == loc) { 14932 return true; 14933 } 14934 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14935 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14936 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14937 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14938 return true; 14939 } 14940 return false; 14941 } 14942 14943 @Override 14944 public int getInstallLocation() { 14945 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14946 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14947 PackageHelper.APP_INSTALL_AUTO); 14948 } 14949 14950 /** Called by UserManagerService */ 14951 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14952 mDirtyUsers.remove(userHandle); 14953 mSettings.removeUserLPw(userHandle); 14954 mPendingBroadcasts.remove(userHandle); 14955 if (mInstaller != null) { 14956 // Technically, we shouldn't be doing this with the package lock 14957 // held. However, this is very rare, and there is already so much 14958 // other disk I/O going on, that we'll let it slide for now. 14959 final StorageManager storage = StorageManager.from(mContext); 14960 final List<VolumeInfo> vols = storage.getVolumes(); 14961 for (VolumeInfo vol : vols) { 14962 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 14963 final String volumeUuid = vol.getFsUuid(); 14964 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 14965 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 14966 } 14967 } 14968 } 14969 mUserNeedsBadging.delete(userHandle); 14970 removeUnusedPackagesLILPw(userManager, userHandle); 14971 } 14972 14973 /** 14974 * We're removing userHandle and would like to remove any downloaded packages 14975 * that are no longer in use by any other user. 14976 * @param userHandle the user being removed 14977 */ 14978 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 14979 final boolean DEBUG_CLEAN_APKS = false; 14980 int [] users = userManager.getUserIdsLPr(); 14981 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 14982 while (psit.hasNext()) { 14983 PackageSetting ps = psit.next(); 14984 if (ps.pkg == null) { 14985 continue; 14986 } 14987 final String packageName = ps.pkg.packageName; 14988 // Skip over if system app 14989 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14990 continue; 14991 } 14992 if (DEBUG_CLEAN_APKS) { 14993 Slog.i(TAG, "Checking package " + packageName); 14994 } 14995 boolean keep = false; 14996 for (int i = 0; i < users.length; i++) { 14997 if (users[i] != userHandle && ps.getInstalled(users[i])) { 14998 keep = true; 14999 if (DEBUG_CLEAN_APKS) { 15000 Slog.i(TAG, " Keeping package " + packageName + " for user " 15001 + users[i]); 15002 } 15003 break; 15004 } 15005 } 15006 if (!keep) { 15007 if (DEBUG_CLEAN_APKS) { 15008 Slog.i(TAG, " Removing package " + packageName); 15009 } 15010 mHandler.post(new Runnable() { 15011 public void run() { 15012 deletePackageX(packageName, userHandle, 0); 15013 } //end run 15014 }); 15015 } 15016 } 15017 } 15018 15019 /** Called by UserManagerService */ 15020 void createNewUserLILPw(int userHandle, File path) { 15021 if (mInstaller != null) { 15022 mInstaller.createUserConfig(userHandle); 15023 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15024 } 15025 } 15026 15027 void newUserCreatedLILPw(int userHandle) { 15028 // Adding a user requires updating runtime permissions for system apps. 15029 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 15030 } 15031 15032 @Override 15033 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15034 mContext.enforceCallingOrSelfPermission( 15035 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15036 "Only package verification agents can read the verifier device identity"); 15037 15038 synchronized (mPackages) { 15039 return mSettings.getVerifierDeviceIdentityLPw(); 15040 } 15041 } 15042 15043 @Override 15044 public void setPermissionEnforced(String permission, boolean enforced) { 15045 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15046 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15047 synchronized (mPackages) { 15048 if (mSettings.mReadExternalStorageEnforced == null 15049 || mSettings.mReadExternalStorageEnforced != enforced) { 15050 mSettings.mReadExternalStorageEnforced = enforced; 15051 mSettings.writeLPr(); 15052 } 15053 } 15054 // kill any non-foreground processes so we restart them and 15055 // grant/revoke the GID. 15056 final IActivityManager am = ActivityManagerNative.getDefault(); 15057 if (am != null) { 15058 final long token = Binder.clearCallingIdentity(); 15059 try { 15060 am.killProcessesBelowForeground("setPermissionEnforcement"); 15061 } catch (RemoteException e) { 15062 } finally { 15063 Binder.restoreCallingIdentity(token); 15064 } 15065 } 15066 } else { 15067 throw new IllegalArgumentException("No selective enforcement for " + permission); 15068 } 15069 } 15070 15071 @Override 15072 @Deprecated 15073 public boolean isPermissionEnforced(String permission) { 15074 return true; 15075 } 15076 15077 @Override 15078 public boolean isStorageLow() { 15079 final long token = Binder.clearCallingIdentity(); 15080 try { 15081 final DeviceStorageMonitorInternal 15082 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15083 if (dsm != null) { 15084 return dsm.isMemoryLow(); 15085 } else { 15086 return false; 15087 } 15088 } finally { 15089 Binder.restoreCallingIdentity(token); 15090 } 15091 } 15092 15093 @Override 15094 public IPackageInstaller getPackageInstaller() { 15095 return mInstallerService; 15096 } 15097 15098 private boolean userNeedsBadging(int userId) { 15099 int index = mUserNeedsBadging.indexOfKey(userId); 15100 if (index < 0) { 15101 final UserInfo userInfo; 15102 final long token = Binder.clearCallingIdentity(); 15103 try { 15104 userInfo = sUserManager.getUserInfo(userId); 15105 } finally { 15106 Binder.restoreCallingIdentity(token); 15107 } 15108 final boolean b; 15109 if (userInfo != null && userInfo.isManagedProfile()) { 15110 b = true; 15111 } else { 15112 b = false; 15113 } 15114 mUserNeedsBadging.put(userId, b); 15115 return b; 15116 } 15117 return mUserNeedsBadging.valueAt(index); 15118 } 15119 15120 @Override 15121 public KeySet getKeySetByAlias(String packageName, String alias) { 15122 if (packageName == null || alias == null) { 15123 return null; 15124 } 15125 synchronized(mPackages) { 15126 final PackageParser.Package pkg = mPackages.get(packageName); 15127 if (pkg == null) { 15128 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15129 throw new IllegalArgumentException("Unknown package: " + packageName); 15130 } 15131 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15132 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15133 } 15134 } 15135 15136 @Override 15137 public KeySet getSigningKeySet(String packageName) { 15138 if (packageName == null) { 15139 return null; 15140 } 15141 synchronized(mPackages) { 15142 final PackageParser.Package pkg = mPackages.get(packageName); 15143 if (pkg == null) { 15144 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15145 throw new IllegalArgumentException("Unknown package: " + packageName); 15146 } 15147 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15148 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15149 throw new SecurityException("May not access signing KeySet of other apps."); 15150 } 15151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15152 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15153 } 15154 } 15155 15156 @Override 15157 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15158 if (packageName == null || ks == null) { 15159 return false; 15160 } 15161 synchronized(mPackages) { 15162 final PackageParser.Package pkg = mPackages.get(packageName); 15163 if (pkg == null) { 15164 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15165 throw new IllegalArgumentException("Unknown package: " + packageName); 15166 } 15167 IBinder ksh = ks.getToken(); 15168 if (ksh instanceof KeySetHandle) { 15169 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15170 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15171 } 15172 return false; 15173 } 15174 } 15175 15176 @Override 15177 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15178 if (packageName == null || ks == null) { 15179 return false; 15180 } 15181 synchronized(mPackages) { 15182 final PackageParser.Package pkg = mPackages.get(packageName); 15183 if (pkg == null) { 15184 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15185 throw new IllegalArgumentException("Unknown package: " + packageName); 15186 } 15187 IBinder ksh = ks.getToken(); 15188 if (ksh instanceof KeySetHandle) { 15189 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15190 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15191 } 15192 return false; 15193 } 15194 } 15195 15196 public void getUsageStatsIfNoPackageUsageInfo() { 15197 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15198 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15199 if (usm == null) { 15200 throw new IllegalStateException("UsageStatsManager must be initialized"); 15201 } 15202 long now = System.currentTimeMillis(); 15203 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15204 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15205 String packageName = entry.getKey(); 15206 PackageParser.Package pkg = mPackages.get(packageName); 15207 if (pkg == null) { 15208 continue; 15209 } 15210 UsageStats usage = entry.getValue(); 15211 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15212 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15213 } 15214 } 15215 } 15216 15217 /** 15218 * Check and throw if the given before/after packages would be considered a 15219 * downgrade. 15220 */ 15221 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15222 throws PackageManagerException { 15223 if (after.versionCode < before.mVersionCode) { 15224 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15225 "Update version code " + after.versionCode + " is older than current " 15226 + before.mVersionCode); 15227 } else if (after.versionCode == before.mVersionCode) { 15228 if (after.baseRevisionCode < before.baseRevisionCode) { 15229 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15230 "Update base revision code " + after.baseRevisionCode 15231 + " is older than current " + before.baseRevisionCode); 15232 } 15233 15234 if (!ArrayUtils.isEmpty(after.splitNames)) { 15235 for (int i = 0; i < after.splitNames.length; i++) { 15236 final String splitName = after.splitNames[i]; 15237 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15238 if (j != -1) { 15239 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15240 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15241 "Update split " + splitName + " revision code " 15242 + after.splitRevisionCodes[i] + " is older than current " 15243 + before.splitRevisionCodes[j]); 15244 } 15245 } 15246 } 15247 } 15248 } 15249 } 15250 15251 private static class MoveCallbacks extends Handler { 15252 private static final int MSG_CREATED = 1; 15253 private static final int MSG_STATUS_CHANGED = 2; 15254 15255 private final RemoteCallbackList<IPackageMoveObserver> 15256 mCallbacks = new RemoteCallbackList<>(); 15257 15258 private final SparseIntArray mLastStatus = new SparseIntArray(); 15259 15260 public MoveCallbacks(Looper looper) { 15261 super(looper); 15262 } 15263 15264 public void register(IPackageMoveObserver callback) { 15265 mCallbacks.register(callback); 15266 } 15267 15268 public void unregister(IPackageMoveObserver callback) { 15269 mCallbacks.unregister(callback); 15270 } 15271 15272 @Override 15273 public void handleMessage(Message msg) { 15274 final SomeArgs args = (SomeArgs) msg.obj; 15275 final int n = mCallbacks.beginBroadcast(); 15276 for (int i = 0; i < n; i++) { 15277 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15278 try { 15279 invokeCallback(callback, msg.what, args); 15280 } catch (RemoteException ignored) { 15281 } 15282 } 15283 mCallbacks.finishBroadcast(); 15284 args.recycle(); 15285 } 15286 15287 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15288 throws RemoteException { 15289 switch (what) { 15290 case MSG_CREATED: { 15291 callback.onCreated(args.argi1, (Bundle) args.arg2); 15292 break; 15293 } 15294 case MSG_STATUS_CHANGED: { 15295 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15296 break; 15297 } 15298 } 15299 } 15300 15301 private void notifyCreated(int moveId, Bundle extras) { 15302 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15303 15304 final SomeArgs args = SomeArgs.obtain(); 15305 args.argi1 = moveId; 15306 args.arg2 = extras; 15307 obtainMessage(MSG_CREATED, args).sendToTarget(); 15308 } 15309 15310 private void notifyStatusChanged(int moveId, int status) { 15311 notifyStatusChanged(moveId, status, -1); 15312 } 15313 15314 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15315 Slog.v(TAG, "Move " + moveId + " status " + status); 15316 15317 final SomeArgs args = SomeArgs.obtain(); 15318 args.argi1 = moveId; 15319 args.argi2 = status; 15320 args.arg3 = estMillis; 15321 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15322 15323 synchronized (mLastStatus) { 15324 mLastStatus.put(moveId, status); 15325 } 15326 } 15327 } 15328 15329 private final class OnPermissionChangeListeners extends Handler { 15330 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15331 15332 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15333 new RemoteCallbackList<>(); 15334 15335 public OnPermissionChangeListeners(Looper looper) { 15336 super(looper); 15337 } 15338 15339 @Override 15340 public void handleMessage(Message msg) { 15341 switch (msg.what) { 15342 case MSG_ON_PERMISSIONS_CHANGED: { 15343 final int uid = msg.arg1; 15344 handleOnPermissionsChanged(uid); 15345 } break; 15346 } 15347 } 15348 15349 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15350 mPermissionListeners.register(listener); 15351 15352 } 15353 15354 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15355 mPermissionListeners.unregister(listener); 15356 } 15357 15358 public void onPermissionsChanged(int uid) { 15359 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15360 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15361 } 15362 } 15363 15364 private void handleOnPermissionsChanged(int uid) { 15365 final int count = mPermissionListeners.beginBroadcast(); 15366 try { 15367 for (int i = 0; i < count; i++) { 15368 IOnPermissionsChangeListener callback = mPermissionListeners 15369 .getBroadcastItem(i); 15370 try { 15371 callback.onPermissionsChanged(uid); 15372 } catch (RemoteException e) { 15373 Log.e(TAG, "Permission listener is dead", e); 15374 } 15375 } 15376 } finally { 15377 mPermissionListeners.finishBroadcast(); 15378 } 15379 } 15380 } 15381} 15382