PackageManagerService.java revision 00c06628286ad4a86d421ed7c4708b83f595e234
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_INTERNAL; 47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 52import static android.content.pm.PackageManager.MATCH_ALL; 53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 57import static android.content.pm.PackageParser.isApkFile; 58import static android.os.Process.FIRST_APPLICATION_UID; 59import static android.os.Process.PACKAGE_INFO_GID; 60import static android.os.Process.SYSTEM_UID; 61import static android.system.OsConstants.O_CREAT; 62import static android.system.OsConstants.O_RDWR; 63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 64import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 65import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 66import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 67import static com.android.internal.util.ArrayUtils.appendInt; 68import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 70import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 71import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 72import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 73 74import android.Manifest; 75import android.app.ActivityManager; 76import android.app.ActivityManagerNative; 77import android.app.AppGlobals; 78import android.app.IActivityManager; 79import android.app.admin.IDevicePolicyManager; 80import android.app.backup.IBackupManager; 81import android.app.usage.UsageStats; 82import android.app.usage.UsageStatsManager; 83import android.content.BroadcastReceiver; 84import android.content.ComponentName; 85import android.content.Context; 86import android.content.IIntentReceiver; 87import android.content.Intent; 88import android.content.IntentFilter; 89import android.content.IntentSender; 90import android.content.IntentSender.SendIntentException; 91import android.content.ServiceConnection; 92import android.content.pm.ActivityInfo; 93import android.content.pm.ApplicationInfo; 94import android.content.pm.FeatureInfo; 95import android.content.pm.IOnPermissionsChangeListener; 96import android.content.pm.IPackageDataObserver; 97import android.content.pm.IPackageDeleteObserver; 98import android.content.pm.IPackageDeleteObserver2; 99import android.content.pm.IPackageInstallObserver2; 100import android.content.pm.IPackageInstaller; 101import android.content.pm.IPackageManager; 102import android.content.pm.IPackageMoveObserver; 103import android.content.pm.IPackageStatsObserver; 104import android.content.pm.InstrumentationInfo; 105import android.content.pm.IntentFilterVerificationInfo; 106import android.content.pm.KeySet; 107import android.content.pm.ManifestDigest; 108import android.content.pm.PackageCleanItem; 109import android.content.pm.PackageInfo; 110import android.content.pm.PackageInfoLite; 111import android.content.pm.PackageInstaller; 112import android.content.pm.PackageManager; 113import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 114import android.content.pm.PackageParser; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageStats; 119import android.content.pm.PackageUserState; 120import android.content.pm.ParceledListSlice; 121import android.content.pm.PermissionGroupInfo; 122import android.content.pm.PermissionInfo; 123import android.content.pm.ProviderInfo; 124import android.content.pm.ResolveInfo; 125import android.content.pm.ServiceInfo; 126import android.content.pm.Signature; 127import android.content.pm.UserInfo; 128import android.content.pm.VerificationParams; 129import android.content.pm.VerifierDeviceIdentity; 130import android.content.pm.VerifierInfo; 131import android.content.res.Resources; 132import android.hardware.display.DisplayManager; 133import android.net.Uri; 134import android.os.Binder; 135import android.os.Build; 136import android.os.Bundle; 137import android.os.Debug; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.FileUtils; 141import android.os.Handler; 142import android.os.IBinder; 143import android.os.Looper; 144import android.os.Message; 145import android.os.Parcel; 146import android.os.ParcelFileDescriptor; 147import android.os.Process; 148import android.os.RemoteCallbackList; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.os.storage.IMountService; 157import android.os.storage.StorageEventListener; 158import android.os.storage.StorageManager; 159import android.os.storage.VolumeInfo; 160import android.os.storage.VolumeRecord; 161import android.security.KeyStore; 162import android.security.SystemKeyStore; 163import android.system.ErrnoException; 164import android.system.Os; 165import android.system.StructStat; 166import android.text.TextUtils; 167import android.text.format.DateUtils; 168import android.util.ArrayMap; 169import android.util.ArraySet; 170import android.util.AtomicFile; 171import android.util.DisplayMetrics; 172import android.util.EventLog; 173import android.util.ExceptionUtils; 174import android.util.Log; 175import android.util.LogPrinter; 176import android.util.MathUtils; 177import android.util.PrintStreamPrinter; 178import android.util.Slog; 179import android.util.SparseArray; 180import android.util.SparseBooleanArray; 181import android.util.SparseIntArray; 182import android.util.Xml; 183import android.view.Display; 184 185import dalvik.system.DexFile; 186import dalvik.system.VMRuntime; 187 188import libcore.io.IoUtils; 189import libcore.util.EmptyArray; 190 191import com.android.internal.R; 192import com.android.internal.app.IMediaContainerService; 193import com.android.internal.app.ResolverActivity; 194import com.android.internal.content.NativeLibraryHelper; 195import com.android.internal.content.PackageHelper; 196import com.android.internal.os.IParcelFileDescriptorFactory; 197import com.android.internal.os.SomeArgs; 198import com.android.internal.util.ArrayUtils; 199import com.android.internal.util.FastPrintWriter; 200import com.android.internal.util.FastXmlSerializer; 201import com.android.internal.util.IndentingPrintWriter; 202import com.android.internal.util.Preconditions; 203import com.android.server.EventLogTags; 204import com.android.server.FgThread; 205import com.android.server.IntentResolver; 206import com.android.server.LocalServices; 207import com.android.server.ServiceThread; 208import com.android.server.SystemConfig; 209import com.android.server.Watchdog; 210import com.android.server.pm.Settings.DatabaseVersion; 211import com.android.server.pm.PermissionsState.PermissionState; 212import com.android.server.storage.DeviceStorageMonitorInternal; 213 214import org.xmlpull.v1.XmlPullParser; 215import org.xmlpull.v1.XmlSerializer; 216 217import java.io.BufferedInputStream; 218import java.io.BufferedOutputStream; 219import java.io.BufferedReader; 220import java.io.ByteArrayInputStream; 221import java.io.ByteArrayOutputStream; 222import java.io.File; 223import java.io.FileDescriptor; 224import java.io.FileNotFoundException; 225import java.io.FileOutputStream; 226import java.io.FileReader; 227import java.io.FilenameFilter; 228import java.io.IOException; 229import java.io.InputStream; 230import java.io.PrintWriter; 231import java.nio.charset.StandardCharsets; 232import java.security.NoSuchAlgorithmException; 233import java.security.PublicKey; 234import java.security.cert.CertificateEncodingException; 235import java.security.cert.CertificateException; 236import java.text.SimpleDateFormat; 237import java.util.ArrayList; 238import java.util.Arrays; 239import java.util.Collection; 240import java.util.Collections; 241import java.util.Comparator; 242import java.util.Date; 243import java.util.Iterator; 244import java.util.List; 245import java.util.Map; 246import java.util.Objects; 247import java.util.Set; 248import java.util.concurrent.CountDownLatch; 249import java.util.concurrent.TimeUnit; 250import java.util.concurrent.atomic.AtomicBoolean; 251import java.util.concurrent.atomic.AtomicInteger; 252import java.util.concurrent.atomic.AtomicLong; 253 254/** 255 * Keep track of all those .apks everywhere. 256 * 257 * This is very central to the platform's security; please run the unit 258 * tests whenever making modifications here: 259 * 260runtest -c android.content.pm.PackageManagerTests frameworks-core 261 * 262 * {@hide} 263 */ 264public class PackageManagerService extends IPackageManager.Stub { 265 static final String TAG = "PackageManager"; 266 static final boolean DEBUG_SETTINGS = false; 267 static final boolean DEBUG_PREFERRED = false; 268 static final boolean DEBUG_UPGRADE = false; 269 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 270 private static final boolean DEBUG_BACKUP = true; 271 private static final boolean DEBUG_INSTALL = false; 272 private static final boolean DEBUG_REMOVE = false; 273 private static final boolean DEBUG_BROADCASTS = false; 274 private static final boolean DEBUG_SHOW_INFO = false; 275 private static final boolean DEBUG_PACKAGE_INFO = false; 276 private static final boolean DEBUG_INTENT_MATCHING = false; 277 private static final boolean DEBUG_PACKAGE_SCANNING = false; 278 private static final boolean DEBUG_VERIFY = false; 279 private static final boolean DEBUG_DEXOPT = false; 280 private static final boolean DEBUG_ABI_SELECTION = false; 281 282 private static final int RADIO_UID = Process.PHONE_UID; 283 private static final int LOG_UID = Process.LOG_UID; 284 private static final int NFC_UID = Process.NFC_UID; 285 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 286 private static final int SHELL_UID = Process.SHELL_UID; 287 288 // Cap the size of permission trees that 3rd party apps can define 289 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 290 291 // Suffix used during package installation when copying/moving 292 // package apks to install directory. 293 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 294 295 static final int SCAN_NO_DEX = 1<<1; 296 static final int SCAN_FORCE_DEX = 1<<2; 297 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 298 static final int SCAN_NEW_INSTALL = 1<<4; 299 static final int SCAN_NO_PATHS = 1<<5; 300 static final int SCAN_UPDATE_TIME = 1<<6; 301 static final int SCAN_DEFER_DEX = 1<<7; 302 static final int SCAN_BOOTING = 1<<8; 303 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 304 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 305 static final int SCAN_REQUIRE_KNOWN = 1<<12; 306 static final int SCAN_MOVE = 1<<13; 307 308 static final int REMOVE_CHATTY = 1<<16; 309 310 private static final int[] EMPTY_INT_ARRAY = new int[0]; 311 312 /** 313 * Timeout (in milliseconds) after which the watchdog should declare that 314 * our handler thread is wedged. The usual default for such things is one 315 * minute but we sometimes do very lengthy I/O operations on this thread, 316 * such as installing multi-gigabyte applications, so ours needs to be longer. 317 */ 318 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 319 320 /** 321 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 322 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 323 * settings entry if available, otherwise we use the hardcoded default. If it's been 324 * more than this long since the last fstrim, we force one during the boot sequence. 325 * 326 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 327 * one gets run at the next available charging+idle time. This final mandatory 328 * no-fstrim check kicks in only of the other scheduling criteria is never met. 329 */ 330 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 331 332 /** 333 * Whether verification is enabled by default. 334 */ 335 private static final boolean DEFAULT_VERIFY_ENABLE = true; 336 337 /** 338 * The default maximum time to wait for the verification agent to return in 339 * milliseconds. 340 */ 341 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 342 343 /** 344 * The default response for package verification timeout. 345 * 346 * This can be either PackageManager.VERIFICATION_ALLOW or 347 * PackageManager.VERIFICATION_REJECT. 348 */ 349 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 350 351 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 352 353 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 354 DEFAULT_CONTAINER_PACKAGE, 355 "com.android.defcontainer.DefaultContainerService"); 356 357 private static final String KILL_APP_REASON_GIDS_CHANGED = 358 "permission grant or revoke changed gids"; 359 360 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 361 "permissions revoked"; 362 363 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 364 365 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 366 367 /** Permission grant: not grant the permission. */ 368 private static final int GRANT_DENIED = 1; 369 370 /** Permission grant: grant the permission as an install permission. */ 371 private static final int GRANT_INSTALL = 2; 372 373 /** Permission grant: grant the permission as an install permission for a legacy app. */ 374 private static final int GRANT_INSTALL_LEGACY = 3; 375 376 /** Permission grant: grant the permission as a runtime one. */ 377 private static final int GRANT_RUNTIME = 4; 378 379 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 380 private static final int GRANT_UPGRADE = 5; 381 382 final ServiceThread mHandlerThread; 383 384 final PackageHandler mHandler; 385 386 /** 387 * Messages for {@link #mHandler} that need to wait for system ready before 388 * being dispatched. 389 */ 390 private ArrayList<Message> mPostSystemReadyMessages; 391 392 final int mSdkVersion = Build.VERSION.SDK_INT; 393 394 final Context mContext; 395 final boolean mFactoryTest; 396 final boolean mOnlyCore; 397 final boolean mLazyDexOpt; 398 final long mDexOptLRUThresholdInMills; 399 final DisplayMetrics mMetrics; 400 final int mDefParseFlags; 401 final String[] mSeparateProcesses; 402 final boolean mIsUpgrade; 403 404 // This is where all application persistent data goes. 405 final File mAppDataDir; 406 407 // This is where all application persistent data goes for secondary users. 408 final File mUserAppDataDir; 409 410 /** The location for ASEC container files on internal storage. */ 411 final String mAsecInternalPath; 412 413 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 414 // LOCK HELD. Can be called with mInstallLock held. 415 final Installer mInstaller; 416 417 /** Directory where installed third-party apps stored */ 418 final File mAppInstallDir; 419 420 /** 421 * Directory to which applications installed internally have their 422 * 32 bit native libraries copied. 423 */ 424 private File mAppLib32InstallDir; 425 426 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 427 // apps. 428 final File mDrmAppPrivateInstallDir; 429 430 // ---------------------------------------------------------------- 431 432 // Lock for state used when installing and doing other long running 433 // operations. Methods that must be called with this lock held have 434 // the suffix "LI". 435 final Object mInstallLock = new Object(); 436 437 // ---------------------------------------------------------------- 438 439 // Keys are String (package name), values are Package. This also serves 440 // as the lock for the global state. Methods that must be called with 441 // this lock held have the prefix "LP". 442 final ArrayMap<String, PackageParser.Package> mPackages = 443 new ArrayMap<String, PackageParser.Package>(); 444 445 // Tracks available target package names -> overlay package paths. 446 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 447 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 448 449 final Settings mSettings; 450 boolean mRestoredSettings; 451 452 // System configuration read by SystemConfig. 453 final int[] mGlobalGids; 454 final SparseArray<ArraySet<String>> mSystemPermissions; 455 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 456 457 // If mac_permissions.xml was found for seinfo labeling. 458 boolean mFoundPolicyFile; 459 460 // If a recursive restorecon of /data/data/<pkg> is needed. 461 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 462 463 public static final class SharedLibraryEntry { 464 public final String path; 465 public final String apk; 466 467 SharedLibraryEntry(String _path, String _apk) { 468 path = _path; 469 apk = _apk; 470 } 471 } 472 473 // Currently known shared libraries. 474 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 475 new ArrayMap<String, SharedLibraryEntry>(); 476 477 // All available activities, for your resolving pleasure. 478 final ActivityIntentResolver mActivities = 479 new ActivityIntentResolver(); 480 481 // All available receivers, for your resolving pleasure. 482 final ActivityIntentResolver mReceivers = 483 new ActivityIntentResolver(); 484 485 // All available services, for your resolving pleasure. 486 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 487 488 // All available providers, for your resolving pleasure. 489 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 490 491 // Mapping from provider base names (first directory in content URI codePath) 492 // to the provider information. 493 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 494 new ArrayMap<String, PackageParser.Provider>(); 495 496 // Mapping from instrumentation class names to info about them. 497 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 498 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 499 500 // Mapping from permission names to info about them. 501 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 502 new ArrayMap<String, PackageParser.PermissionGroup>(); 503 504 // Packages whose data we have transfered into another package, thus 505 // should no longer exist. 506 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 507 508 // Broadcast actions that are only available to the system. 509 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 510 511 /** List of packages waiting for verification. */ 512 final SparseArray<PackageVerificationState> mPendingVerification 513 = new SparseArray<PackageVerificationState>(); 514 515 /** Set of packages associated with each app op permission. */ 516 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 517 518 final PackageInstallerService mInstallerService; 519 520 private final PackageDexOptimizer mPackageDexOptimizer; 521 522 private AtomicInteger mNextMoveId = new AtomicInteger(); 523 private final MoveCallbacks mMoveCallbacks; 524 525 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 526 527 // Cache of users who need badging. 528 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 529 530 /** Token for keys in mPendingVerification. */ 531 private int mPendingVerificationToken = 0; 532 533 volatile boolean mSystemReady; 534 volatile boolean mSafeMode; 535 volatile boolean mHasSystemUidErrors; 536 537 ApplicationInfo mAndroidApplication; 538 final ActivityInfo mResolveActivity = new ActivityInfo(); 539 final ResolveInfo mResolveInfo = new ResolveInfo(); 540 ComponentName mResolveComponentName; 541 PackageParser.Package mPlatformPackage; 542 ComponentName mCustomResolverComponentName; 543 544 boolean mResolverReplaced = false; 545 546 private final ComponentName mIntentFilterVerifierComponent; 547 private int mIntentFilterVerificationToken = 0; 548 549 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 550 = new SparseArray<IntentFilterVerificationState>(); 551 552 private interface IntentFilterVerifier<T extends IntentFilter> { 553 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 554 T filter, String packageName); 555 void startVerifications(int userId); 556 void receiveVerificationResponse(int verificationId); 557 } 558 559 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 560 private Context mContext; 561 private ComponentName mIntentFilterVerifierComponent; 562 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 563 564 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 565 mContext = context; 566 mIntentFilterVerifierComponent = verifierComponent; 567 } 568 569 private String getDefaultScheme() { 570 return IntentFilter.SCHEME_HTTPS; 571 } 572 573 @Override 574 public void startVerifications(int userId) { 575 // Launch verifications requests 576 int count = mCurrentIntentFilterVerifications.size(); 577 for (int n=0; n<count; n++) { 578 int verificationId = mCurrentIntentFilterVerifications.get(n); 579 final IntentFilterVerificationState ivs = 580 mIntentFilterVerificationStates.get(verificationId); 581 582 String packageName = ivs.getPackageName(); 583 584 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 585 final int filterCount = filters.size(); 586 ArraySet<String> domainsSet = new ArraySet<>(); 587 for (int m=0; m<filterCount; m++) { 588 PackageParser.ActivityIntentInfo filter = filters.get(m); 589 domainsSet.addAll(filter.getHostsList()); 590 } 591 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 592 synchronized (mPackages) { 593 if (mSettings.createIntentFilterVerificationIfNeededLPw( 594 packageName, domainsList) != null) { 595 scheduleWriteSettingsLocked(); 596 } 597 } 598 sendVerificationRequest(userId, verificationId, ivs); 599 } 600 mCurrentIntentFilterVerifications.clear(); 601 } 602 603 private void sendVerificationRequest(int userId, int verificationId, 604 IntentFilterVerificationState ivs) { 605 606 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 607 verificationIntent.putExtra( 608 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 609 verificationId); 610 verificationIntent.putExtra( 611 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 612 getDefaultScheme()); 613 verificationIntent.putExtra( 614 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 615 ivs.getHostsString()); 616 verificationIntent.putExtra( 617 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 618 ivs.getPackageName()); 619 verificationIntent.setComponent(mIntentFilterVerifierComponent); 620 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 621 622 UserHandle user = new UserHandle(userId); 623 mContext.sendBroadcastAsUser(verificationIntent, user); 624 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 625 "Sending IntenFilter verification broadcast"); 626 } 627 628 public void receiveVerificationResponse(int verificationId) { 629 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 630 631 final boolean verified = ivs.isVerified(); 632 633 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 634 final int count = filters.size(); 635 for (int n=0; n<count; n++) { 636 PackageParser.ActivityIntentInfo filter = filters.get(n); 637 filter.setVerified(verified); 638 639 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 640 + " verified with result:" + verified + " and hosts:" 641 + ivs.getHostsString()); 642 } 643 644 mIntentFilterVerificationStates.remove(verificationId); 645 646 final String packageName = ivs.getPackageName(); 647 IntentFilterVerificationInfo ivi = null; 648 649 synchronized (mPackages) { 650 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 651 } 652 if (ivi == null) { 653 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 654 + verificationId + " packageName:" + packageName); 655 return; 656 } 657 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 658 "Updating IntentFilterVerificationInfo for verificationId:" + verificationId); 659 660 synchronized (mPackages) { 661 if (verified) { 662 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 663 } else { 664 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 665 } 666 scheduleWriteSettingsLocked(); 667 668 final int userId = ivs.getUserId(); 669 if (userId != UserHandle.USER_ALL) { 670 final int userStatus = 671 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 672 673 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 674 boolean needUpdate = false; 675 676 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 677 // already been set by the User thru the Disambiguation dialog 678 switch (userStatus) { 679 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 680 if (verified) { 681 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 682 } else { 683 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 684 } 685 needUpdate = true; 686 break; 687 688 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 689 if (verified) { 690 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 691 needUpdate = true; 692 } 693 break; 694 695 default: 696 // Nothing to do 697 } 698 699 if (needUpdate) { 700 mSettings.updateIntentFilterVerificationStatusLPw( 701 packageName, updatedStatus, userId); 702 scheduleWritePackageRestrictionsLocked(userId); 703 } 704 } 705 } 706 } 707 708 @Override 709 public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 710 ActivityIntentInfo filter, String packageName) { 711 if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 712 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 713 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 714 "IntentFilter does not contain HTTP nor HTTPS data scheme"); 715 return false; 716 } 717 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 718 if (ivs == null) { 719 ivs = createDomainVerificationState(verifierId, userId, verificationId, 720 packageName); 721 } 722 if (!hasValidDomains(filter)) { 723 return false; 724 } 725 ivs.addFilter(filter); 726 return true; 727 } 728 729 private IntentFilterVerificationState createDomainVerificationState(int verifierId, 730 int userId, int verificationId, String packageName) { 731 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 732 verifierId, userId, packageName); 733 ivs.setPendingState(); 734 synchronized (mPackages) { 735 mIntentFilterVerificationStates.append(verificationId, ivs); 736 mCurrentIntentFilterVerifications.add(verificationId); 737 } 738 return ivs; 739 } 740 } 741 742 private static boolean hasValidDomains(ActivityIntentInfo filter) { 743 boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 744 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS); 745 if (!hasHTTPorHTTPS) { 746 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 747 "IntentFilter does not contain any HTTP or HTTPS data scheme"); 748 return false; 749 } 750 return true; 751 } 752 753 private IntentFilterVerifier mIntentFilterVerifier; 754 755 // Set of pending broadcasts for aggregating enable/disable of components. 756 static class PendingPackageBroadcasts { 757 // for each user id, a map of <package name -> components within that package> 758 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 759 760 public PendingPackageBroadcasts() { 761 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 762 } 763 764 public ArrayList<String> get(int userId, String packageName) { 765 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 766 return packages.get(packageName); 767 } 768 769 public void put(int userId, String packageName, ArrayList<String> components) { 770 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 771 packages.put(packageName, components); 772 } 773 774 public void remove(int userId, String packageName) { 775 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 776 if (packages != null) { 777 packages.remove(packageName); 778 } 779 } 780 781 public void remove(int userId) { 782 mUidMap.remove(userId); 783 } 784 785 public int userIdCount() { 786 return mUidMap.size(); 787 } 788 789 public int userIdAt(int n) { 790 return mUidMap.keyAt(n); 791 } 792 793 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 794 return mUidMap.get(userId); 795 } 796 797 public int size() { 798 // total number of pending broadcast entries across all userIds 799 int num = 0; 800 for (int i = 0; i< mUidMap.size(); i++) { 801 num += mUidMap.valueAt(i).size(); 802 } 803 return num; 804 } 805 806 public void clear() { 807 mUidMap.clear(); 808 } 809 810 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 811 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 812 if (map == null) { 813 map = new ArrayMap<String, ArrayList<String>>(); 814 mUidMap.put(userId, map); 815 } 816 return map; 817 } 818 } 819 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 820 821 // Service Connection to remote media container service to copy 822 // package uri's from external media onto secure containers 823 // or internal storage. 824 private IMediaContainerService mContainerService = null; 825 826 static final int SEND_PENDING_BROADCAST = 1; 827 static final int MCS_BOUND = 3; 828 static final int END_COPY = 4; 829 static final int INIT_COPY = 5; 830 static final int MCS_UNBIND = 6; 831 static final int START_CLEANING_PACKAGE = 7; 832 static final int FIND_INSTALL_LOC = 8; 833 static final int POST_INSTALL = 9; 834 static final int MCS_RECONNECT = 10; 835 static final int MCS_GIVE_UP = 11; 836 static final int UPDATED_MEDIA_STATUS = 12; 837 static final int WRITE_SETTINGS = 13; 838 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 839 static final int PACKAGE_VERIFIED = 15; 840 static final int CHECK_PENDING_VERIFICATION = 16; 841 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 842 static final int INTENT_FILTER_VERIFIED = 18; 843 844 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 845 846 // Delay time in millisecs 847 static final int BROADCAST_DELAY = 10 * 1000; 848 849 static UserManagerService sUserManager; 850 851 // Stores a list of users whose package restrictions file needs to be updated 852 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 853 854 final private DefaultContainerConnection mDefContainerConn = 855 new DefaultContainerConnection(); 856 class DefaultContainerConnection implements ServiceConnection { 857 public void onServiceConnected(ComponentName name, IBinder service) { 858 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 859 IMediaContainerService imcs = 860 IMediaContainerService.Stub.asInterface(service); 861 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 862 } 863 864 public void onServiceDisconnected(ComponentName name) { 865 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 866 } 867 }; 868 869 // Recordkeeping of restore-after-install operations that are currently in flight 870 // between the Package Manager and the Backup Manager 871 class PostInstallData { 872 public InstallArgs args; 873 public PackageInstalledInfo res; 874 875 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 876 args = _a; 877 res = _r; 878 } 879 }; 880 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 881 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 882 883 // backup/restore of preferred activity state 884 private static final String TAG_PREFERRED_BACKUP = "pa"; 885 886 private final String mRequiredVerifierPackage; 887 888 private final PackageUsage mPackageUsage = new PackageUsage(); 889 890 private class PackageUsage { 891 private static final int WRITE_INTERVAL 892 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 893 894 private final Object mFileLock = new Object(); 895 private final AtomicLong mLastWritten = new AtomicLong(0); 896 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 897 898 private boolean mIsHistoricalPackageUsageAvailable = true; 899 900 boolean isHistoricalPackageUsageAvailable() { 901 return mIsHistoricalPackageUsageAvailable; 902 } 903 904 void write(boolean force) { 905 if (force) { 906 writeInternal(); 907 return; 908 } 909 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 910 && !DEBUG_DEXOPT) { 911 return; 912 } 913 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 914 new Thread("PackageUsage_DiskWriter") { 915 @Override 916 public void run() { 917 try { 918 writeInternal(); 919 } finally { 920 mBackgroundWriteRunning.set(false); 921 } 922 } 923 }.start(); 924 } 925 } 926 927 private void writeInternal() { 928 synchronized (mPackages) { 929 synchronized (mFileLock) { 930 AtomicFile file = getFile(); 931 FileOutputStream f = null; 932 try { 933 f = file.startWrite(); 934 BufferedOutputStream out = new BufferedOutputStream(f); 935 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 936 StringBuilder sb = new StringBuilder(); 937 for (PackageParser.Package pkg : mPackages.values()) { 938 if (pkg.mLastPackageUsageTimeInMills == 0) { 939 continue; 940 } 941 sb.setLength(0); 942 sb.append(pkg.packageName); 943 sb.append(' '); 944 sb.append((long)pkg.mLastPackageUsageTimeInMills); 945 sb.append('\n'); 946 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 947 } 948 out.flush(); 949 file.finishWrite(f); 950 } catch (IOException e) { 951 if (f != null) { 952 file.failWrite(f); 953 } 954 Log.e(TAG, "Failed to write package usage times", e); 955 } 956 } 957 } 958 mLastWritten.set(SystemClock.elapsedRealtime()); 959 } 960 961 void readLP() { 962 synchronized (mFileLock) { 963 AtomicFile file = getFile(); 964 BufferedInputStream in = null; 965 try { 966 in = new BufferedInputStream(file.openRead()); 967 StringBuffer sb = new StringBuffer(); 968 while (true) { 969 String packageName = readToken(in, sb, ' '); 970 if (packageName == null) { 971 break; 972 } 973 String timeInMillisString = readToken(in, sb, '\n'); 974 if (timeInMillisString == null) { 975 throw new IOException("Failed to find last usage time for package " 976 + packageName); 977 } 978 PackageParser.Package pkg = mPackages.get(packageName); 979 if (pkg == null) { 980 continue; 981 } 982 long timeInMillis; 983 try { 984 timeInMillis = Long.parseLong(timeInMillisString.toString()); 985 } catch (NumberFormatException e) { 986 throw new IOException("Failed to parse " + timeInMillisString 987 + " as a long.", e); 988 } 989 pkg.mLastPackageUsageTimeInMills = timeInMillis; 990 } 991 } catch (FileNotFoundException expected) { 992 mIsHistoricalPackageUsageAvailable = false; 993 } catch (IOException e) { 994 Log.w(TAG, "Failed to read package usage times", e); 995 } finally { 996 IoUtils.closeQuietly(in); 997 } 998 } 999 mLastWritten.set(SystemClock.elapsedRealtime()); 1000 } 1001 1002 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1003 throws IOException { 1004 sb.setLength(0); 1005 while (true) { 1006 int ch = in.read(); 1007 if (ch == -1) { 1008 if (sb.length() == 0) { 1009 return null; 1010 } 1011 throw new IOException("Unexpected EOF"); 1012 } 1013 if (ch == endOfToken) { 1014 return sb.toString(); 1015 } 1016 sb.append((char)ch); 1017 } 1018 } 1019 1020 private AtomicFile getFile() { 1021 File dataDir = Environment.getDataDirectory(); 1022 File systemDir = new File(dataDir, "system"); 1023 File fname = new File(systemDir, "package-usage.list"); 1024 return new AtomicFile(fname); 1025 } 1026 } 1027 1028 class PackageHandler extends Handler { 1029 private boolean mBound = false; 1030 final ArrayList<HandlerParams> mPendingInstalls = 1031 new ArrayList<HandlerParams>(); 1032 1033 private boolean connectToService() { 1034 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1035 " DefaultContainerService"); 1036 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1037 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1038 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1039 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 1040 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1041 mBound = true; 1042 return true; 1043 } 1044 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1045 return false; 1046 } 1047 1048 private void disconnectService() { 1049 mContainerService = null; 1050 mBound = false; 1051 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1052 mContext.unbindService(mDefContainerConn); 1053 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1054 } 1055 1056 PackageHandler(Looper looper) { 1057 super(looper); 1058 } 1059 1060 public void handleMessage(Message msg) { 1061 try { 1062 doHandleMessage(msg); 1063 } finally { 1064 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1065 } 1066 } 1067 1068 void doHandleMessage(Message msg) { 1069 switch (msg.what) { 1070 case INIT_COPY: { 1071 HandlerParams params = (HandlerParams) msg.obj; 1072 int idx = mPendingInstalls.size(); 1073 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1074 // If a bind was already initiated we dont really 1075 // need to do anything. The pending install 1076 // will be processed later on. 1077 if (!mBound) { 1078 // If this is the only one pending we might 1079 // have to bind to the service again. 1080 if (!connectToService()) { 1081 Slog.e(TAG, "Failed to bind to media container service"); 1082 params.serviceError(); 1083 return; 1084 } else { 1085 // Once we bind to the service, the first 1086 // pending request will be processed. 1087 mPendingInstalls.add(idx, params); 1088 } 1089 } else { 1090 mPendingInstalls.add(idx, params); 1091 // Already bound to the service. Just make 1092 // sure we trigger off processing the first request. 1093 if (idx == 0) { 1094 mHandler.sendEmptyMessage(MCS_BOUND); 1095 } 1096 } 1097 break; 1098 } 1099 case MCS_BOUND: { 1100 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1101 if (msg.obj != null) { 1102 mContainerService = (IMediaContainerService) msg.obj; 1103 } 1104 if (mContainerService == null) { 1105 // Something seriously wrong. Bail out 1106 Slog.e(TAG, "Cannot bind to media container service"); 1107 for (HandlerParams params : mPendingInstalls) { 1108 // Indicate service bind error 1109 params.serviceError(); 1110 } 1111 mPendingInstalls.clear(); 1112 } else if (mPendingInstalls.size() > 0) { 1113 HandlerParams params = mPendingInstalls.get(0); 1114 if (params != null) { 1115 if (params.startCopy()) { 1116 // We are done... look for more work or to 1117 // go idle. 1118 if (DEBUG_SD_INSTALL) Log.i(TAG, 1119 "Checking for more work or unbind..."); 1120 // Delete pending install 1121 if (mPendingInstalls.size() > 0) { 1122 mPendingInstalls.remove(0); 1123 } 1124 if (mPendingInstalls.size() == 0) { 1125 if (mBound) { 1126 if (DEBUG_SD_INSTALL) Log.i(TAG, 1127 "Posting delayed MCS_UNBIND"); 1128 removeMessages(MCS_UNBIND); 1129 Message ubmsg = obtainMessage(MCS_UNBIND); 1130 // Unbind after a little delay, to avoid 1131 // continual thrashing. 1132 sendMessageDelayed(ubmsg, 10000); 1133 } 1134 } else { 1135 // There are more pending requests in queue. 1136 // Just post MCS_BOUND message to trigger processing 1137 // of next pending install. 1138 if (DEBUG_SD_INSTALL) Log.i(TAG, 1139 "Posting MCS_BOUND for next work"); 1140 mHandler.sendEmptyMessage(MCS_BOUND); 1141 } 1142 } 1143 } 1144 } else { 1145 // Should never happen ideally. 1146 Slog.w(TAG, "Empty queue"); 1147 } 1148 break; 1149 } 1150 case MCS_RECONNECT: { 1151 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1152 if (mPendingInstalls.size() > 0) { 1153 if (mBound) { 1154 disconnectService(); 1155 } 1156 if (!connectToService()) { 1157 Slog.e(TAG, "Failed to bind to media container service"); 1158 for (HandlerParams params : mPendingInstalls) { 1159 // Indicate service bind error 1160 params.serviceError(); 1161 } 1162 mPendingInstalls.clear(); 1163 } 1164 } 1165 break; 1166 } 1167 case MCS_UNBIND: { 1168 // If there is no actual work left, then time to unbind. 1169 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1170 1171 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1172 if (mBound) { 1173 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1174 1175 disconnectService(); 1176 } 1177 } else if (mPendingInstalls.size() > 0) { 1178 // There are more pending requests in queue. 1179 // Just post MCS_BOUND message to trigger processing 1180 // of next pending install. 1181 mHandler.sendEmptyMessage(MCS_BOUND); 1182 } 1183 1184 break; 1185 } 1186 case MCS_GIVE_UP: { 1187 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1188 mPendingInstalls.remove(0); 1189 break; 1190 } 1191 case SEND_PENDING_BROADCAST: { 1192 String packages[]; 1193 ArrayList<String> components[]; 1194 int size = 0; 1195 int uids[]; 1196 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1197 synchronized (mPackages) { 1198 if (mPendingBroadcasts == null) { 1199 return; 1200 } 1201 size = mPendingBroadcasts.size(); 1202 if (size <= 0) { 1203 // Nothing to be done. Just return 1204 return; 1205 } 1206 packages = new String[size]; 1207 components = new ArrayList[size]; 1208 uids = new int[size]; 1209 int i = 0; // filling out the above arrays 1210 1211 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1212 int packageUserId = mPendingBroadcasts.userIdAt(n); 1213 Iterator<Map.Entry<String, ArrayList<String>>> it 1214 = mPendingBroadcasts.packagesForUserId(packageUserId) 1215 .entrySet().iterator(); 1216 while (it.hasNext() && i < size) { 1217 Map.Entry<String, ArrayList<String>> ent = it.next(); 1218 packages[i] = ent.getKey(); 1219 components[i] = ent.getValue(); 1220 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1221 uids[i] = (ps != null) 1222 ? UserHandle.getUid(packageUserId, ps.appId) 1223 : -1; 1224 i++; 1225 } 1226 } 1227 size = i; 1228 mPendingBroadcasts.clear(); 1229 } 1230 // Send broadcasts 1231 for (int i = 0; i < size; i++) { 1232 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1233 } 1234 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1235 break; 1236 } 1237 case START_CLEANING_PACKAGE: { 1238 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1239 final String packageName = (String)msg.obj; 1240 final int userId = msg.arg1; 1241 final boolean andCode = msg.arg2 != 0; 1242 synchronized (mPackages) { 1243 if (userId == UserHandle.USER_ALL) { 1244 int[] users = sUserManager.getUserIds(); 1245 for (int user : users) { 1246 mSettings.addPackageToCleanLPw( 1247 new PackageCleanItem(user, packageName, andCode)); 1248 } 1249 } else { 1250 mSettings.addPackageToCleanLPw( 1251 new PackageCleanItem(userId, packageName, andCode)); 1252 } 1253 } 1254 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1255 startCleaningPackages(); 1256 } break; 1257 case POST_INSTALL: { 1258 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1259 PostInstallData data = mRunningInstalls.get(msg.arg1); 1260 mRunningInstalls.delete(msg.arg1); 1261 boolean deleteOld = false; 1262 1263 if (data != null) { 1264 InstallArgs args = data.args; 1265 PackageInstalledInfo res = data.res; 1266 1267 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1268 res.removedInfo.sendBroadcast(false, true, false); 1269 Bundle extras = new Bundle(1); 1270 extras.putInt(Intent.EXTRA_UID, res.uid); 1271 1272 // Now that we successfully installed the package, grant runtime 1273 // permissions if requested before broadcasting the install. 1274 if ((args.installFlags 1275 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) { 1276 grantRequestedRuntimePermissions(res.pkg, 1277 args.user.getIdentifier()); 1278 } 1279 1280 // Determine the set of users who are adding this 1281 // package for the first time vs. those who are seeing 1282 // an update. 1283 int[] firstUsers; 1284 int[] updateUsers = new int[0]; 1285 if (res.origUsers == null || res.origUsers.length == 0) { 1286 firstUsers = res.newUsers; 1287 } else { 1288 firstUsers = new int[0]; 1289 for (int i=0; i<res.newUsers.length; i++) { 1290 int user = res.newUsers[i]; 1291 boolean isNew = true; 1292 for (int j=0; j<res.origUsers.length; j++) { 1293 if (res.origUsers[j] == user) { 1294 isNew = false; 1295 break; 1296 } 1297 } 1298 if (isNew) { 1299 int[] newFirst = new int[firstUsers.length+1]; 1300 System.arraycopy(firstUsers, 0, newFirst, 0, 1301 firstUsers.length); 1302 newFirst[firstUsers.length] = user; 1303 firstUsers = newFirst; 1304 } else { 1305 int[] newUpdate = new int[updateUsers.length+1]; 1306 System.arraycopy(updateUsers, 0, newUpdate, 0, 1307 updateUsers.length); 1308 newUpdate[updateUsers.length] = user; 1309 updateUsers = newUpdate; 1310 } 1311 } 1312 } 1313 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1314 res.pkg.applicationInfo.packageName, 1315 extras, null, null, firstUsers); 1316 final boolean update = res.removedInfo.removedPackage != null; 1317 if (update) { 1318 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1319 } 1320 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1321 res.pkg.applicationInfo.packageName, 1322 extras, null, null, updateUsers); 1323 if (update) { 1324 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1325 res.pkg.applicationInfo.packageName, 1326 extras, null, null, updateUsers); 1327 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1328 null, null, 1329 res.pkg.applicationInfo.packageName, null, updateUsers); 1330 1331 // treat asec-hosted packages like removable media on upgrade 1332 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1333 if (DEBUG_INSTALL) { 1334 Slog.i(TAG, "upgrading pkg " + res.pkg 1335 + " is ASEC-hosted -> AVAILABLE"); 1336 } 1337 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1338 ArrayList<String> pkgList = new ArrayList<String>(1); 1339 pkgList.add(res.pkg.applicationInfo.packageName); 1340 sendResourcesChangedBroadcast(true, true, 1341 pkgList,uidArray, null); 1342 } 1343 } 1344 if (res.removedInfo.args != null) { 1345 // Remove the replaced package's older resources safely now 1346 deleteOld = true; 1347 } 1348 1349 // Log current value of "unknown sources" setting 1350 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1351 getUnknownSourcesSettings()); 1352 } 1353 // Force a gc to clear up things 1354 Runtime.getRuntime().gc(); 1355 // We delete after a gc for applications on sdcard. 1356 if (deleteOld) { 1357 synchronized (mInstallLock) { 1358 res.removedInfo.args.doPostDeleteLI(true); 1359 } 1360 } 1361 if (args.observer != null) { 1362 try { 1363 Bundle extras = extrasForInstallResult(res); 1364 args.observer.onPackageInstalled(res.name, res.returnCode, 1365 res.returnMsg, extras); 1366 } catch (RemoteException e) { 1367 Slog.i(TAG, "Observer no longer exists."); 1368 } 1369 } 1370 } else { 1371 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1372 } 1373 } break; 1374 case UPDATED_MEDIA_STATUS: { 1375 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1376 boolean reportStatus = msg.arg1 == 1; 1377 boolean doGc = msg.arg2 == 1; 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1379 if (doGc) { 1380 // Force a gc to clear up stale containers. 1381 Runtime.getRuntime().gc(); 1382 } 1383 if (msg.obj != null) { 1384 @SuppressWarnings("unchecked") 1385 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1386 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1387 // Unload containers 1388 unloadAllContainers(args); 1389 } 1390 if (reportStatus) { 1391 try { 1392 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1393 PackageHelper.getMountService().finishMediaUpdate(); 1394 } catch (RemoteException e) { 1395 Log.e(TAG, "MountService not running?"); 1396 } 1397 } 1398 } break; 1399 case WRITE_SETTINGS: { 1400 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1401 synchronized (mPackages) { 1402 removeMessages(WRITE_SETTINGS); 1403 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1404 mSettings.writeLPr(); 1405 mDirtyUsers.clear(); 1406 } 1407 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1408 } break; 1409 case WRITE_PACKAGE_RESTRICTIONS: { 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1411 synchronized (mPackages) { 1412 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1413 for (int userId : mDirtyUsers) { 1414 mSettings.writePackageRestrictionsLPr(userId); 1415 } 1416 mDirtyUsers.clear(); 1417 } 1418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1419 } break; 1420 case CHECK_PENDING_VERIFICATION: { 1421 final int verificationId = msg.arg1; 1422 final PackageVerificationState state = mPendingVerification.get(verificationId); 1423 1424 if ((state != null) && !state.timeoutExtended()) { 1425 final InstallArgs args = state.getInstallArgs(); 1426 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1427 1428 Slog.i(TAG, "Verification timed out for " + originUri); 1429 mPendingVerification.remove(verificationId); 1430 1431 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1432 1433 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1434 Slog.i(TAG, "Continuing with installation of " + originUri); 1435 state.setVerifierResponse(Binder.getCallingUid(), 1436 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1437 broadcastPackageVerified(verificationId, originUri, 1438 PackageManager.VERIFICATION_ALLOW, 1439 state.getInstallArgs().getUser()); 1440 try { 1441 ret = args.copyApk(mContainerService, true); 1442 } catch (RemoteException e) { 1443 Slog.e(TAG, "Could not contact the ContainerService"); 1444 } 1445 } else { 1446 broadcastPackageVerified(verificationId, originUri, 1447 PackageManager.VERIFICATION_REJECT, 1448 state.getInstallArgs().getUser()); 1449 } 1450 1451 processPendingInstall(args, ret); 1452 mHandler.sendEmptyMessage(MCS_UNBIND); 1453 } 1454 break; 1455 } 1456 case PACKAGE_VERIFIED: { 1457 final int verificationId = msg.arg1; 1458 1459 final PackageVerificationState state = mPendingVerification.get(verificationId); 1460 if (state == null) { 1461 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1462 break; 1463 } 1464 1465 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1466 1467 state.setVerifierResponse(response.callerUid, response.code); 1468 1469 if (state.isVerificationComplete()) { 1470 mPendingVerification.remove(verificationId); 1471 1472 final InstallArgs args = state.getInstallArgs(); 1473 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1474 1475 int ret; 1476 if (state.isInstallAllowed()) { 1477 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1478 broadcastPackageVerified(verificationId, originUri, 1479 response.code, state.getInstallArgs().getUser()); 1480 try { 1481 ret = args.copyApk(mContainerService, true); 1482 } catch (RemoteException e) { 1483 Slog.e(TAG, "Could not contact the ContainerService"); 1484 } 1485 } else { 1486 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1487 } 1488 1489 processPendingInstall(args, ret); 1490 1491 mHandler.sendEmptyMessage(MCS_UNBIND); 1492 } 1493 1494 break; 1495 } 1496 case START_INTENT_FILTER_VERIFICATIONS: { 1497 int userId = msg.arg1; 1498 int verifierUid = msg.arg2; 1499 PackageParser.Package pkg = (PackageParser.Package)msg.obj; 1500 1501 verifyIntentFiltersIfNeeded(userId, verifierUid, pkg); 1502 break; 1503 } 1504 case INTENT_FILTER_VERIFIED: { 1505 final int verificationId = msg.arg1; 1506 1507 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1508 verificationId); 1509 if (state == null) { 1510 Slog.w(TAG, "Invalid IntentFilter verification token " 1511 + verificationId + " received"); 1512 break; 1513 } 1514 1515 final int userId = state.getUserId(); 1516 1517 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1518 "Processing IntentFilter verification with token:" 1519 + verificationId + " and userId:" + userId); 1520 1521 final IntentFilterVerificationResponse response = 1522 (IntentFilterVerificationResponse) msg.obj; 1523 1524 state.setVerifierResponse(response.callerUid, response.code); 1525 1526 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1527 "IntentFilter verification with token:" + verificationId 1528 + " and userId:" + userId 1529 + " is settings verifier response with response code:" 1530 + response.code); 1531 1532 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1533 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1534 + response.getFailedDomainsString()); 1535 } 1536 1537 if (state.isVerificationComplete()) { 1538 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1539 } else { 1540 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1541 "IntentFilter verification with token:" + verificationId 1542 + " was not said to be complete"); 1543 } 1544 1545 break; 1546 } 1547 } 1548 } 1549 } 1550 1551 private StorageEventListener mStorageListener = new StorageEventListener() { 1552 @Override 1553 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1554 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1555 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1556 // TODO: ensure that private directories exist for all active users 1557 // TODO: remove user data whose serial number doesn't match 1558 loadPrivatePackages(vol); 1559 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1560 unloadPrivatePackages(vol); 1561 } 1562 } 1563 1564 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1565 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1566 updateExternalMediaStatus(true, false); 1567 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1568 updateExternalMediaStatus(false, false); 1569 } 1570 } 1571 } 1572 1573 @Override 1574 public void onVolumeForgotten(String fsUuid) { 1575 // TODO: remove all packages hosted on this uuid 1576 } 1577 }; 1578 1579 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) { 1580 if (userId >= UserHandle.USER_OWNER) { 1581 grantRequestedRuntimePermissionsForUser(pkg, userId); 1582 } else if (userId == UserHandle.USER_ALL) { 1583 for (int someUserId : UserManagerService.getInstance().getUserIds()) { 1584 grantRequestedRuntimePermissionsForUser(pkg, someUserId); 1585 } 1586 } 1587 } 1588 1589 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) { 1590 SettingBase sb = (SettingBase) pkg.mExtras; 1591 if (sb == null) { 1592 return; 1593 } 1594 1595 PermissionsState permissionsState = sb.getPermissionsState(); 1596 1597 for (String permission : pkg.requestedPermissions) { 1598 BasePermission bp = mSettings.mPermissions.get(permission); 1599 if (bp != null && bp.isRuntime()) { 1600 permissionsState.grantRuntimePermission(bp, userId); 1601 } 1602 } 1603 } 1604 1605 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1606 Bundle extras = null; 1607 switch (res.returnCode) { 1608 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1609 extras = new Bundle(); 1610 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1611 res.origPermission); 1612 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1613 res.origPackage); 1614 break; 1615 } 1616 case PackageManager.INSTALL_SUCCEEDED: { 1617 extras = new Bundle(); 1618 extras.putBoolean(Intent.EXTRA_REPLACING, 1619 res.removedInfo != null && res.removedInfo.removedPackage != null); 1620 break; 1621 } 1622 } 1623 return extras; 1624 } 1625 1626 void scheduleWriteSettingsLocked() { 1627 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1628 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1629 } 1630 } 1631 1632 void scheduleWritePackageRestrictionsLocked(int userId) { 1633 if (!sUserManager.exists(userId)) return; 1634 mDirtyUsers.add(userId); 1635 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1636 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1637 } 1638 } 1639 1640 public static PackageManagerService main(Context context, Installer installer, 1641 boolean factoryTest, boolean onlyCore) { 1642 PackageManagerService m = new PackageManagerService(context, installer, 1643 factoryTest, onlyCore); 1644 ServiceManager.addService("package", m); 1645 return m; 1646 } 1647 1648 static String[] splitString(String str, char sep) { 1649 int count = 1; 1650 int i = 0; 1651 while ((i=str.indexOf(sep, i)) >= 0) { 1652 count++; 1653 i++; 1654 } 1655 1656 String[] res = new String[count]; 1657 i=0; 1658 count = 0; 1659 int lastI=0; 1660 while ((i=str.indexOf(sep, i)) >= 0) { 1661 res[count] = str.substring(lastI, i); 1662 count++; 1663 i++; 1664 lastI = i; 1665 } 1666 res[count] = str.substring(lastI, str.length()); 1667 return res; 1668 } 1669 1670 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1671 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1672 Context.DISPLAY_SERVICE); 1673 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1674 } 1675 1676 public PackageManagerService(Context context, Installer installer, 1677 boolean factoryTest, boolean onlyCore) { 1678 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1679 SystemClock.uptimeMillis()); 1680 1681 if (mSdkVersion <= 0) { 1682 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1683 } 1684 1685 mContext = context; 1686 mFactoryTest = factoryTest; 1687 mOnlyCore = onlyCore; 1688 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1689 mMetrics = new DisplayMetrics(); 1690 mSettings = new Settings(mPackages); 1691 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1692 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1693 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1694 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1695 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1696 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1697 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1698 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1699 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1700 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1701 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1702 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1703 1704 // TODO: add a property to control this? 1705 long dexOptLRUThresholdInMinutes; 1706 if (mLazyDexOpt) { 1707 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1708 } else { 1709 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1710 } 1711 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1712 1713 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1714 if (separateProcesses != null && separateProcesses.length() > 0) { 1715 if ("*".equals(separateProcesses)) { 1716 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1717 mSeparateProcesses = null; 1718 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1719 } else { 1720 mDefParseFlags = 0; 1721 mSeparateProcesses = separateProcesses.split(","); 1722 Slog.w(TAG, "Running with debug.separate_processes: " 1723 + separateProcesses); 1724 } 1725 } else { 1726 mDefParseFlags = 0; 1727 mSeparateProcesses = null; 1728 } 1729 1730 mInstaller = installer; 1731 mPackageDexOptimizer = new PackageDexOptimizer(this); 1732 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 1733 1734 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 1735 FgThread.get().getLooper()); 1736 1737 getDefaultDisplayMetrics(context, mMetrics); 1738 1739 SystemConfig systemConfig = SystemConfig.getInstance(); 1740 mGlobalGids = systemConfig.getGlobalGids(); 1741 mSystemPermissions = systemConfig.getSystemPermissions(); 1742 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1743 1744 synchronized (mInstallLock) { 1745 // writer 1746 synchronized (mPackages) { 1747 mHandlerThread = new ServiceThread(TAG, 1748 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1749 mHandlerThread.start(); 1750 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1751 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1752 1753 File dataDir = Environment.getDataDirectory(); 1754 mAppDataDir = new File(dataDir, "data"); 1755 mAppInstallDir = new File(dataDir, "app"); 1756 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1757 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1758 mUserAppDataDir = new File(dataDir, "user"); 1759 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1760 1761 sUserManager = new UserManagerService(context, this, 1762 mInstallLock, mPackages); 1763 1764 // Propagate permission configuration in to package manager. 1765 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1766 = systemConfig.getPermissions(); 1767 for (int i=0; i<permConfig.size(); i++) { 1768 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1769 BasePermission bp = mSettings.mPermissions.get(perm.name); 1770 if (bp == null) { 1771 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1772 mSettings.mPermissions.put(perm.name, bp); 1773 } 1774 if (perm.gids != null) { 1775 bp.setGids(perm.gids, perm.perUser); 1776 } 1777 } 1778 1779 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1780 for (int i=0; i<libConfig.size(); i++) { 1781 mSharedLibraries.put(libConfig.keyAt(i), 1782 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1783 } 1784 1785 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1786 1787 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1788 mSdkVersion, mOnlyCore); 1789 1790 String customResolverActivity = Resources.getSystem().getString( 1791 R.string.config_customResolverActivity); 1792 if (TextUtils.isEmpty(customResolverActivity)) { 1793 customResolverActivity = null; 1794 } else { 1795 mCustomResolverComponentName = ComponentName.unflattenFromString( 1796 customResolverActivity); 1797 } 1798 1799 long startTime = SystemClock.uptimeMillis(); 1800 1801 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1802 startTime); 1803 1804 // Set flag to monitor and not change apk file paths when 1805 // scanning install directories. 1806 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1807 1808 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1809 1810 /** 1811 * Add everything in the in the boot class path to the 1812 * list of process files because dexopt will have been run 1813 * if necessary during zygote startup. 1814 */ 1815 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1816 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1817 1818 if (bootClassPath != null) { 1819 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1820 for (String element : bootClassPathElements) { 1821 alreadyDexOpted.add(element); 1822 } 1823 } else { 1824 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1825 } 1826 1827 if (systemServerClassPath != null) { 1828 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1829 for (String element : systemServerClassPathElements) { 1830 alreadyDexOpted.add(element); 1831 } 1832 } else { 1833 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1834 } 1835 1836 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 1837 final String[] dexCodeInstructionSets = 1838 getDexCodeInstructionSets( 1839 allInstructionSets.toArray(new String[allInstructionSets.size()])); 1840 1841 /** 1842 * Ensure all external libraries have had dexopt run on them. 1843 */ 1844 if (mSharedLibraries.size() > 0) { 1845 // NOTE: For now, we're compiling these system "shared libraries" 1846 // (and framework jars) into all available architectures. It's possible 1847 // to compile them only when we come across an app that uses them (there's 1848 // already logic for that in scanPackageLI) but that adds some complexity. 1849 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1850 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1851 final String lib = libEntry.path; 1852 if (lib == null) { 1853 continue; 1854 } 1855 1856 try { 1857 int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false); 1858 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1859 alreadyDexOpted.add(lib); 1860 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1861 } 1862 } catch (FileNotFoundException e) { 1863 Slog.w(TAG, "Library not found: " + lib); 1864 } catch (IOException e) { 1865 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1866 + e.getMessage()); 1867 } 1868 } 1869 } 1870 } 1871 1872 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1873 1874 // Gross hack for now: we know this file doesn't contain any 1875 // code, so don't dexopt it to avoid the resulting log spew. 1876 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1877 1878 // Gross hack for now: we know this file is only part of 1879 // the boot class path for art, so don't dexopt it to 1880 // avoid the resulting log spew. 1881 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1882 1883 /** 1884 * There are a number of commands implemented in Java, which 1885 * we currently need to do the dexopt on so that they can be 1886 * run from a non-root shell. 1887 */ 1888 String[] frameworkFiles = frameworkDir.list(); 1889 if (frameworkFiles != null) { 1890 // TODO: We could compile these only for the most preferred ABI. We should 1891 // first double check that the dex files for these commands are not referenced 1892 // by other system apps. 1893 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1894 for (int i=0; i<frameworkFiles.length; i++) { 1895 File libPath = new File(frameworkDir, frameworkFiles[i]); 1896 String path = libPath.getPath(); 1897 // Skip the file if we already did it. 1898 if (alreadyDexOpted.contains(path)) { 1899 continue; 1900 } 1901 // Skip the file if it is not a type we want to dexopt. 1902 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1903 continue; 1904 } 1905 try { 1906 int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false); 1907 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 1908 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded); 1909 } 1910 } catch (FileNotFoundException e) { 1911 Slog.w(TAG, "Jar not found: " + path); 1912 } catch (IOException e) { 1913 Slog.w(TAG, "Exception reading jar: " + path, e); 1914 } 1915 } 1916 } 1917 } 1918 1919 // Collect vendor overlay packages. 1920 // (Do this before scanning any apps.) 1921 // For security and version matching reason, only consider 1922 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1923 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1924 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1925 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1926 1927 // Find base frameworks (resource packages without code). 1928 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1929 | PackageParser.PARSE_IS_SYSTEM_DIR 1930 | PackageParser.PARSE_IS_PRIVILEGED, 1931 scanFlags | SCAN_NO_DEX, 0); 1932 1933 // Collected privileged system packages. 1934 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1935 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1936 | PackageParser.PARSE_IS_SYSTEM_DIR 1937 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1938 1939 // Collect ordinary system packages. 1940 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1941 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1942 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1943 1944 // Collect all vendor packages. 1945 File vendorAppDir = new File("/vendor/app"); 1946 try { 1947 vendorAppDir = vendorAppDir.getCanonicalFile(); 1948 } catch (IOException e) { 1949 // failed to look up canonical path, continue with original one 1950 } 1951 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1952 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1953 1954 // Collect all OEM packages. 1955 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1956 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1957 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1958 1959 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1960 mInstaller.moveFiles(); 1961 1962 // Prune any system packages that no longer exist. 1963 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1964 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1965 if (!mOnlyCore) { 1966 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1967 while (psit.hasNext()) { 1968 PackageSetting ps = psit.next(); 1969 1970 /* 1971 * If this is not a system app, it can't be a 1972 * disable system app. 1973 */ 1974 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1975 continue; 1976 } 1977 1978 /* 1979 * If the package is scanned, it's not erased. 1980 */ 1981 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1982 if (scannedPkg != null) { 1983 /* 1984 * If the system app is both scanned and in the 1985 * disabled packages list, then it must have been 1986 * added via OTA. Remove it from the currently 1987 * scanned package so the previously user-installed 1988 * application can be scanned. 1989 */ 1990 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1991 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1992 + ps.name + "; removing system app. Last known codePath=" 1993 + ps.codePathString + ", installStatus=" + ps.installStatus 1994 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1995 + scannedPkg.mVersionCode); 1996 removePackageLI(ps, true); 1997 expectingBetter.put(ps.name, ps.codePath); 1998 } 1999 2000 continue; 2001 } 2002 2003 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2004 psit.remove(); 2005 logCriticalInfo(Log.WARN, "System package " + ps.name 2006 + " no longer exists; wiping its data"); 2007 removeDataDirsLI(null, ps.name); 2008 } else { 2009 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2010 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2011 possiblyDeletedUpdatedSystemApps.add(ps.name); 2012 } 2013 } 2014 } 2015 } 2016 2017 //look for any incomplete package installations 2018 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2019 //clean up list 2020 for(int i = 0; i < deletePkgsList.size(); i++) { 2021 //clean up here 2022 cleanupInstallFailedPackage(deletePkgsList.get(i)); 2023 } 2024 //delete tmp files 2025 deleteTempPackageFiles(); 2026 2027 // Remove any shared userIDs that have no associated packages 2028 mSettings.pruneSharedUsersLPw(); 2029 2030 if (!mOnlyCore) { 2031 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2032 SystemClock.uptimeMillis()); 2033 scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2034 2035 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2036 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2037 2038 /** 2039 * Remove disable package settings for any updated system 2040 * apps that were removed via an OTA. If they're not a 2041 * previously-updated app, remove them completely. 2042 * Otherwise, just revoke their system-level permissions. 2043 */ 2044 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2045 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2046 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2047 2048 String msg; 2049 if (deletedPkg == null) { 2050 msg = "Updated system package " + deletedAppName 2051 + " no longer exists; wiping its data"; 2052 removeDataDirsLI(null, deletedAppName); 2053 } else { 2054 msg = "Updated system app + " + deletedAppName 2055 + " no longer present; removing system privileges for " 2056 + deletedAppName; 2057 2058 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2059 2060 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2061 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2062 } 2063 logCriticalInfo(Log.WARN, msg); 2064 } 2065 2066 /** 2067 * Make sure all system apps that we expected to appear on 2068 * the userdata partition actually showed up. If they never 2069 * appeared, crawl back and revive the system version. 2070 */ 2071 for (int i = 0; i < expectingBetter.size(); i++) { 2072 final String packageName = expectingBetter.keyAt(i); 2073 if (!mPackages.containsKey(packageName)) { 2074 final File scanFile = expectingBetter.valueAt(i); 2075 2076 logCriticalInfo(Log.WARN, "Expected better " + packageName 2077 + " but never showed up; reverting to system"); 2078 2079 final int reparseFlags; 2080 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2081 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2082 | PackageParser.PARSE_IS_SYSTEM_DIR 2083 | PackageParser.PARSE_IS_PRIVILEGED; 2084 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2085 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2086 | PackageParser.PARSE_IS_SYSTEM_DIR; 2087 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2088 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2089 | PackageParser.PARSE_IS_SYSTEM_DIR; 2090 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2091 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2092 | PackageParser.PARSE_IS_SYSTEM_DIR; 2093 } else { 2094 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2095 continue; 2096 } 2097 2098 mSettings.enableSystemPackageLPw(packageName); 2099 2100 try { 2101 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 2102 } catch (PackageManagerException e) { 2103 Slog.e(TAG, "Failed to parse original system package: " 2104 + e.getMessage()); 2105 } 2106 } 2107 } 2108 } 2109 2110 // Now that we know all of the shared libraries, update all clients to have 2111 // the correct library paths. 2112 updateAllSharedLibrariesLPw(); 2113 2114 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2115 // NOTE: We ignore potential failures here during a system scan (like 2116 // the rest of the commands above) because there's precious little we 2117 // can do about it. A settings error is reported, though. 2118 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2119 false /* force dexopt */, false /* defer dexopt */); 2120 } 2121 2122 // Now that we know all the packages we are keeping, 2123 // read and update their last usage times. 2124 mPackageUsage.readLP(); 2125 2126 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2127 SystemClock.uptimeMillis()); 2128 Slog.i(TAG, "Time to scan packages: " 2129 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2130 + " seconds"); 2131 2132 // If the platform SDK has changed since the last time we booted, 2133 // we need to re-grant app permission to catch any new ones that 2134 // appear. This is really a hack, and means that apps can in some 2135 // cases get permissions that the user didn't initially explicitly 2136 // allow... it would be nice to have some better way to handle 2137 // this situation. 2138 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 2139 != mSdkVersion; 2140 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 2141 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 2142 + "; regranting permissions for internal storage"); 2143 mSettings.mInternalSdkPlatform = mSdkVersion; 2144 2145 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 2146 | (regrantPermissions 2147 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 2148 : 0)); 2149 2150 // If this is the first boot, and it is a normal boot, then 2151 // we need to initialize the default preferred apps. 2152 if (!mRestoredSettings && !onlyCore) { 2153 mSettings.readDefaultPreferredAppsLPw(this, 0); 2154 } 2155 2156 // If this is first boot after an OTA, and a normal boot, then 2157 // we need to clear code cache directories. 2158 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 2159 if (mIsUpgrade && !onlyCore) { 2160 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2161 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2162 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2163 deleteCodeCacheDirsLI(ps.volumeUuid, ps.name); 2164 } 2165 mSettings.mFingerprint = Build.FINGERPRINT; 2166 } 2167 2168 primeDomainVerificationsLPw(); 2169 checkDefaultBrowser(); 2170 2171 // All the changes are done during package scanning. 2172 mSettings.updateInternalDatabaseVersion(); 2173 2174 // can downgrade to reader 2175 mSettings.writeLPr(); 2176 2177 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2178 SystemClock.uptimeMillis()); 2179 2180 mRequiredVerifierPackage = getRequiredVerifierLPr(); 2181 2182 mInstallerService = new PackageInstallerService(context, this); 2183 2184 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2185 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2186 mIntentFilterVerifierComponent); 2187 2188 } // synchronized (mPackages) 2189 } // synchronized (mInstallLock) 2190 2191 // Now after opening every single application zip, make sure they 2192 // are all flushed. Not really needed, but keeps things nice and 2193 // tidy. 2194 Runtime.getRuntime().gc(); 2195 } 2196 2197 @Override 2198 public boolean isFirstBoot() { 2199 return !mRestoredSettings; 2200 } 2201 2202 @Override 2203 public boolean isOnlyCoreApps() { 2204 return mOnlyCore; 2205 } 2206 2207 @Override 2208 public boolean isUpgrade() { 2209 return mIsUpgrade; 2210 } 2211 2212 private String getRequiredVerifierLPr() { 2213 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2214 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2215 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 2216 2217 String requiredVerifier = null; 2218 2219 final int N = receivers.size(); 2220 for (int i = 0; i < N; i++) { 2221 final ResolveInfo info = receivers.get(i); 2222 2223 if (info.activityInfo == null) { 2224 continue; 2225 } 2226 2227 final String packageName = info.activityInfo.packageName; 2228 2229 if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 2230 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2231 continue; 2232 } 2233 2234 if (requiredVerifier != null) { 2235 throw new RuntimeException("There can be only one required verifier"); 2236 } 2237 2238 requiredVerifier = packageName; 2239 } 2240 2241 return requiredVerifier; 2242 } 2243 2244 private ComponentName getIntentFilterVerifierComponentNameLPr() { 2245 final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2246 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 2247 PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */); 2248 2249 ComponentName verifierComponentName = null; 2250 2251 int priority = -1000; 2252 final int N = receivers.size(); 2253 for (int i = 0; i < N; i++) { 2254 final ResolveInfo info = receivers.get(i); 2255 2256 if (info.activityInfo == null) { 2257 continue; 2258 } 2259 2260 final String packageName = info.activityInfo.packageName; 2261 2262 final PackageSetting ps = mSettings.mPackages.get(packageName); 2263 if (ps == null) { 2264 continue; 2265 } 2266 2267 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2268 packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) { 2269 continue; 2270 } 2271 2272 // Select the IntentFilterVerifier with the highest priority 2273 if (priority < info.priority) { 2274 priority = info.priority; 2275 verifierComponentName = new ComponentName(packageName, info.activityInfo.name); 2276 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: " 2277 + verifierComponentName + " with priority: " + info.priority); 2278 } 2279 } 2280 2281 return verifierComponentName; 2282 } 2283 2284 private void primeDomainVerificationsLPw() { 2285 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications"); 2286 boolean updated = false; 2287 ArraySet<String> allHostsSet = new ArraySet<>(); 2288 for (PackageParser.Package pkg : mPackages.values()) { 2289 final String packageName = pkg.packageName; 2290 if (!hasDomainURLs(pkg)) { 2291 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " + 2292 "package with no domain URLs: " + packageName); 2293 continue; 2294 } 2295 if (!pkg.isSystemApp()) { 2296 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2297 "No priming domain verifications for a non system package : " + 2298 packageName); 2299 continue; 2300 } 2301 for (PackageParser.Activity a : pkg.activities) { 2302 for (ActivityIntentInfo filter : a.intents) { 2303 if (hasValidDomains(filter)) { 2304 allHostsSet.addAll(filter.getHostsList()); 2305 } 2306 } 2307 } 2308 if (allHostsSet.size() == 0) { 2309 allHostsSet.add("*"); 2310 } 2311 ArrayList<String> allHostsList = new ArrayList<>(allHostsSet); 2312 IntentFilterVerificationInfo ivi = 2313 mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList); 2314 if (ivi != null) { 2315 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2316 "Priming domain verifications for package: " + packageName + 2317 " with hosts:" + ivi.getDomainsString()); 2318 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 2319 updated = true; 2320 } 2321 else { 2322 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2323 "No priming domain verifications for package: " + packageName); 2324 } 2325 allHostsSet.clear(); 2326 } 2327 if (updated) { 2328 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 2329 "Will need to write primed domain verifications"); 2330 } 2331 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications"); 2332 } 2333 2334 private void checkDefaultBrowser() { 2335 final int myUserId = UserHandle.myUserId(); 2336 final String packageName = getDefaultBrowserPackageName(myUserId); 2337 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2338 if (info == null) { 2339 Slog.w(TAG, "Clearing default Browser as its package is no more installed: " + 2340 packageName); 2341 setDefaultBrowserPackageName(null, myUserId); 2342 } 2343 } 2344 2345 @Override 2346 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2347 throws RemoteException { 2348 try { 2349 return super.onTransact(code, data, reply, flags); 2350 } catch (RuntimeException e) { 2351 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2352 Slog.wtf(TAG, "Package Manager Crash", e); 2353 } 2354 throw e; 2355 } 2356 } 2357 2358 void cleanupInstallFailedPackage(PackageSetting ps) { 2359 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 2360 2361 removeDataDirsLI(ps.volumeUuid, ps.name); 2362 if (ps.codePath != null) { 2363 if (ps.codePath.isDirectory()) { 2364 mInstaller.rmPackageDir(ps.codePath.getAbsolutePath()); 2365 } else { 2366 ps.codePath.delete(); 2367 } 2368 } 2369 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 2370 if (ps.resourcePath.isDirectory()) { 2371 FileUtils.deleteContents(ps.resourcePath); 2372 } 2373 ps.resourcePath.delete(); 2374 } 2375 mSettings.removePackageLPw(ps.name); 2376 } 2377 2378 static int[] appendInts(int[] cur, int[] add) { 2379 if (add == null) return cur; 2380 if (cur == null) return add; 2381 final int N = add.length; 2382 for (int i=0; i<N; i++) { 2383 cur = appendInt(cur, add[i]); 2384 } 2385 return cur; 2386 } 2387 2388 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 2389 if (!sUserManager.exists(userId)) return null; 2390 final PackageSetting ps = (PackageSetting) p.mExtras; 2391 if (ps == null) { 2392 return null; 2393 } 2394 2395 final PermissionsState permissionsState = ps.getPermissionsState(); 2396 2397 final int[] gids = permissionsState.computeGids(userId); 2398 final Set<String> permissions = permissionsState.getPermissions(userId); 2399 final PackageUserState state = ps.readUserState(userId); 2400 2401 return PackageParser.generatePackageInfo(p, gids, flags, 2402 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 2403 } 2404 2405 @Override 2406 public boolean isPackageFrozen(String packageName) { 2407 synchronized (mPackages) { 2408 final PackageSetting ps = mSettings.mPackages.get(packageName); 2409 if (ps != null) { 2410 return ps.frozen; 2411 } 2412 } 2413 Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen"); 2414 return true; 2415 } 2416 2417 @Override 2418 public boolean isPackageAvailable(String packageName, int userId) { 2419 if (!sUserManager.exists(userId)) return false; 2420 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 2421 synchronized (mPackages) { 2422 PackageParser.Package p = mPackages.get(packageName); 2423 if (p != null) { 2424 final PackageSetting ps = (PackageSetting) p.mExtras; 2425 if (ps != null) { 2426 final PackageUserState state = ps.readUserState(userId); 2427 if (state != null) { 2428 return PackageParser.isAvailable(state); 2429 } 2430 } 2431 } 2432 } 2433 return false; 2434 } 2435 2436 @Override 2437 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2438 if (!sUserManager.exists(userId)) return null; 2439 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 2440 // reader 2441 synchronized (mPackages) { 2442 PackageParser.Package p = mPackages.get(packageName); 2443 if (DEBUG_PACKAGE_INFO) 2444 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2445 if (p != null) { 2446 return generatePackageInfo(p, flags, userId); 2447 } 2448 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2449 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2450 } 2451 } 2452 return null; 2453 } 2454 2455 @Override 2456 public String[] currentToCanonicalPackageNames(String[] names) { 2457 String[] out = new String[names.length]; 2458 // reader 2459 synchronized (mPackages) { 2460 for (int i=names.length-1; i>=0; i--) { 2461 PackageSetting ps = mSettings.mPackages.get(names[i]); 2462 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2463 } 2464 } 2465 return out; 2466 } 2467 2468 @Override 2469 public String[] canonicalToCurrentPackageNames(String[] names) { 2470 String[] out = new String[names.length]; 2471 // reader 2472 synchronized (mPackages) { 2473 for (int i=names.length-1; i>=0; i--) { 2474 String cur = mSettings.mRenamedPackages.get(names[i]); 2475 out[i] = cur != null ? cur : names[i]; 2476 } 2477 } 2478 return out; 2479 } 2480 2481 @Override 2482 public int getPackageUid(String packageName, int userId) { 2483 if (!sUserManager.exists(userId)) return -1; 2484 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 2485 2486 // reader 2487 synchronized (mPackages) { 2488 PackageParser.Package p = mPackages.get(packageName); 2489 if(p != null) { 2490 return UserHandle.getUid(userId, p.applicationInfo.uid); 2491 } 2492 PackageSetting ps = mSettings.mPackages.get(packageName); 2493 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2494 return -1; 2495 } 2496 p = ps.pkg; 2497 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2498 } 2499 } 2500 2501 @Override 2502 public int[] getPackageGids(String packageName, int userId) throws RemoteException { 2503 if (!sUserManager.exists(userId)) { 2504 return null; 2505 } 2506 2507 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2508 "getPackageGids"); 2509 2510 // reader 2511 synchronized (mPackages) { 2512 PackageParser.Package p = mPackages.get(packageName); 2513 if (DEBUG_PACKAGE_INFO) { 2514 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2515 } 2516 if (p != null) { 2517 PackageSetting ps = (PackageSetting) p.mExtras; 2518 return ps.getPermissionsState().computeGids(userId); 2519 } 2520 } 2521 2522 return null; 2523 } 2524 2525 static PermissionInfo generatePermissionInfo( 2526 BasePermission bp, int flags) { 2527 if (bp.perm != null) { 2528 return PackageParser.generatePermissionInfo(bp.perm, flags); 2529 } 2530 PermissionInfo pi = new PermissionInfo(); 2531 pi.name = bp.name; 2532 pi.packageName = bp.sourcePackage; 2533 pi.nonLocalizedLabel = bp.name; 2534 pi.protectionLevel = bp.protectionLevel; 2535 return pi; 2536 } 2537 2538 @Override 2539 public PermissionInfo getPermissionInfo(String name, int flags) { 2540 // reader 2541 synchronized (mPackages) { 2542 final BasePermission p = mSettings.mPermissions.get(name); 2543 if (p != null) { 2544 return generatePermissionInfo(p, flags); 2545 } 2546 return null; 2547 } 2548 } 2549 2550 @Override 2551 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2552 // reader 2553 synchronized (mPackages) { 2554 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2555 for (BasePermission p : mSettings.mPermissions.values()) { 2556 if (group == null) { 2557 if (p.perm == null || p.perm.info.group == null) { 2558 out.add(generatePermissionInfo(p, flags)); 2559 } 2560 } else { 2561 if (p.perm != null && group.equals(p.perm.info.group)) { 2562 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2563 } 2564 } 2565 } 2566 2567 if (out.size() > 0) { 2568 return out; 2569 } 2570 return mPermissionGroups.containsKey(group) ? out : null; 2571 } 2572 } 2573 2574 @Override 2575 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2576 // reader 2577 synchronized (mPackages) { 2578 return PackageParser.generatePermissionGroupInfo( 2579 mPermissionGroups.get(name), flags); 2580 } 2581 } 2582 2583 @Override 2584 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2585 // reader 2586 synchronized (mPackages) { 2587 final int N = mPermissionGroups.size(); 2588 ArrayList<PermissionGroupInfo> out 2589 = new ArrayList<PermissionGroupInfo>(N); 2590 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2591 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2592 } 2593 return out; 2594 } 2595 } 2596 2597 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2598 int userId) { 2599 if (!sUserManager.exists(userId)) return null; 2600 PackageSetting ps = mSettings.mPackages.get(packageName); 2601 if (ps != null) { 2602 if (ps.pkg == null) { 2603 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2604 flags, userId); 2605 if (pInfo != null) { 2606 return pInfo.applicationInfo; 2607 } 2608 return null; 2609 } 2610 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2611 ps.readUserState(userId), userId); 2612 } 2613 return null; 2614 } 2615 2616 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2617 int userId) { 2618 if (!sUserManager.exists(userId)) return null; 2619 PackageSetting ps = mSettings.mPackages.get(packageName); 2620 if (ps != null) { 2621 PackageParser.Package pkg = ps.pkg; 2622 if (pkg == null) { 2623 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2624 return null; 2625 } 2626 // Only data remains, so we aren't worried about code paths 2627 pkg = new PackageParser.Package(packageName); 2628 pkg.applicationInfo.packageName = packageName; 2629 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2630 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2631 pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid, 2632 packageName, userId).getAbsolutePath(); 2633 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2634 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2635 } 2636 return generatePackageInfo(pkg, flags, userId); 2637 } 2638 return null; 2639 } 2640 2641 @Override 2642 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2643 if (!sUserManager.exists(userId)) return null; 2644 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2645 // writer 2646 synchronized (mPackages) { 2647 PackageParser.Package p = mPackages.get(packageName); 2648 if (DEBUG_PACKAGE_INFO) Log.v( 2649 TAG, "getApplicationInfo " + packageName 2650 + ": " + p); 2651 if (p != null) { 2652 PackageSetting ps = mSettings.mPackages.get(packageName); 2653 if (ps == null) return null; 2654 // Note: isEnabledLP() does not apply here - always return info 2655 return PackageParser.generateApplicationInfo( 2656 p, flags, ps.readUserState(userId), userId); 2657 } 2658 if ("android".equals(packageName)||"system".equals(packageName)) { 2659 return mAndroidApplication; 2660 } 2661 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2662 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2663 } 2664 } 2665 return null; 2666 } 2667 2668 @Override 2669 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 2670 final IPackageDataObserver observer) { 2671 mContext.enforceCallingOrSelfPermission( 2672 android.Manifest.permission.CLEAR_APP_CACHE, null); 2673 // Queue up an async operation since clearing cache may take a little while. 2674 mHandler.post(new Runnable() { 2675 public void run() { 2676 mHandler.removeCallbacks(this); 2677 int retCode = -1; 2678 synchronized (mInstallLock) { 2679 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2680 if (retCode < 0) { 2681 Slog.w(TAG, "Couldn't clear application caches"); 2682 } 2683 } 2684 if (observer != null) { 2685 try { 2686 observer.onRemoveCompleted(null, (retCode >= 0)); 2687 } catch (RemoteException e) { 2688 Slog.w(TAG, "RemoveException when invoking call back"); 2689 } 2690 } 2691 } 2692 }); 2693 } 2694 2695 @Override 2696 public void freeStorage(final String volumeUuid, final long freeStorageSize, 2697 final IntentSender pi) { 2698 mContext.enforceCallingOrSelfPermission( 2699 android.Manifest.permission.CLEAR_APP_CACHE, null); 2700 // Queue up an async operation since clearing cache may take a little while. 2701 mHandler.post(new Runnable() { 2702 public void run() { 2703 mHandler.removeCallbacks(this); 2704 int retCode = -1; 2705 synchronized (mInstallLock) { 2706 retCode = mInstaller.freeCache(volumeUuid, freeStorageSize); 2707 if (retCode < 0) { 2708 Slog.w(TAG, "Couldn't clear application caches"); 2709 } 2710 } 2711 if(pi != null) { 2712 try { 2713 // Callback via pending intent 2714 int code = (retCode >= 0) ? 1 : 0; 2715 pi.sendIntent(null, code, null, 2716 null, null); 2717 } catch (SendIntentException e1) { 2718 Slog.i(TAG, "Failed to send pending intent"); 2719 } 2720 } 2721 } 2722 }); 2723 } 2724 2725 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 2726 synchronized (mInstallLock) { 2727 if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) { 2728 throw new IOException("Failed to free enough space"); 2729 } 2730 } 2731 } 2732 2733 @Override 2734 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2735 if (!sUserManager.exists(userId)) return null; 2736 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2737 synchronized (mPackages) { 2738 PackageParser.Activity a = mActivities.mActivities.get(component); 2739 2740 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2741 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2742 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2743 if (ps == null) return null; 2744 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2745 userId); 2746 } 2747 if (mResolveComponentName.equals(component)) { 2748 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2749 new PackageUserState(), userId); 2750 } 2751 } 2752 return null; 2753 } 2754 2755 @Override 2756 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2757 String resolvedType) { 2758 synchronized (mPackages) { 2759 PackageParser.Activity a = mActivities.mActivities.get(component); 2760 if (a == null) { 2761 return false; 2762 } 2763 for (int i=0; i<a.intents.size(); i++) { 2764 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2765 intent.getData(), intent.getCategories(), TAG) >= 0) { 2766 return true; 2767 } 2768 } 2769 return false; 2770 } 2771 } 2772 2773 @Override 2774 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2775 if (!sUserManager.exists(userId)) return null; 2776 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2777 synchronized (mPackages) { 2778 PackageParser.Activity a = mReceivers.mActivities.get(component); 2779 if (DEBUG_PACKAGE_INFO) Log.v( 2780 TAG, "getReceiverInfo " + component + ": " + a); 2781 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2782 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2783 if (ps == null) return null; 2784 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2785 userId); 2786 } 2787 } 2788 return null; 2789 } 2790 2791 @Override 2792 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2793 if (!sUserManager.exists(userId)) return null; 2794 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2795 synchronized (mPackages) { 2796 PackageParser.Service s = mServices.mServices.get(component); 2797 if (DEBUG_PACKAGE_INFO) Log.v( 2798 TAG, "getServiceInfo " + component + ": " + s); 2799 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2800 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2801 if (ps == null) return null; 2802 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2803 userId); 2804 } 2805 } 2806 return null; 2807 } 2808 2809 @Override 2810 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2811 if (!sUserManager.exists(userId)) return null; 2812 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2813 synchronized (mPackages) { 2814 PackageParser.Provider p = mProviders.mProviders.get(component); 2815 if (DEBUG_PACKAGE_INFO) Log.v( 2816 TAG, "getProviderInfo " + component + ": " + p); 2817 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2818 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2819 if (ps == null) return null; 2820 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2821 userId); 2822 } 2823 } 2824 return null; 2825 } 2826 2827 @Override 2828 public String[] getSystemSharedLibraryNames() { 2829 Set<String> libSet; 2830 synchronized (mPackages) { 2831 libSet = mSharedLibraries.keySet(); 2832 int size = libSet.size(); 2833 if (size > 0) { 2834 String[] libs = new String[size]; 2835 libSet.toArray(libs); 2836 return libs; 2837 } 2838 } 2839 return null; 2840 } 2841 2842 /** 2843 * @hide 2844 */ 2845 PackageParser.Package findSharedNonSystemLibrary(String libName) { 2846 synchronized (mPackages) { 2847 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 2848 if (lib != null && lib.apk != null) { 2849 return mPackages.get(lib.apk); 2850 } 2851 } 2852 return null; 2853 } 2854 2855 @Override 2856 public FeatureInfo[] getSystemAvailableFeatures() { 2857 Collection<FeatureInfo> featSet; 2858 synchronized (mPackages) { 2859 featSet = mAvailableFeatures.values(); 2860 int size = featSet.size(); 2861 if (size > 0) { 2862 FeatureInfo[] features = new FeatureInfo[size+1]; 2863 featSet.toArray(features); 2864 FeatureInfo fi = new FeatureInfo(); 2865 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2866 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2867 features[size] = fi; 2868 return features; 2869 } 2870 } 2871 return null; 2872 } 2873 2874 @Override 2875 public boolean hasSystemFeature(String name) { 2876 synchronized (mPackages) { 2877 return mAvailableFeatures.containsKey(name); 2878 } 2879 } 2880 2881 private void checkValidCaller(int uid, int userId) { 2882 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2883 return; 2884 2885 throw new SecurityException("Caller uid=" + uid 2886 + " is not privileged to communicate with user=" + userId); 2887 } 2888 2889 @Override 2890 public int checkPermission(String permName, String pkgName, int userId) { 2891 if (!sUserManager.exists(userId)) { 2892 return PackageManager.PERMISSION_DENIED; 2893 } 2894 2895 synchronized (mPackages) { 2896 final PackageParser.Package p = mPackages.get(pkgName); 2897 if (p != null && p.mExtras != null) { 2898 final PackageSetting ps = (PackageSetting) p.mExtras; 2899 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2900 return PackageManager.PERMISSION_GRANTED; 2901 } 2902 } 2903 } 2904 2905 return PackageManager.PERMISSION_DENIED; 2906 } 2907 2908 @Override 2909 public int checkUidPermission(String permName, int uid) { 2910 final int userId = UserHandle.getUserId(uid); 2911 2912 if (!sUserManager.exists(userId)) { 2913 return PackageManager.PERMISSION_DENIED; 2914 } 2915 2916 synchronized (mPackages) { 2917 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2918 if (obj != null) { 2919 final SettingBase ps = (SettingBase) obj; 2920 if (ps.getPermissionsState().hasPermission(permName, userId)) { 2921 return PackageManager.PERMISSION_GRANTED; 2922 } 2923 } else { 2924 ArraySet<String> perms = mSystemPermissions.get(uid); 2925 if (perms != null && perms.contains(permName)) { 2926 return PackageManager.PERMISSION_GRANTED; 2927 } 2928 } 2929 } 2930 2931 return PackageManager.PERMISSION_DENIED; 2932 } 2933 2934 /** 2935 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2936 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2937 * @param checkShell TODO(yamasani): 2938 * @param message the message to log on security exception 2939 */ 2940 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2941 boolean checkShell, String message) { 2942 if (userId < 0) { 2943 throw new IllegalArgumentException("Invalid userId " + userId); 2944 } 2945 if (checkShell) { 2946 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2947 } 2948 if (userId == UserHandle.getUserId(callingUid)) return; 2949 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2950 if (requireFullPermission) { 2951 mContext.enforceCallingOrSelfPermission( 2952 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2953 } else { 2954 try { 2955 mContext.enforceCallingOrSelfPermission( 2956 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2957 } catch (SecurityException se) { 2958 mContext.enforceCallingOrSelfPermission( 2959 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2960 } 2961 } 2962 } 2963 } 2964 2965 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2966 if (callingUid == Process.SHELL_UID) { 2967 if (userHandle >= 0 2968 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2969 throw new SecurityException("Shell does not have permission to access user " 2970 + userHandle); 2971 } else if (userHandle < 0) { 2972 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2973 + Debug.getCallers(3)); 2974 } 2975 } 2976 } 2977 2978 private BasePermission findPermissionTreeLP(String permName) { 2979 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2980 if (permName.startsWith(bp.name) && 2981 permName.length() > bp.name.length() && 2982 permName.charAt(bp.name.length()) == '.') { 2983 return bp; 2984 } 2985 } 2986 return null; 2987 } 2988 2989 private BasePermission checkPermissionTreeLP(String permName) { 2990 if (permName != null) { 2991 BasePermission bp = findPermissionTreeLP(permName); 2992 if (bp != null) { 2993 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2994 return bp; 2995 } 2996 throw new SecurityException("Calling uid " 2997 + Binder.getCallingUid() 2998 + " is not allowed to add to permission tree " 2999 + bp.name + " owned by uid " + bp.uid); 3000 } 3001 } 3002 throw new SecurityException("No permission tree found for " + permName); 3003 } 3004 3005 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3006 if (s1 == null) { 3007 return s2 == null; 3008 } 3009 if (s2 == null) { 3010 return false; 3011 } 3012 if (s1.getClass() != s2.getClass()) { 3013 return false; 3014 } 3015 return s1.equals(s2); 3016 } 3017 3018 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3019 if (pi1.icon != pi2.icon) return false; 3020 if (pi1.logo != pi2.logo) return false; 3021 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3022 if (!compareStrings(pi1.name, pi2.name)) return false; 3023 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3024 // We'll take care of setting this one. 3025 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3026 // These are not currently stored in settings. 3027 //if (!compareStrings(pi1.group, pi2.group)) return false; 3028 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3029 //if (pi1.labelRes != pi2.labelRes) return false; 3030 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3031 return true; 3032 } 3033 3034 int permissionInfoFootprint(PermissionInfo info) { 3035 int size = info.name.length(); 3036 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3037 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3038 return size; 3039 } 3040 3041 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3042 int size = 0; 3043 for (BasePermission perm : mSettings.mPermissions.values()) { 3044 if (perm.uid == tree.uid) { 3045 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3046 } 3047 } 3048 return size; 3049 } 3050 3051 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3052 // We calculate the max size of permissions defined by this uid and throw 3053 // if that plus the size of 'info' would exceed our stated maximum. 3054 if (tree.uid != Process.SYSTEM_UID) { 3055 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3056 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3057 throw new SecurityException("Permission tree size cap exceeded"); 3058 } 3059 } 3060 } 3061 3062 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3063 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3064 throw new SecurityException("Label must be specified in permission"); 3065 } 3066 BasePermission tree = checkPermissionTreeLP(info.name); 3067 BasePermission bp = mSettings.mPermissions.get(info.name); 3068 boolean added = bp == null; 3069 boolean changed = true; 3070 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3071 if (added) { 3072 enforcePermissionCapLocked(info, tree); 3073 bp = new BasePermission(info.name, tree.sourcePackage, 3074 BasePermission.TYPE_DYNAMIC); 3075 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3076 throw new SecurityException( 3077 "Not allowed to modify non-dynamic permission " 3078 + info.name); 3079 } else { 3080 if (bp.protectionLevel == fixedLevel 3081 && bp.perm.owner.equals(tree.perm.owner) 3082 && bp.uid == tree.uid 3083 && comparePermissionInfos(bp.perm.info, info)) { 3084 changed = false; 3085 } 3086 } 3087 bp.protectionLevel = fixedLevel; 3088 info = new PermissionInfo(info); 3089 info.protectionLevel = fixedLevel; 3090 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3091 bp.perm.info.packageName = tree.perm.info.packageName; 3092 bp.uid = tree.uid; 3093 if (added) { 3094 mSettings.mPermissions.put(info.name, bp); 3095 } 3096 if (changed) { 3097 if (!async) { 3098 mSettings.writeLPr(); 3099 } else { 3100 scheduleWriteSettingsLocked(); 3101 } 3102 } 3103 return added; 3104 } 3105 3106 @Override 3107 public boolean addPermission(PermissionInfo info) { 3108 synchronized (mPackages) { 3109 return addPermissionLocked(info, false); 3110 } 3111 } 3112 3113 @Override 3114 public boolean addPermissionAsync(PermissionInfo info) { 3115 synchronized (mPackages) { 3116 return addPermissionLocked(info, true); 3117 } 3118 } 3119 3120 @Override 3121 public void removePermission(String name) { 3122 synchronized (mPackages) { 3123 checkPermissionTreeLP(name); 3124 BasePermission bp = mSettings.mPermissions.get(name); 3125 if (bp != null) { 3126 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3127 throw new SecurityException( 3128 "Not allowed to modify non-dynamic permission " 3129 + name); 3130 } 3131 mSettings.mPermissions.remove(name); 3132 mSettings.writeLPr(); 3133 } 3134 } 3135 } 3136 3137 private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg, 3138 BasePermission bp) { 3139 int index = pkg.requestedPermissions.indexOf(bp.name); 3140 if (index == -1) { 3141 throw new SecurityException("Package " + pkg.packageName 3142 + " has not requested permission " + bp.name); 3143 } 3144 if (!bp.isRuntime()) { 3145 throw new SecurityException("Permission " + bp.name 3146 + " is not a changeable permission type"); 3147 } 3148 } 3149 3150 @Override 3151 public void grantRuntimePermission(String packageName, String name, int userId) { 3152 if (!sUserManager.exists(userId)) { 3153 Log.e(TAG, "No such user:" + userId); 3154 return; 3155 } 3156 3157 mContext.enforceCallingOrSelfPermission( 3158 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3159 "grantRuntimePermission"); 3160 3161 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3162 "grantRuntimePermission"); 3163 3164 boolean gidsChanged = false; 3165 final SettingBase sb; 3166 3167 synchronized (mPackages) { 3168 final PackageParser.Package pkg = mPackages.get(packageName); 3169 if (pkg == null) { 3170 throw new IllegalArgumentException("Unknown package: " + packageName); 3171 } 3172 3173 final BasePermission bp = mSettings.mPermissions.get(name); 3174 if (bp == null) { 3175 throw new IllegalArgumentException("Unknown permission: " + name); 3176 } 3177 3178 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3179 3180 sb = (SettingBase) pkg.mExtras; 3181 if (sb == null) { 3182 throw new IllegalArgumentException("Unknown package: " + packageName); 3183 } 3184 3185 final PermissionsState permissionsState = sb.getPermissionsState(); 3186 3187 final int flags = permissionsState.getPermissionFlags(name, userId); 3188 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3189 throw new SecurityException("Cannot grant system fixed permission: " 3190 + name + " for package: " + packageName); 3191 } 3192 3193 final int result = permissionsState.grantRuntimePermission(bp, userId); 3194 switch (result) { 3195 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 3196 return; 3197 } 3198 3199 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 3200 gidsChanged = true; 3201 } break; 3202 } 3203 3204 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3205 3206 // Not critical if that is lost - app has to request again. 3207 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3208 } 3209 3210 if (gidsChanged) { 3211 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED); 3212 } 3213 } 3214 3215 @Override 3216 public void revokeRuntimePermission(String packageName, String name, int userId) { 3217 if (!sUserManager.exists(userId)) { 3218 Log.e(TAG, "No such user:" + userId); 3219 return; 3220 } 3221 3222 mContext.enforceCallingOrSelfPermission( 3223 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3224 "revokeRuntimePermission"); 3225 3226 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3227 "revokeRuntimePermission"); 3228 3229 final SettingBase sb; 3230 3231 synchronized (mPackages) { 3232 final PackageParser.Package pkg = mPackages.get(packageName); 3233 if (pkg == null) { 3234 throw new IllegalArgumentException("Unknown package: " + packageName); 3235 } 3236 3237 final BasePermission bp = mSettings.mPermissions.get(name); 3238 if (bp == null) { 3239 throw new IllegalArgumentException("Unknown permission: " + name); 3240 } 3241 3242 enforceDeclaredAsUsedAndRuntimePermission(pkg, bp); 3243 3244 sb = (SettingBase) pkg.mExtras; 3245 if (sb == null) { 3246 throw new IllegalArgumentException("Unknown package: " + packageName); 3247 } 3248 3249 final PermissionsState permissionsState = sb.getPermissionsState(); 3250 3251 final int flags = permissionsState.getPermissionFlags(name, userId); 3252 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3253 throw new SecurityException("Cannot revoke system fixed permission: " 3254 + name + " for package: " + packageName); 3255 } 3256 3257 if (permissionsState.revokeRuntimePermission(bp, userId) == 3258 PermissionsState.PERMISSION_OPERATION_FAILURE) { 3259 return; 3260 } 3261 3262 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 3263 3264 // Critical, after this call app should never have the permission. 3265 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 3266 } 3267 3268 killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 3269 } 3270 3271 @Override 3272 public int getPermissionFlags(String name, String packageName, int userId) { 3273 if (!sUserManager.exists(userId)) { 3274 return 0; 3275 } 3276 3277 mContext.enforceCallingOrSelfPermission( 3278 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3279 "getPermissionFlags"); 3280 3281 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3282 "getPermissionFlags"); 3283 3284 synchronized (mPackages) { 3285 final PackageParser.Package pkg = mPackages.get(packageName); 3286 if (pkg == null) { 3287 throw new IllegalArgumentException("Unknown package: " + packageName); 3288 } 3289 3290 final BasePermission bp = mSettings.mPermissions.get(name); 3291 if (bp == null) { 3292 throw new IllegalArgumentException("Unknown permission: " + name); 3293 } 3294 3295 SettingBase sb = (SettingBase) pkg.mExtras; 3296 if (sb == null) { 3297 throw new IllegalArgumentException("Unknown package: " + packageName); 3298 } 3299 3300 PermissionsState permissionsState = sb.getPermissionsState(); 3301 return permissionsState.getPermissionFlags(name, userId); 3302 } 3303 } 3304 3305 @Override 3306 public void updatePermissionFlags(String name, String packageName, int flagMask, 3307 int flagValues, int userId) { 3308 if (!sUserManager.exists(userId)) { 3309 return; 3310 } 3311 3312 mContext.enforceCallingOrSelfPermission( 3313 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, 3314 "updatePermissionFlags"); 3315 3316 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, 3317 "updatePermissionFlags"); 3318 3319 // Only the system can change policy flags. 3320 if (getCallingUid() != Process.SYSTEM_UID) { 3321 flagMask &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3322 flagValues &= ~PackageManager.FLAG_PERMISSION_POLICY_FIXED; 3323 } 3324 3325 // Only the package manager can change system flags. 3326 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3327 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 3328 3329 synchronized (mPackages) { 3330 final PackageParser.Package pkg = mPackages.get(packageName); 3331 if (pkg == null) { 3332 throw new IllegalArgumentException("Unknown package: " + packageName); 3333 } 3334 3335 final BasePermission bp = mSettings.mPermissions.get(name); 3336 if (bp == null) { 3337 throw new IllegalArgumentException("Unknown permission: " + name); 3338 } 3339 3340 SettingBase sb = (SettingBase) pkg.mExtras; 3341 if (sb == null) { 3342 throw new IllegalArgumentException("Unknown package: " + packageName); 3343 } 3344 3345 PermissionsState permissionsState = sb.getPermissionsState(); 3346 3347 // Only the package manager can change flags for system component permissions. 3348 final int flags = permissionsState.getPermissionFlags(bp.name, userId); 3349 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3350 return; 3351 } 3352 3353 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 3354 // Install and runtime permissions are stored in different places, 3355 // so figure out what permission changed and persist the change. 3356 if (permissionsState.getInstallPermissionState(name) != null) { 3357 scheduleWriteSettingsLocked(); 3358 } else if (permissionsState.getRuntimePermissionState(name, userId) != null) { 3359 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 3360 } 3361 } 3362 } 3363 } 3364 3365 @Override 3366 public boolean shouldShowRequestPermissionRationale(String permissionName, 3367 String packageName, int userId) { 3368 if (UserHandle.getCallingUserId() != userId) { 3369 mContext.enforceCallingPermission( 3370 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3371 "canShowRequestPermissionRationale for user " + userId); 3372 } 3373 3374 final int uid = getPackageUid(packageName, userId); 3375 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 3376 return false; 3377 } 3378 3379 if (checkPermission(permissionName, packageName, userId) 3380 == PackageManager.PERMISSION_GRANTED) { 3381 return false; 3382 } 3383 3384 final int flags; 3385 3386 final long identity = Binder.clearCallingIdentity(); 3387 try { 3388 flags = getPermissionFlags(permissionName, 3389 packageName, userId); 3390 } finally { 3391 Binder.restoreCallingIdentity(identity); 3392 } 3393 3394 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 3395 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 3396 | PackageManager.FLAG_PERMISSION_USER_FIXED; 3397 3398 if ((flags & fixedFlags) != 0) { 3399 return false; 3400 } 3401 3402 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 3403 } 3404 3405 @Override 3406 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3407 mContext.enforceCallingOrSelfPermission( 3408 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 3409 "addOnPermissionsChangeListener"); 3410 3411 synchronized (mPackages) { 3412 mOnPermissionChangeListeners.addListenerLocked(listener); 3413 } 3414 } 3415 3416 @Override 3417 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 3418 synchronized (mPackages) { 3419 mOnPermissionChangeListeners.removeListenerLocked(listener); 3420 } 3421 } 3422 3423 @Override 3424 public boolean isProtectedBroadcast(String actionName) { 3425 synchronized (mPackages) { 3426 return mProtectedBroadcasts.contains(actionName); 3427 } 3428 } 3429 3430 @Override 3431 public int checkSignatures(String pkg1, String pkg2) { 3432 synchronized (mPackages) { 3433 final PackageParser.Package p1 = mPackages.get(pkg1); 3434 final PackageParser.Package p2 = mPackages.get(pkg2); 3435 if (p1 == null || p1.mExtras == null 3436 || p2 == null || p2.mExtras == null) { 3437 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3438 } 3439 return compareSignatures(p1.mSignatures, p2.mSignatures); 3440 } 3441 } 3442 3443 @Override 3444 public int checkUidSignatures(int uid1, int uid2) { 3445 // Map to base uids. 3446 uid1 = UserHandle.getAppId(uid1); 3447 uid2 = UserHandle.getAppId(uid2); 3448 // reader 3449 synchronized (mPackages) { 3450 Signature[] s1; 3451 Signature[] s2; 3452 Object obj = mSettings.getUserIdLPr(uid1); 3453 if (obj != null) { 3454 if (obj instanceof SharedUserSetting) { 3455 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 3456 } else if (obj instanceof PackageSetting) { 3457 s1 = ((PackageSetting)obj).signatures.mSignatures; 3458 } else { 3459 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3460 } 3461 } else { 3462 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3463 } 3464 obj = mSettings.getUserIdLPr(uid2); 3465 if (obj != null) { 3466 if (obj instanceof SharedUserSetting) { 3467 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 3468 } else if (obj instanceof PackageSetting) { 3469 s2 = ((PackageSetting)obj).signatures.mSignatures; 3470 } else { 3471 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3472 } 3473 } else { 3474 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 3475 } 3476 return compareSignatures(s1, s2); 3477 } 3478 } 3479 3480 private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) { 3481 final long identity = Binder.clearCallingIdentity(); 3482 try { 3483 if (sb instanceof SharedUserSetting) { 3484 SharedUserSetting sus = (SharedUserSetting) sb; 3485 final int packageCount = sus.packages.size(); 3486 for (int i = 0; i < packageCount; i++) { 3487 PackageSetting susPs = sus.packages.valueAt(i); 3488 if (userId == UserHandle.USER_ALL) { 3489 killApplication(susPs.pkg.packageName, susPs.appId, reason); 3490 } else { 3491 final int uid = UserHandle.getUid(userId, susPs.appId); 3492 killUid(uid, reason); 3493 } 3494 } 3495 } else if (sb instanceof PackageSetting) { 3496 PackageSetting ps = (PackageSetting) sb; 3497 if (userId == UserHandle.USER_ALL) { 3498 killApplication(ps.pkg.packageName, ps.appId, reason); 3499 } else { 3500 final int uid = UserHandle.getUid(userId, ps.appId); 3501 killUid(uid, reason); 3502 } 3503 } 3504 } finally { 3505 Binder.restoreCallingIdentity(identity); 3506 } 3507 } 3508 3509 private static void killUid(int uid, String reason) { 3510 IActivityManager am = ActivityManagerNative.getDefault(); 3511 if (am != null) { 3512 try { 3513 am.killUid(uid, reason); 3514 } catch (RemoteException e) { 3515 /* ignore - same process */ 3516 } 3517 } 3518 } 3519 3520 /** 3521 * Compares two sets of signatures. Returns: 3522 * <br /> 3523 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 3524 * <br /> 3525 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 3526 * <br /> 3527 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 3528 * <br /> 3529 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 3530 * <br /> 3531 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 3532 */ 3533 static int compareSignatures(Signature[] s1, Signature[] s2) { 3534 if (s1 == null) { 3535 return s2 == null 3536 ? PackageManager.SIGNATURE_NEITHER_SIGNED 3537 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 3538 } 3539 3540 if (s2 == null) { 3541 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 3542 } 3543 3544 if (s1.length != s2.length) { 3545 return PackageManager.SIGNATURE_NO_MATCH; 3546 } 3547 3548 // Since both signature sets are of size 1, we can compare without HashSets. 3549 if (s1.length == 1) { 3550 return s1[0].equals(s2[0]) ? 3551 PackageManager.SIGNATURE_MATCH : 3552 PackageManager.SIGNATURE_NO_MATCH; 3553 } 3554 3555 ArraySet<Signature> set1 = new ArraySet<Signature>(); 3556 for (Signature sig : s1) { 3557 set1.add(sig); 3558 } 3559 ArraySet<Signature> set2 = new ArraySet<Signature>(); 3560 for (Signature sig : s2) { 3561 set2.add(sig); 3562 } 3563 // Make sure s2 contains all signatures in s1. 3564 if (set1.equals(set2)) { 3565 return PackageManager.SIGNATURE_MATCH; 3566 } 3567 return PackageManager.SIGNATURE_NO_MATCH; 3568 } 3569 3570 /** 3571 * If the database version for this type of package (internal storage or 3572 * external storage) is less than the version where package signatures 3573 * were updated, return true. 3574 */ 3575 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3576 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 3577 DatabaseVersion.SIGNATURE_END_ENTITY)) 3578 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 3579 DatabaseVersion.SIGNATURE_END_ENTITY)); 3580 } 3581 3582 /** 3583 * Used for backward compatibility to make sure any packages with 3584 * certificate chains get upgraded to the new style. {@code existingSigs} 3585 * will be in the old format (since they were stored on disk from before the 3586 * system upgrade) and {@code scannedSigs} will be in the newer format. 3587 */ 3588 private int compareSignaturesCompat(PackageSignatures existingSigs, 3589 PackageParser.Package scannedPkg) { 3590 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 3591 return PackageManager.SIGNATURE_NO_MATCH; 3592 } 3593 3594 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 3595 for (Signature sig : existingSigs.mSignatures) { 3596 existingSet.add(sig); 3597 } 3598 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 3599 for (Signature sig : scannedPkg.mSignatures) { 3600 try { 3601 Signature[] chainSignatures = sig.getChainSignatures(); 3602 for (Signature chainSig : chainSignatures) { 3603 scannedCompatSet.add(chainSig); 3604 } 3605 } catch (CertificateEncodingException e) { 3606 scannedCompatSet.add(sig); 3607 } 3608 } 3609 /* 3610 * Make sure the expanded scanned set contains all signatures in the 3611 * existing one. 3612 */ 3613 if (scannedCompatSet.equals(existingSet)) { 3614 // Migrate the old signatures to the new scheme. 3615 existingSigs.assignSignatures(scannedPkg.mSignatures); 3616 // The new KeySets will be re-added later in the scanning process. 3617 synchronized (mPackages) { 3618 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 3619 } 3620 return PackageManager.SIGNATURE_MATCH; 3621 } 3622 return PackageManager.SIGNATURE_NO_MATCH; 3623 } 3624 3625 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 3626 if (isExternal(scannedPkg)) { 3627 return mSettings.isExternalDatabaseVersionOlderThan( 3628 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3629 } else { 3630 return mSettings.isInternalDatabaseVersionOlderThan( 3631 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 3632 } 3633 } 3634 3635 private int compareSignaturesRecover(PackageSignatures existingSigs, 3636 PackageParser.Package scannedPkg) { 3637 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 3638 return PackageManager.SIGNATURE_NO_MATCH; 3639 } 3640 3641 String msg = null; 3642 try { 3643 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 3644 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 3645 + scannedPkg.packageName); 3646 return PackageManager.SIGNATURE_MATCH; 3647 } 3648 } catch (CertificateException e) { 3649 msg = e.getMessage(); 3650 } 3651 3652 logCriticalInfo(Log.INFO, 3653 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 3654 return PackageManager.SIGNATURE_NO_MATCH; 3655 } 3656 3657 @Override 3658 public String[] getPackagesForUid(int uid) { 3659 uid = UserHandle.getAppId(uid); 3660 // reader 3661 synchronized (mPackages) { 3662 Object obj = mSettings.getUserIdLPr(uid); 3663 if (obj instanceof SharedUserSetting) { 3664 final SharedUserSetting sus = (SharedUserSetting) obj; 3665 final int N = sus.packages.size(); 3666 final String[] res = new String[N]; 3667 final Iterator<PackageSetting> it = sus.packages.iterator(); 3668 int i = 0; 3669 while (it.hasNext()) { 3670 res[i++] = it.next().name; 3671 } 3672 return res; 3673 } else if (obj instanceof PackageSetting) { 3674 final PackageSetting ps = (PackageSetting) obj; 3675 return new String[] { ps.name }; 3676 } 3677 } 3678 return null; 3679 } 3680 3681 @Override 3682 public String getNameForUid(int uid) { 3683 // reader 3684 synchronized (mPackages) { 3685 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3686 if (obj instanceof SharedUserSetting) { 3687 final SharedUserSetting sus = (SharedUserSetting) obj; 3688 return sus.name + ":" + sus.userId; 3689 } else if (obj instanceof PackageSetting) { 3690 final PackageSetting ps = (PackageSetting) obj; 3691 return ps.name; 3692 } 3693 } 3694 return null; 3695 } 3696 3697 @Override 3698 public int getUidForSharedUser(String sharedUserName) { 3699 if(sharedUserName == null) { 3700 return -1; 3701 } 3702 // reader 3703 synchronized (mPackages) { 3704 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 3705 if (suid == null) { 3706 return -1; 3707 } 3708 return suid.userId; 3709 } 3710 } 3711 3712 @Override 3713 public int getFlagsForUid(int uid) { 3714 synchronized (mPackages) { 3715 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3716 if (obj instanceof SharedUserSetting) { 3717 final SharedUserSetting sus = (SharedUserSetting) obj; 3718 return sus.pkgFlags; 3719 } else if (obj instanceof PackageSetting) { 3720 final PackageSetting ps = (PackageSetting) obj; 3721 return ps.pkgFlags; 3722 } 3723 } 3724 return 0; 3725 } 3726 3727 @Override 3728 public int getPrivateFlagsForUid(int uid) { 3729 synchronized (mPackages) { 3730 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3731 if (obj instanceof SharedUserSetting) { 3732 final SharedUserSetting sus = (SharedUserSetting) obj; 3733 return sus.pkgPrivateFlags; 3734 } else if (obj instanceof PackageSetting) { 3735 final PackageSetting ps = (PackageSetting) obj; 3736 return ps.pkgPrivateFlags; 3737 } 3738 } 3739 return 0; 3740 } 3741 3742 @Override 3743 public boolean isUidPrivileged(int uid) { 3744 uid = UserHandle.getAppId(uid); 3745 // reader 3746 synchronized (mPackages) { 3747 Object obj = mSettings.getUserIdLPr(uid); 3748 if (obj instanceof SharedUserSetting) { 3749 final SharedUserSetting sus = (SharedUserSetting) obj; 3750 final Iterator<PackageSetting> it = sus.packages.iterator(); 3751 while (it.hasNext()) { 3752 if (it.next().isPrivileged()) { 3753 return true; 3754 } 3755 } 3756 } else if (obj instanceof PackageSetting) { 3757 final PackageSetting ps = (PackageSetting) obj; 3758 return ps.isPrivileged(); 3759 } 3760 } 3761 return false; 3762 } 3763 3764 @Override 3765 public String[] getAppOpPermissionPackages(String permissionName) { 3766 synchronized (mPackages) { 3767 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3768 if (pkgs == null) { 3769 return null; 3770 } 3771 return pkgs.toArray(new String[pkgs.size()]); 3772 } 3773 } 3774 3775 @Override 3776 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3777 int flags, int userId) { 3778 if (!sUserManager.exists(userId)) return null; 3779 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3780 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3781 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3782 } 3783 3784 @Override 3785 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3786 IntentFilter filter, int match, ComponentName activity) { 3787 final int userId = UserHandle.getCallingUserId(); 3788 if (DEBUG_PREFERRED) { 3789 Log.v(TAG, "setLastChosenActivity intent=" + intent 3790 + " resolvedType=" + resolvedType 3791 + " flags=" + flags 3792 + " filter=" + filter 3793 + " match=" + match 3794 + " activity=" + activity); 3795 filter.dump(new PrintStreamPrinter(System.out), " "); 3796 } 3797 intent.setComponent(null); 3798 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3799 // Find any earlier preferred or last chosen entries and nuke them 3800 findPreferredActivity(intent, resolvedType, 3801 flags, query, 0, false, true, false, userId); 3802 // Add the new activity as the last chosen for this filter 3803 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3804 "Setting last chosen"); 3805 } 3806 3807 @Override 3808 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3809 final int userId = UserHandle.getCallingUserId(); 3810 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3811 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3812 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3813 false, false, false, userId); 3814 } 3815 3816 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3817 int flags, List<ResolveInfo> query, int userId) { 3818 if (query != null) { 3819 final int N = query.size(); 3820 if (N == 1) { 3821 return query.get(0); 3822 } else if (N > 1) { 3823 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3824 // If there is more than one activity with the same priority, 3825 // then let the user decide between them. 3826 ResolveInfo r0 = query.get(0); 3827 ResolveInfo r1 = query.get(1); 3828 if (DEBUG_INTENT_MATCHING || debug) { 3829 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3830 + r1.activityInfo.name + "=" + r1.priority); 3831 } 3832 // If the first activity has a higher priority, or a different 3833 // default, then it is always desireable to pick it. 3834 if (r0.priority != r1.priority 3835 || r0.preferredOrder != r1.preferredOrder 3836 || r0.isDefault != r1.isDefault) { 3837 return query.get(0); 3838 } 3839 // If we have saved a preference for a preferred activity for 3840 // this Intent, use that. 3841 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3842 flags, query, r0.priority, true, false, debug, userId); 3843 if (ri != null) { 3844 return ri; 3845 } 3846 if (userId != 0) { 3847 ri = new ResolveInfo(mResolveInfo); 3848 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3849 ri.activityInfo.applicationInfo = new ApplicationInfo( 3850 ri.activityInfo.applicationInfo); 3851 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3852 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3853 return ri; 3854 } 3855 return mResolveInfo; 3856 } 3857 } 3858 return null; 3859 } 3860 3861 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3862 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3863 final int N = query.size(); 3864 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3865 .get(userId); 3866 // Get the list of persistent preferred activities that handle the intent 3867 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3868 List<PersistentPreferredActivity> pprefs = ppir != null 3869 ? ppir.queryIntent(intent, resolvedType, 3870 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3871 : null; 3872 if (pprefs != null && pprefs.size() > 0) { 3873 final int M = pprefs.size(); 3874 for (int i=0; i<M; i++) { 3875 final PersistentPreferredActivity ppa = pprefs.get(i); 3876 if (DEBUG_PREFERRED || debug) { 3877 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3878 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3879 + "\n component=" + ppa.mComponent); 3880 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3881 } 3882 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3883 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3884 if (DEBUG_PREFERRED || debug) { 3885 Slog.v(TAG, "Found persistent preferred activity:"); 3886 if (ai != null) { 3887 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3888 } else { 3889 Slog.v(TAG, " null"); 3890 } 3891 } 3892 if (ai == null) { 3893 // This previously registered persistent preferred activity 3894 // component is no longer known. Ignore it and do NOT remove it. 3895 continue; 3896 } 3897 for (int j=0; j<N; j++) { 3898 final ResolveInfo ri = query.get(j); 3899 if (!ri.activityInfo.applicationInfo.packageName 3900 .equals(ai.applicationInfo.packageName)) { 3901 continue; 3902 } 3903 if (!ri.activityInfo.name.equals(ai.name)) { 3904 continue; 3905 } 3906 // Found a persistent preference that can handle the intent. 3907 if (DEBUG_PREFERRED || debug) { 3908 Slog.v(TAG, "Returning persistent preferred activity: " + 3909 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3910 } 3911 return ri; 3912 } 3913 } 3914 } 3915 return null; 3916 } 3917 3918 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3919 List<ResolveInfo> query, int priority, boolean always, 3920 boolean removeMatches, boolean debug, int userId) { 3921 if (!sUserManager.exists(userId)) return null; 3922 // writer 3923 synchronized (mPackages) { 3924 if (intent.getSelector() != null) { 3925 intent = intent.getSelector(); 3926 } 3927 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3928 3929 // Try to find a matching persistent preferred activity. 3930 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3931 debug, userId); 3932 3933 // If a persistent preferred activity matched, use it. 3934 if (pri != null) { 3935 return pri; 3936 } 3937 3938 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3939 // Get the list of preferred activities that handle the intent 3940 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3941 List<PreferredActivity> prefs = pir != null 3942 ? pir.queryIntent(intent, resolvedType, 3943 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3944 : null; 3945 if (prefs != null && prefs.size() > 0) { 3946 boolean changed = false; 3947 try { 3948 // First figure out how good the original match set is. 3949 // We will only allow preferred activities that came 3950 // from the same match quality. 3951 int match = 0; 3952 3953 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3954 3955 final int N = query.size(); 3956 for (int j=0; j<N; j++) { 3957 final ResolveInfo ri = query.get(j); 3958 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3959 + ": 0x" + Integer.toHexString(match)); 3960 if (ri.match > match) { 3961 match = ri.match; 3962 } 3963 } 3964 3965 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3966 + Integer.toHexString(match)); 3967 3968 match &= IntentFilter.MATCH_CATEGORY_MASK; 3969 final int M = prefs.size(); 3970 for (int i=0; i<M; i++) { 3971 final PreferredActivity pa = prefs.get(i); 3972 if (DEBUG_PREFERRED || debug) { 3973 Slog.v(TAG, "Checking PreferredActivity ds=" 3974 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3975 + "\n component=" + pa.mPref.mComponent); 3976 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3977 } 3978 if (pa.mPref.mMatch != match) { 3979 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3980 + Integer.toHexString(pa.mPref.mMatch)); 3981 continue; 3982 } 3983 // If it's not an "always" type preferred activity and that's what we're 3984 // looking for, skip it. 3985 if (always && !pa.mPref.mAlways) { 3986 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3987 continue; 3988 } 3989 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3990 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3991 if (DEBUG_PREFERRED || debug) { 3992 Slog.v(TAG, "Found preferred activity:"); 3993 if (ai != null) { 3994 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3995 } else { 3996 Slog.v(TAG, " null"); 3997 } 3998 } 3999 if (ai == null) { 4000 // This previously registered preferred activity 4001 // component is no longer known. Most likely an update 4002 // to the app was installed and in the new version this 4003 // component no longer exists. Clean it up by removing 4004 // it from the preferred activities list, and skip it. 4005 Slog.w(TAG, "Removing dangling preferred activity: " 4006 + pa.mPref.mComponent); 4007 pir.removeFilter(pa); 4008 changed = true; 4009 continue; 4010 } 4011 for (int j=0; j<N; j++) { 4012 final ResolveInfo ri = query.get(j); 4013 if (!ri.activityInfo.applicationInfo.packageName 4014 .equals(ai.applicationInfo.packageName)) { 4015 continue; 4016 } 4017 if (!ri.activityInfo.name.equals(ai.name)) { 4018 continue; 4019 } 4020 4021 if (removeMatches) { 4022 pir.removeFilter(pa); 4023 changed = true; 4024 if (DEBUG_PREFERRED) { 4025 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 4026 } 4027 break; 4028 } 4029 4030 // Okay we found a previously set preferred or last chosen app. 4031 // If the result set is different from when this 4032 // was created, we need to clear it and re-ask the 4033 // user their preference, if we're looking for an "always" type entry. 4034 if (always && !pa.mPref.sameSet(query)) { 4035 Slog.i(TAG, "Result set changed, dropping preferred activity for " 4036 + intent + " type " + resolvedType); 4037 if (DEBUG_PREFERRED) { 4038 Slog.v(TAG, "Removing preferred activity since set changed " 4039 + pa.mPref.mComponent); 4040 } 4041 pir.removeFilter(pa); 4042 // Re-add the filter as a "last chosen" entry (!always) 4043 PreferredActivity lastChosen = new PreferredActivity( 4044 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 4045 pir.addFilter(lastChosen); 4046 changed = true; 4047 return null; 4048 } 4049 4050 // Yay! Either the set matched or we're looking for the last chosen 4051 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 4052 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4053 return ri; 4054 } 4055 } 4056 } finally { 4057 if (changed) { 4058 if (DEBUG_PREFERRED) { 4059 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 4060 } 4061 scheduleWritePackageRestrictionsLocked(userId); 4062 } 4063 } 4064 } 4065 } 4066 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 4067 return null; 4068 } 4069 4070 /* 4071 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 4072 */ 4073 @Override 4074 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 4075 int targetUserId) { 4076 mContext.enforceCallingOrSelfPermission( 4077 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4078 List<CrossProfileIntentFilter> matches = 4079 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 4080 if (matches != null) { 4081 int size = matches.size(); 4082 for (int i = 0; i < size; i++) { 4083 if (matches.get(i).getTargetUserId() == targetUserId) return true; 4084 } 4085 } 4086 return false; 4087 } 4088 4089 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 4090 String resolvedType, int userId) { 4091 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 4092 if (resolver != null) { 4093 return resolver.queryIntent(intent, resolvedType, false, userId); 4094 } 4095 return null; 4096 } 4097 4098 @Override 4099 public List<ResolveInfo> queryIntentActivities(Intent intent, 4100 String resolvedType, int flags, int userId) { 4101 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4102 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 4103 ComponentName comp = intent.getComponent(); 4104 if (comp == null) { 4105 if (intent.getSelector() != null) { 4106 intent = intent.getSelector(); 4107 comp = intent.getComponent(); 4108 } 4109 } 4110 4111 if (comp != null) { 4112 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4113 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 4114 if (ai != null) { 4115 final ResolveInfo ri = new ResolveInfo(); 4116 ri.activityInfo = ai; 4117 list.add(ri); 4118 } 4119 return list; 4120 } 4121 4122 // reader 4123 synchronized (mPackages) { 4124 final String pkgName = intent.getPackage(); 4125 if (pkgName == null) { 4126 List<CrossProfileIntentFilter> matchingFilters = 4127 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 4128 // Check for results that need to skip the current profile. 4129 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 4130 resolvedType, flags, userId); 4131 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4132 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 4133 result.add(resolveInfo); 4134 return filterIfNotPrimaryUser(result, userId); 4135 } 4136 4137 // Check for results in the current profile. 4138 List<ResolveInfo> result = mActivities.queryIntent( 4139 intent, resolvedType, flags, userId); 4140 4141 // Check for cross profile results. 4142 resolveInfo = queryCrossProfileIntents( 4143 matchingFilters, intent, resolvedType, flags, userId); 4144 if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) { 4145 result.add(resolveInfo); 4146 Collections.sort(result, mResolvePrioritySorter); 4147 } 4148 result = filterIfNotPrimaryUser(result, userId); 4149 if (result.size() > 1 && hasWebURI(intent)) { 4150 return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result); 4151 } 4152 return result; 4153 } 4154 final PackageParser.Package pkg = mPackages.get(pkgName); 4155 if (pkg != null) { 4156 return filterIfNotPrimaryUser( 4157 mActivities.queryIntentForPackage( 4158 intent, resolvedType, flags, pkg.activities, userId), 4159 userId); 4160 } 4161 return new ArrayList<ResolveInfo>(); 4162 } 4163 } 4164 4165 private boolean isUserEnabled(int userId) { 4166 long callingId = Binder.clearCallingIdentity(); 4167 try { 4168 UserInfo userInfo = sUserManager.getUserInfo(userId); 4169 return userInfo != null && userInfo.isEnabled(); 4170 } finally { 4171 Binder.restoreCallingIdentity(callingId); 4172 } 4173 } 4174 4175 /** 4176 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 4177 * 4178 * @return filtered list 4179 */ 4180 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 4181 if (userId == UserHandle.USER_OWNER) { 4182 return resolveInfos; 4183 } 4184 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 4185 ResolveInfo info = resolveInfos.get(i); 4186 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 4187 resolveInfos.remove(i); 4188 } 4189 } 4190 return resolveInfos; 4191 } 4192 4193 private static boolean hasWebURI(Intent intent) { 4194 if (intent.getData() == null) { 4195 return false; 4196 } 4197 final String scheme = intent.getScheme(); 4198 if (TextUtils.isEmpty(scheme)) { 4199 return false; 4200 } 4201 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 4202 } 4203 4204 private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr( 4205 int flags, List<ResolveInfo> candidates) { 4206 if (DEBUG_PREFERRED) { 4207 Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " + 4208 candidates.size()); 4209 } 4210 4211 final int userId = UserHandle.getCallingUserId(); 4212 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 4213 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 4214 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 4215 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 4216 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 4217 4218 synchronized (mPackages) { 4219 final int count = candidates.size(); 4220 // First, try to use the domain prefered App. Partition the candidates into four lists: 4221 // one for the final results, one for the "do not use ever", one for "undefined status" 4222 // and finally one for "Browser App type". 4223 for (int n=0; n<count; n++) { 4224 ResolveInfo info = candidates.get(n); 4225 String packageName = info.activityInfo.packageName; 4226 PackageSetting ps = mSettings.mPackages.get(packageName); 4227 if (ps != null) { 4228 // Add to the special match all list (Browser use case) 4229 if (info.handleAllWebDataURI) { 4230 matchAllList.add(info); 4231 continue; 4232 } 4233 // Try to get the status from User settings first 4234 int status = getDomainVerificationStatusLPr(ps, userId); 4235 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 4236 alwaysList.add(info); 4237 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 4238 neverList.add(info); 4239 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 4240 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 4241 undefinedList.add(info); 4242 } 4243 } 4244 } 4245 // First try to add the "always" if there is any 4246 if (alwaysList.size() > 0) { 4247 result.addAll(alwaysList); 4248 } else { 4249 // Add all undefined Apps as we want them to appear in the Disambiguation dialog. 4250 result.addAll(undefinedList); 4251 // Also add Browsers (all of them or only the default one) 4252 if ((flags & MATCH_ALL) != 0) { 4253 result.addAll(matchAllList); 4254 } else { 4255 // Try to add the Default Browser if we can 4256 final String defaultBrowserPackageName = getDefaultBrowserPackageName( 4257 UserHandle.myUserId()); 4258 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 4259 boolean defaultBrowserFound = false; 4260 final int browserCount = matchAllList.size(); 4261 for (int n=0; n<browserCount; n++) { 4262 ResolveInfo browser = matchAllList.get(n); 4263 if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) { 4264 result.add(browser); 4265 defaultBrowserFound = true; 4266 break; 4267 } 4268 } 4269 if (!defaultBrowserFound) { 4270 result.addAll(matchAllList); 4271 } 4272 } else { 4273 result.addAll(matchAllList); 4274 } 4275 } 4276 4277 // If there is nothing selected, add all candidates and remove the ones that the User 4278 // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 4279 if (result.size() == 0) { 4280 result.addAll(candidates); 4281 result.removeAll(neverList); 4282 } 4283 } 4284 } 4285 if (DEBUG_PREFERRED) { 4286 Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " + 4287 result.size()); 4288 } 4289 return result; 4290 } 4291 4292 private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 4293 int status = ps.getDomainVerificationStatusForUser(userId); 4294 // if none available, get the master status 4295 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 4296 if (ps.getIntentFilterVerificationInfo() != null) { 4297 status = ps.getIntentFilterVerificationInfo().getStatus(); 4298 } 4299 } 4300 return status; 4301 } 4302 4303 private ResolveInfo querySkipCurrentProfileIntents( 4304 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4305 int flags, int sourceUserId) { 4306 if (matchingFilters != null) { 4307 int size = matchingFilters.size(); 4308 for (int i = 0; i < size; i ++) { 4309 CrossProfileIntentFilter filter = matchingFilters.get(i); 4310 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 4311 // Checking if there are activities in the target user that can handle the 4312 // intent. 4313 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4314 flags, sourceUserId); 4315 if (resolveInfo != null) { 4316 return resolveInfo; 4317 } 4318 } 4319 } 4320 } 4321 return null; 4322 } 4323 4324 // Return matching ResolveInfo if any for skip current profile intent filters. 4325 private ResolveInfo queryCrossProfileIntents( 4326 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 4327 int flags, int sourceUserId) { 4328 if (matchingFilters != null) { 4329 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 4330 // match the same intent. For performance reasons, it is better not to 4331 // run queryIntent twice for the same userId 4332 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 4333 int size = matchingFilters.size(); 4334 for (int i = 0; i < size; i++) { 4335 CrossProfileIntentFilter filter = matchingFilters.get(i); 4336 int targetUserId = filter.getTargetUserId(); 4337 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 4338 && !alreadyTriedUserIds.get(targetUserId)) { 4339 // Checking if there are activities in the target user that can handle the 4340 // intent. 4341 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 4342 flags, sourceUserId); 4343 if (resolveInfo != null) return resolveInfo; 4344 alreadyTriedUserIds.put(targetUserId, true); 4345 } 4346 } 4347 } 4348 return null; 4349 } 4350 4351 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 4352 String resolvedType, int flags, int sourceUserId) { 4353 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 4354 resolvedType, flags, filter.getTargetUserId()); 4355 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 4356 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 4357 } 4358 return null; 4359 } 4360 4361 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 4362 int sourceUserId, int targetUserId) { 4363 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 4364 String className; 4365 if (targetUserId == UserHandle.USER_OWNER) { 4366 className = FORWARD_INTENT_TO_USER_OWNER; 4367 } else { 4368 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 4369 } 4370 ComponentName forwardingActivityComponentName = new ComponentName( 4371 mAndroidApplication.packageName, className); 4372 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 4373 sourceUserId); 4374 if (targetUserId == UserHandle.USER_OWNER) { 4375 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 4376 forwardingResolveInfo.noResourceId = true; 4377 } 4378 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 4379 forwardingResolveInfo.priority = 0; 4380 forwardingResolveInfo.preferredOrder = 0; 4381 forwardingResolveInfo.match = 0; 4382 forwardingResolveInfo.isDefault = true; 4383 forwardingResolveInfo.filter = filter; 4384 forwardingResolveInfo.targetUserId = targetUserId; 4385 return forwardingResolveInfo; 4386 } 4387 4388 @Override 4389 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 4390 Intent[] specifics, String[] specificTypes, Intent intent, 4391 String resolvedType, int flags, int userId) { 4392 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4393 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 4394 false, "query intent activity options"); 4395 final String resultsAction = intent.getAction(); 4396 4397 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 4398 | PackageManager.GET_RESOLVED_FILTER, userId); 4399 4400 if (DEBUG_INTENT_MATCHING) { 4401 Log.v(TAG, "Query " + intent + ": " + results); 4402 } 4403 4404 int specificsPos = 0; 4405 int N; 4406 4407 // todo: note that the algorithm used here is O(N^2). This 4408 // isn't a problem in our current environment, but if we start running 4409 // into situations where we have more than 5 or 10 matches then this 4410 // should probably be changed to something smarter... 4411 4412 // First we go through and resolve each of the specific items 4413 // that were supplied, taking care of removing any corresponding 4414 // duplicate items in the generic resolve list. 4415 if (specifics != null) { 4416 for (int i=0; i<specifics.length; i++) { 4417 final Intent sintent = specifics[i]; 4418 if (sintent == null) { 4419 continue; 4420 } 4421 4422 if (DEBUG_INTENT_MATCHING) { 4423 Log.v(TAG, "Specific #" + i + ": " + sintent); 4424 } 4425 4426 String action = sintent.getAction(); 4427 if (resultsAction != null && resultsAction.equals(action)) { 4428 // If this action was explicitly requested, then don't 4429 // remove things that have it. 4430 action = null; 4431 } 4432 4433 ResolveInfo ri = null; 4434 ActivityInfo ai = null; 4435 4436 ComponentName comp = sintent.getComponent(); 4437 if (comp == null) { 4438 ri = resolveIntent( 4439 sintent, 4440 specificTypes != null ? specificTypes[i] : null, 4441 flags, userId); 4442 if (ri == null) { 4443 continue; 4444 } 4445 if (ri == mResolveInfo) { 4446 // ACK! Must do something better with this. 4447 } 4448 ai = ri.activityInfo; 4449 comp = new ComponentName(ai.applicationInfo.packageName, 4450 ai.name); 4451 } else { 4452 ai = getActivityInfo(comp, flags, userId); 4453 if (ai == null) { 4454 continue; 4455 } 4456 } 4457 4458 // Look for any generic query activities that are duplicates 4459 // of this specific one, and remove them from the results. 4460 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 4461 N = results.size(); 4462 int j; 4463 for (j=specificsPos; j<N; j++) { 4464 ResolveInfo sri = results.get(j); 4465 if ((sri.activityInfo.name.equals(comp.getClassName()) 4466 && sri.activityInfo.applicationInfo.packageName.equals( 4467 comp.getPackageName())) 4468 || (action != null && sri.filter.matchAction(action))) { 4469 results.remove(j); 4470 if (DEBUG_INTENT_MATCHING) Log.v( 4471 TAG, "Removing duplicate item from " + j 4472 + " due to specific " + specificsPos); 4473 if (ri == null) { 4474 ri = sri; 4475 } 4476 j--; 4477 N--; 4478 } 4479 } 4480 4481 // Add this specific item to its proper place. 4482 if (ri == null) { 4483 ri = new ResolveInfo(); 4484 ri.activityInfo = ai; 4485 } 4486 results.add(specificsPos, ri); 4487 ri.specificIndex = i; 4488 specificsPos++; 4489 } 4490 } 4491 4492 // Now we go through the remaining generic results and remove any 4493 // duplicate actions that are found here. 4494 N = results.size(); 4495 for (int i=specificsPos; i<N-1; i++) { 4496 final ResolveInfo rii = results.get(i); 4497 if (rii.filter == null) { 4498 continue; 4499 } 4500 4501 // Iterate over all of the actions of this result's intent 4502 // filter... typically this should be just one. 4503 final Iterator<String> it = rii.filter.actionsIterator(); 4504 if (it == null) { 4505 continue; 4506 } 4507 while (it.hasNext()) { 4508 final String action = it.next(); 4509 if (resultsAction != null && resultsAction.equals(action)) { 4510 // If this action was explicitly requested, then don't 4511 // remove things that have it. 4512 continue; 4513 } 4514 for (int j=i+1; j<N; j++) { 4515 final ResolveInfo rij = results.get(j); 4516 if (rij.filter != null && rij.filter.hasAction(action)) { 4517 results.remove(j); 4518 if (DEBUG_INTENT_MATCHING) Log.v( 4519 TAG, "Removing duplicate item from " + j 4520 + " due to action " + action + " at " + i); 4521 j--; 4522 N--; 4523 } 4524 } 4525 } 4526 4527 // If the caller didn't request filter information, drop it now 4528 // so we don't have to marshall/unmarshall it. 4529 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4530 rii.filter = null; 4531 } 4532 } 4533 4534 // Filter out the caller activity if so requested. 4535 if (caller != null) { 4536 N = results.size(); 4537 for (int i=0; i<N; i++) { 4538 ActivityInfo ainfo = results.get(i).activityInfo; 4539 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 4540 && caller.getClassName().equals(ainfo.name)) { 4541 results.remove(i); 4542 break; 4543 } 4544 } 4545 } 4546 4547 // If the caller didn't request filter information, 4548 // drop them now so we don't have to 4549 // marshall/unmarshall it. 4550 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 4551 N = results.size(); 4552 for (int i=0; i<N; i++) { 4553 results.get(i).filter = null; 4554 } 4555 } 4556 4557 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 4558 return results; 4559 } 4560 4561 @Override 4562 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 4563 int userId) { 4564 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4565 ComponentName comp = intent.getComponent(); 4566 if (comp == null) { 4567 if (intent.getSelector() != null) { 4568 intent = intent.getSelector(); 4569 comp = intent.getComponent(); 4570 } 4571 } 4572 if (comp != null) { 4573 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4574 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 4575 if (ai != null) { 4576 ResolveInfo ri = new ResolveInfo(); 4577 ri.activityInfo = ai; 4578 list.add(ri); 4579 } 4580 return list; 4581 } 4582 4583 // reader 4584 synchronized (mPackages) { 4585 String pkgName = intent.getPackage(); 4586 if (pkgName == null) { 4587 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 4588 } 4589 final PackageParser.Package pkg = mPackages.get(pkgName); 4590 if (pkg != null) { 4591 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 4592 userId); 4593 } 4594 return null; 4595 } 4596 } 4597 4598 @Override 4599 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 4600 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 4601 if (!sUserManager.exists(userId)) return null; 4602 if (query != null) { 4603 if (query.size() >= 1) { 4604 // If there is more than one service with the same priority, 4605 // just arbitrarily pick the first one. 4606 return query.get(0); 4607 } 4608 } 4609 return null; 4610 } 4611 4612 @Override 4613 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 4614 int userId) { 4615 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4616 ComponentName comp = intent.getComponent(); 4617 if (comp == null) { 4618 if (intent.getSelector() != null) { 4619 intent = intent.getSelector(); 4620 comp = intent.getComponent(); 4621 } 4622 } 4623 if (comp != null) { 4624 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4625 final ServiceInfo si = getServiceInfo(comp, flags, userId); 4626 if (si != null) { 4627 final ResolveInfo ri = new ResolveInfo(); 4628 ri.serviceInfo = si; 4629 list.add(ri); 4630 } 4631 return list; 4632 } 4633 4634 // reader 4635 synchronized (mPackages) { 4636 String pkgName = intent.getPackage(); 4637 if (pkgName == null) { 4638 return mServices.queryIntent(intent, resolvedType, flags, userId); 4639 } 4640 final PackageParser.Package pkg = mPackages.get(pkgName); 4641 if (pkg != null) { 4642 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 4643 userId); 4644 } 4645 return null; 4646 } 4647 } 4648 4649 @Override 4650 public List<ResolveInfo> queryIntentContentProviders( 4651 Intent intent, String resolvedType, int flags, int userId) { 4652 if (!sUserManager.exists(userId)) return Collections.emptyList(); 4653 ComponentName comp = intent.getComponent(); 4654 if (comp == null) { 4655 if (intent.getSelector() != null) { 4656 intent = intent.getSelector(); 4657 comp = intent.getComponent(); 4658 } 4659 } 4660 if (comp != null) { 4661 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 4662 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 4663 if (pi != null) { 4664 final ResolveInfo ri = new ResolveInfo(); 4665 ri.providerInfo = pi; 4666 list.add(ri); 4667 } 4668 return list; 4669 } 4670 4671 // reader 4672 synchronized (mPackages) { 4673 String pkgName = intent.getPackage(); 4674 if (pkgName == null) { 4675 return mProviders.queryIntent(intent, resolvedType, flags, userId); 4676 } 4677 final PackageParser.Package pkg = mPackages.get(pkgName); 4678 if (pkg != null) { 4679 return mProviders.queryIntentForPackage( 4680 intent, resolvedType, flags, pkg.providers, userId); 4681 } 4682 return null; 4683 } 4684 } 4685 4686 @Override 4687 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 4688 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4689 4690 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 4691 4692 // writer 4693 synchronized (mPackages) { 4694 ArrayList<PackageInfo> list; 4695 if (listUninstalled) { 4696 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 4697 for (PackageSetting ps : mSettings.mPackages.values()) { 4698 PackageInfo pi; 4699 if (ps.pkg != null) { 4700 pi = generatePackageInfo(ps.pkg, flags, userId); 4701 } else { 4702 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4703 } 4704 if (pi != null) { 4705 list.add(pi); 4706 } 4707 } 4708 } else { 4709 list = new ArrayList<PackageInfo>(mPackages.size()); 4710 for (PackageParser.Package p : mPackages.values()) { 4711 PackageInfo pi = generatePackageInfo(p, flags, userId); 4712 if (pi != null) { 4713 list.add(pi); 4714 } 4715 } 4716 } 4717 4718 return new ParceledListSlice<PackageInfo>(list); 4719 } 4720 } 4721 4722 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 4723 String[] permissions, boolean[] tmp, int flags, int userId) { 4724 int numMatch = 0; 4725 final PermissionsState permissionsState = ps.getPermissionsState(); 4726 for (int i=0; i<permissions.length; i++) { 4727 final String permission = permissions[i]; 4728 if (permissionsState.hasPermission(permission, userId)) { 4729 tmp[i] = true; 4730 numMatch++; 4731 } else { 4732 tmp[i] = false; 4733 } 4734 } 4735 if (numMatch == 0) { 4736 return; 4737 } 4738 PackageInfo pi; 4739 if (ps.pkg != null) { 4740 pi = generatePackageInfo(ps.pkg, flags, userId); 4741 } else { 4742 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 4743 } 4744 // The above might return null in cases of uninstalled apps or install-state 4745 // skew across users/profiles. 4746 if (pi != null) { 4747 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 4748 if (numMatch == permissions.length) { 4749 pi.requestedPermissions = permissions; 4750 } else { 4751 pi.requestedPermissions = new String[numMatch]; 4752 numMatch = 0; 4753 for (int i=0; i<permissions.length; i++) { 4754 if (tmp[i]) { 4755 pi.requestedPermissions[numMatch] = permissions[i]; 4756 numMatch++; 4757 } 4758 } 4759 } 4760 } 4761 list.add(pi); 4762 } 4763 } 4764 4765 @Override 4766 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4767 String[] permissions, int flags, int userId) { 4768 if (!sUserManager.exists(userId)) return null; 4769 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4770 4771 // writer 4772 synchronized (mPackages) { 4773 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 4774 boolean[] tmpBools = new boolean[permissions.length]; 4775 if (listUninstalled) { 4776 for (PackageSetting ps : mSettings.mPackages.values()) { 4777 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4778 } 4779 } else { 4780 for (PackageParser.Package pkg : mPackages.values()) { 4781 PackageSetting ps = (PackageSetting)pkg.mExtras; 4782 if (ps != null) { 4783 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 4784 userId); 4785 } 4786 } 4787 } 4788 4789 return new ParceledListSlice<PackageInfo>(list); 4790 } 4791 } 4792 4793 @Override 4794 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 4795 if (!sUserManager.exists(userId)) return null; 4796 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 4797 4798 // writer 4799 synchronized (mPackages) { 4800 ArrayList<ApplicationInfo> list; 4801 if (listUninstalled) { 4802 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 4803 for (PackageSetting ps : mSettings.mPackages.values()) { 4804 ApplicationInfo ai; 4805 if (ps.pkg != null) { 4806 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4807 ps.readUserState(userId), userId); 4808 } else { 4809 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 4810 } 4811 if (ai != null) { 4812 list.add(ai); 4813 } 4814 } 4815 } else { 4816 list = new ArrayList<ApplicationInfo>(mPackages.size()); 4817 for (PackageParser.Package p : mPackages.values()) { 4818 if (p.mExtras != null) { 4819 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4820 ((PackageSetting)p.mExtras).readUserState(userId), userId); 4821 if (ai != null) { 4822 list.add(ai); 4823 } 4824 } 4825 } 4826 } 4827 4828 return new ParceledListSlice<ApplicationInfo>(list); 4829 } 4830 } 4831 4832 public List<ApplicationInfo> getPersistentApplications(int flags) { 4833 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 4834 4835 // reader 4836 synchronized (mPackages) { 4837 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 4838 final int userId = UserHandle.getCallingUserId(); 4839 while (i.hasNext()) { 4840 final PackageParser.Package p = i.next(); 4841 if (p.applicationInfo != null 4842 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 4843 && (!mSafeMode || isSystemApp(p))) { 4844 PackageSetting ps = mSettings.mPackages.get(p.packageName); 4845 if (ps != null) { 4846 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 4847 ps.readUserState(userId), userId); 4848 if (ai != null) { 4849 finalList.add(ai); 4850 } 4851 } 4852 } 4853 } 4854 } 4855 4856 return finalList; 4857 } 4858 4859 @Override 4860 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4861 if (!sUserManager.exists(userId)) return null; 4862 // reader 4863 synchronized (mPackages) { 4864 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4865 PackageSetting ps = provider != null 4866 ? mSettings.mPackages.get(provider.owner.packageName) 4867 : null; 4868 return ps != null 4869 && mSettings.isEnabledLPr(provider.info, flags, userId) 4870 && (!mSafeMode || (provider.info.applicationInfo.flags 4871 &ApplicationInfo.FLAG_SYSTEM) != 0) 4872 ? PackageParser.generateProviderInfo(provider, flags, 4873 ps.readUserState(userId), userId) 4874 : null; 4875 } 4876 } 4877 4878 /** 4879 * @deprecated 4880 */ 4881 @Deprecated 4882 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4883 // reader 4884 synchronized (mPackages) { 4885 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4886 .entrySet().iterator(); 4887 final int userId = UserHandle.getCallingUserId(); 4888 while (i.hasNext()) { 4889 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4890 PackageParser.Provider p = entry.getValue(); 4891 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4892 4893 if (ps != null && p.syncable 4894 && (!mSafeMode || (p.info.applicationInfo.flags 4895 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4896 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4897 ps.readUserState(userId), userId); 4898 if (info != null) { 4899 outNames.add(entry.getKey()); 4900 outInfo.add(info); 4901 } 4902 } 4903 } 4904 } 4905 } 4906 4907 @Override 4908 public List<ProviderInfo> queryContentProviders(String processName, 4909 int uid, int flags) { 4910 ArrayList<ProviderInfo> finalList = null; 4911 // reader 4912 synchronized (mPackages) { 4913 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4914 final int userId = processName != null ? 4915 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4916 while (i.hasNext()) { 4917 final PackageParser.Provider p = i.next(); 4918 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4919 if (ps != null && p.info.authority != null 4920 && (processName == null 4921 || (p.info.processName.equals(processName) 4922 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4923 && mSettings.isEnabledLPr(p.info, flags, userId) 4924 && (!mSafeMode 4925 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4926 if (finalList == null) { 4927 finalList = new ArrayList<ProviderInfo>(3); 4928 } 4929 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4930 ps.readUserState(userId), userId); 4931 if (info != null) { 4932 finalList.add(info); 4933 } 4934 } 4935 } 4936 } 4937 4938 if (finalList != null) { 4939 Collections.sort(finalList, mProviderInitOrderSorter); 4940 } 4941 4942 return finalList; 4943 } 4944 4945 @Override 4946 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4947 int flags) { 4948 // reader 4949 synchronized (mPackages) { 4950 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4951 return PackageParser.generateInstrumentationInfo(i, flags); 4952 } 4953 } 4954 4955 @Override 4956 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4957 int flags) { 4958 ArrayList<InstrumentationInfo> finalList = 4959 new ArrayList<InstrumentationInfo>(); 4960 4961 // reader 4962 synchronized (mPackages) { 4963 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4964 while (i.hasNext()) { 4965 final PackageParser.Instrumentation p = i.next(); 4966 if (targetPackage == null 4967 || targetPackage.equals(p.info.targetPackage)) { 4968 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4969 flags); 4970 if (ii != null) { 4971 finalList.add(ii); 4972 } 4973 } 4974 } 4975 } 4976 4977 return finalList; 4978 } 4979 4980 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4981 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4982 if (overlays == null) { 4983 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4984 return; 4985 } 4986 for (PackageParser.Package opkg : overlays.values()) { 4987 // Not much to do if idmap fails: we already logged the error 4988 // and we certainly don't want to abort installation of pkg simply 4989 // because an overlay didn't fit properly. For these reasons, 4990 // ignore the return value of createIdmapForPackagePairLI. 4991 createIdmapForPackagePairLI(pkg, opkg); 4992 } 4993 } 4994 4995 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4996 PackageParser.Package opkg) { 4997 if (!opkg.mTrustedOverlay) { 4998 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4999 opkg.baseCodePath + ": overlay not trusted"); 5000 return false; 5001 } 5002 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 5003 if (overlaySet == null) { 5004 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 5005 opkg.baseCodePath + " but target package has no known overlays"); 5006 return false; 5007 } 5008 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 5009 // TODO: generate idmap for split APKs 5010 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 5011 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 5012 + opkg.baseCodePath); 5013 return false; 5014 } 5015 PackageParser.Package[] overlayArray = 5016 overlaySet.values().toArray(new PackageParser.Package[0]); 5017 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 5018 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 5019 return p1.mOverlayPriority - p2.mOverlayPriority; 5020 } 5021 }; 5022 Arrays.sort(overlayArray, cmp); 5023 5024 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 5025 int i = 0; 5026 for (PackageParser.Package p : overlayArray) { 5027 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 5028 } 5029 return true; 5030 } 5031 5032 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 5033 final File[] files = dir.listFiles(); 5034 if (ArrayUtils.isEmpty(files)) { 5035 Log.d(TAG, "No files in app dir " + dir); 5036 return; 5037 } 5038 5039 if (DEBUG_PACKAGE_SCANNING) { 5040 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 5041 + " flags=0x" + Integer.toHexString(parseFlags)); 5042 } 5043 5044 for (File file : files) { 5045 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 5046 && !PackageInstallerService.isStageName(file.getName()); 5047 if (!isPackage) { 5048 // Ignore entries which are not packages 5049 continue; 5050 } 5051 try { 5052 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 5053 scanFlags, currentTime, null); 5054 } catch (PackageManagerException e) { 5055 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 5056 5057 // Delete invalid userdata apps 5058 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 5059 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 5060 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 5061 if (file.isDirectory()) { 5062 mInstaller.rmPackageDir(file.getAbsolutePath()); 5063 } else { 5064 file.delete(); 5065 } 5066 } 5067 } 5068 } 5069 } 5070 5071 private static File getSettingsProblemFile() { 5072 File dataDir = Environment.getDataDirectory(); 5073 File systemDir = new File(dataDir, "system"); 5074 File fname = new File(systemDir, "uiderrors.txt"); 5075 return fname; 5076 } 5077 5078 static void reportSettingsProblem(int priority, String msg) { 5079 logCriticalInfo(priority, msg); 5080 } 5081 5082 static void logCriticalInfo(int priority, String msg) { 5083 Slog.println(priority, TAG, msg); 5084 EventLogTags.writePmCriticalInfo(msg); 5085 try { 5086 File fname = getSettingsProblemFile(); 5087 FileOutputStream out = new FileOutputStream(fname, true); 5088 PrintWriter pw = new FastPrintWriter(out); 5089 SimpleDateFormat formatter = new SimpleDateFormat(); 5090 String dateString = formatter.format(new Date(System.currentTimeMillis())); 5091 pw.println(dateString + ": " + msg); 5092 pw.close(); 5093 FileUtils.setPermissions( 5094 fname.toString(), 5095 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 5096 -1, -1); 5097 } catch (java.io.IOException e) { 5098 } 5099 } 5100 5101 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 5102 PackageParser.Package pkg, File srcFile, int parseFlags) 5103 throws PackageManagerException { 5104 if (ps != null 5105 && ps.codePath.equals(srcFile) 5106 && ps.timeStamp == srcFile.lastModified() 5107 && !isCompatSignatureUpdateNeeded(pkg) 5108 && !isRecoverSignatureUpdateNeeded(pkg)) { 5109 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 5110 if (ps.signatures.mSignatures != null 5111 && ps.signatures.mSignatures.length != 0 5112 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 5113 // Optimization: reuse the existing cached certificates 5114 // if the package appears to be unchanged. 5115 pkg.mSignatures = ps.signatures.mSignatures; 5116 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5117 synchronized (mPackages) { 5118 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 5119 } 5120 return; 5121 } 5122 5123 Slog.w(TAG, "PackageSetting for " + ps.name 5124 + " is missing signatures. Collecting certs again to recover them."); 5125 } else { 5126 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 5127 } 5128 5129 try { 5130 pp.collectCertificates(pkg, parseFlags); 5131 pp.collectManifestDigest(pkg); 5132 } catch (PackageParserException e) { 5133 throw PackageManagerException.from(e); 5134 } 5135 } 5136 5137 /* 5138 * Scan a package and return the newly parsed package. 5139 * Returns null in case of errors and the error code is stored in mLastScanError 5140 */ 5141 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 5142 long currentTime, UserHandle user) throws PackageManagerException { 5143 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 5144 parseFlags |= mDefParseFlags; 5145 PackageParser pp = new PackageParser(); 5146 pp.setSeparateProcesses(mSeparateProcesses); 5147 pp.setOnlyCoreApps(mOnlyCore); 5148 pp.setDisplayMetrics(mMetrics); 5149 5150 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 5151 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 5152 } 5153 5154 final PackageParser.Package pkg; 5155 try { 5156 pkg = pp.parsePackage(scanFile, parseFlags); 5157 } catch (PackageParserException e) { 5158 throw PackageManagerException.from(e); 5159 } 5160 5161 PackageSetting ps = null; 5162 PackageSetting updatedPkg; 5163 // reader 5164 synchronized (mPackages) { 5165 // Look to see if we already know about this package. 5166 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 5167 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 5168 // This package has been renamed to its original name. Let's 5169 // use that. 5170 ps = mSettings.peekPackageLPr(oldName); 5171 } 5172 // If there was no original package, see one for the real package name. 5173 if (ps == null) { 5174 ps = mSettings.peekPackageLPr(pkg.packageName); 5175 } 5176 // Check to see if this package could be hiding/updating a system 5177 // package. Must look for it either under the original or real 5178 // package name depending on our state. 5179 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 5180 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 5181 } 5182 boolean updatedPkgBetter = false; 5183 // First check if this is a system package that may involve an update 5184 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5185 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 5186 // it needs to drop FLAG_PRIVILEGED. 5187 if (locationIsPrivileged(scanFile)) { 5188 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5189 } else { 5190 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5191 } 5192 5193 if (ps != null && !ps.codePath.equals(scanFile)) { 5194 // The path has changed from what was last scanned... check the 5195 // version of the new path against what we have stored to determine 5196 // what to do. 5197 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 5198 if (pkg.mVersionCode <= ps.versionCode) { 5199 // The system package has been updated and the code path does not match 5200 // Ignore entry. Skip it. 5201 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 5202 + " ignored: updated version " + ps.versionCode 5203 + " better than this " + pkg.mVersionCode); 5204 if (!updatedPkg.codePath.equals(scanFile)) { 5205 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 5206 + ps.name + " changing from " + updatedPkg.codePathString 5207 + " to " + scanFile); 5208 updatedPkg.codePath = scanFile; 5209 updatedPkg.codePathString = scanFile.toString(); 5210 updatedPkg.resourcePath = scanFile; 5211 updatedPkg.resourcePathString = scanFile.toString(); 5212 } 5213 updatedPkg.pkg = pkg; 5214 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 5215 } else { 5216 // The current app on the system partition is better than 5217 // what we have updated to on the data partition; switch 5218 // back to the system partition version. 5219 // At this point, its safely assumed that package installation for 5220 // apps in system partition will go through. If not there won't be a working 5221 // version of the app 5222 // writer 5223 synchronized (mPackages) { 5224 // Just remove the loaded entries from package lists. 5225 mPackages.remove(ps.name); 5226 } 5227 5228 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5229 + " reverting from " + ps.codePathString 5230 + ": new version " + pkg.mVersionCode 5231 + " better than installed " + ps.versionCode); 5232 5233 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5234 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5235 synchronized (mInstallLock) { 5236 args.cleanUpResourcesLI(); 5237 } 5238 synchronized (mPackages) { 5239 mSettings.enableSystemPackageLPw(ps.name); 5240 } 5241 updatedPkgBetter = true; 5242 } 5243 } 5244 } 5245 5246 if (updatedPkg != null) { 5247 // An updated system app will not have the PARSE_IS_SYSTEM flag set 5248 // initially 5249 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 5250 5251 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 5252 // flag set initially 5253 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 5254 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 5255 } 5256 } 5257 5258 // Verify certificates against what was last scanned 5259 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 5260 5261 /* 5262 * A new system app appeared, but we already had a non-system one of the 5263 * same name installed earlier. 5264 */ 5265 boolean shouldHideSystemApp = false; 5266 if (updatedPkg == null && ps != null 5267 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 5268 /* 5269 * Check to make sure the signatures match first. If they don't, 5270 * wipe the installed application and its data. 5271 */ 5272 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 5273 != PackageManager.SIGNATURE_MATCH) { 5274 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 5275 + " signatures don't match existing userdata copy; removing"); 5276 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 5277 ps = null; 5278 } else { 5279 /* 5280 * If the newly-added system app is an older version than the 5281 * already installed version, hide it. It will be scanned later 5282 * and re-added like an update. 5283 */ 5284 if (pkg.mVersionCode <= ps.versionCode) { 5285 shouldHideSystemApp = true; 5286 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 5287 + " but new version " + pkg.mVersionCode + " better than installed " 5288 + ps.versionCode + "; hiding system"); 5289 } else { 5290 /* 5291 * The newly found system app is a newer version that the 5292 * one previously installed. Simply remove the 5293 * already-installed application and replace it with our own 5294 * while keeping the application data. 5295 */ 5296 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 5297 + " reverting from " + ps.codePathString + ": new version " 5298 + pkg.mVersionCode + " better than installed " + ps.versionCode); 5299 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 5300 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 5301 synchronized (mInstallLock) { 5302 args.cleanUpResourcesLI(); 5303 } 5304 } 5305 } 5306 } 5307 5308 // The apk is forward locked (not public) if its code and resources 5309 // are kept in different files. (except for app in either system or 5310 // vendor path). 5311 // TODO grab this value from PackageSettings 5312 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5313 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 5314 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 5315 } 5316 } 5317 5318 // TODO: extend to support forward-locked splits 5319 String resourcePath = null; 5320 String baseResourcePath = null; 5321 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 5322 if (ps != null && ps.resourcePathString != null) { 5323 resourcePath = ps.resourcePathString; 5324 baseResourcePath = ps.resourcePathString; 5325 } else { 5326 // Should not happen at all. Just log an error. 5327 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 5328 } 5329 } else { 5330 resourcePath = pkg.codePath; 5331 baseResourcePath = pkg.baseCodePath; 5332 } 5333 5334 // Set application objects path explicitly. 5335 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 5336 pkg.applicationInfo.setCodePath(pkg.codePath); 5337 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 5338 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 5339 pkg.applicationInfo.setResourcePath(resourcePath); 5340 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 5341 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 5342 5343 // Note that we invoke the following method only if we are about to unpack an application 5344 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 5345 | SCAN_UPDATE_SIGNATURE, currentTime, user); 5346 5347 /* 5348 * If the system app should be overridden by a previously installed 5349 * data, hide the system app now and let the /data/app scan pick it up 5350 * again. 5351 */ 5352 if (shouldHideSystemApp) { 5353 synchronized (mPackages) { 5354 /* 5355 * We have to grant systems permissions before we hide, because 5356 * grantPermissions will assume the package update is trying to 5357 * expand its permissions. 5358 */ 5359 grantPermissionsLPw(pkg, true, pkg.packageName); 5360 mSettings.disableSystemPackageLPw(pkg.packageName); 5361 } 5362 } 5363 5364 return scannedPkg; 5365 } 5366 5367 private static String fixProcessName(String defProcessName, 5368 String processName, int uid) { 5369 if (processName == null) { 5370 return defProcessName; 5371 } 5372 return processName; 5373 } 5374 5375 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 5376 throws PackageManagerException { 5377 if (pkgSetting.signatures.mSignatures != null) { 5378 // Already existing package. Make sure signatures match 5379 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 5380 == PackageManager.SIGNATURE_MATCH; 5381 if (!match) { 5382 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 5383 == PackageManager.SIGNATURE_MATCH; 5384 } 5385 if (!match) { 5386 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 5387 == PackageManager.SIGNATURE_MATCH; 5388 } 5389 if (!match) { 5390 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5391 + pkg.packageName + " signatures do not match the " 5392 + "previously installed version; ignoring!"); 5393 } 5394 } 5395 5396 // Check for shared user signatures 5397 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 5398 // Already existing package. Make sure signatures match 5399 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5400 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 5401 if (!match) { 5402 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 5403 == PackageManager.SIGNATURE_MATCH; 5404 } 5405 if (!match) { 5406 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 5407 == PackageManager.SIGNATURE_MATCH; 5408 } 5409 if (!match) { 5410 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 5411 "Package " + pkg.packageName 5412 + " has no signatures that match those in shared user " 5413 + pkgSetting.sharedUser.name + "; ignoring!"); 5414 } 5415 } 5416 } 5417 5418 /** 5419 * Enforces that only the system UID or root's UID can call a method exposed 5420 * via Binder. 5421 * 5422 * @param message used as message if SecurityException is thrown 5423 * @throws SecurityException if the caller is not system or root 5424 */ 5425 private static final void enforceSystemOrRoot(String message) { 5426 final int uid = Binder.getCallingUid(); 5427 if (uid != Process.SYSTEM_UID && uid != 0) { 5428 throw new SecurityException(message); 5429 } 5430 } 5431 5432 @Override 5433 public void performBootDexOpt() { 5434 enforceSystemOrRoot("Only the system can request dexopt be performed"); 5435 5436 // Before everything else, see whether we need to fstrim. 5437 try { 5438 IMountService ms = PackageHelper.getMountService(); 5439 if (ms != null) { 5440 final boolean isUpgrade = isUpgrade(); 5441 boolean doTrim = isUpgrade; 5442 if (doTrim) { 5443 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 5444 } else { 5445 final long interval = android.provider.Settings.Global.getLong( 5446 mContext.getContentResolver(), 5447 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 5448 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 5449 if (interval > 0) { 5450 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 5451 if (timeSinceLast > interval) { 5452 doTrim = true; 5453 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 5454 + "; running immediately"); 5455 } 5456 } 5457 } 5458 if (doTrim) { 5459 if (!isFirstBoot()) { 5460 try { 5461 ActivityManagerNative.getDefault().showBootMessage( 5462 mContext.getResources().getString( 5463 R.string.android_upgrading_fstrim), true); 5464 } catch (RemoteException e) { 5465 } 5466 } 5467 ms.runMaintenance(); 5468 } 5469 } else { 5470 Slog.e(TAG, "Mount service unavailable!"); 5471 } 5472 } catch (RemoteException e) { 5473 // Can't happen; MountService is local 5474 } 5475 5476 final ArraySet<PackageParser.Package> pkgs; 5477 synchronized (mPackages) { 5478 pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages(); 5479 } 5480 5481 if (pkgs != null) { 5482 // Sort apps by importance for dexopt ordering. Important apps are given more priority 5483 // in case the device runs out of space. 5484 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 5485 // Give priority to core apps. 5486 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5487 PackageParser.Package pkg = it.next(); 5488 if (pkg.coreApp) { 5489 if (DEBUG_DEXOPT) { 5490 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 5491 } 5492 sortedPkgs.add(pkg); 5493 it.remove(); 5494 } 5495 } 5496 // Give priority to system apps that listen for pre boot complete. 5497 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 5498 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 5499 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5500 PackageParser.Package pkg = it.next(); 5501 if (pkgNames.contains(pkg.packageName)) { 5502 if (DEBUG_DEXOPT) { 5503 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 5504 } 5505 sortedPkgs.add(pkg); 5506 it.remove(); 5507 } 5508 } 5509 // Give priority to system apps. 5510 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5511 PackageParser.Package pkg = it.next(); 5512 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 5513 if (DEBUG_DEXOPT) { 5514 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 5515 } 5516 sortedPkgs.add(pkg); 5517 it.remove(); 5518 } 5519 } 5520 // Give priority to updated system apps. 5521 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5522 PackageParser.Package pkg = it.next(); 5523 if (pkg.isUpdatedSystemApp()) { 5524 if (DEBUG_DEXOPT) { 5525 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 5526 } 5527 sortedPkgs.add(pkg); 5528 it.remove(); 5529 } 5530 } 5531 // Give priority to apps that listen for boot complete. 5532 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 5533 pkgNames = getPackageNamesForIntent(intent); 5534 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 5535 PackageParser.Package pkg = it.next(); 5536 if (pkgNames.contains(pkg.packageName)) { 5537 if (DEBUG_DEXOPT) { 5538 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 5539 } 5540 sortedPkgs.add(pkg); 5541 it.remove(); 5542 } 5543 } 5544 // Filter out packages that aren't recently used. 5545 filterRecentlyUsedApps(pkgs); 5546 // Add all remaining apps. 5547 for (PackageParser.Package pkg : pkgs) { 5548 if (DEBUG_DEXOPT) { 5549 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 5550 } 5551 sortedPkgs.add(pkg); 5552 } 5553 5554 // If we want to be lazy, filter everything that wasn't recently used. 5555 if (mLazyDexOpt) { 5556 filterRecentlyUsedApps(sortedPkgs); 5557 } 5558 5559 int i = 0; 5560 int total = sortedPkgs.size(); 5561 File dataDir = Environment.getDataDirectory(); 5562 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 5563 if (lowThreshold == 0) { 5564 throw new IllegalStateException("Invalid low memory threshold"); 5565 } 5566 for (PackageParser.Package pkg : sortedPkgs) { 5567 long usableSpace = dataDir.getUsableSpace(); 5568 if (usableSpace < lowThreshold) { 5569 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 5570 break; 5571 } 5572 performBootDexOpt(pkg, ++i, total); 5573 } 5574 } 5575 } 5576 5577 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 5578 // Filter out packages that aren't recently used. 5579 // 5580 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 5581 // should do a full dexopt. 5582 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 5583 int total = pkgs.size(); 5584 int skipped = 0; 5585 long now = System.currentTimeMillis(); 5586 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 5587 PackageParser.Package pkg = i.next(); 5588 long then = pkg.mLastPackageUsageTimeInMills; 5589 if (then + mDexOptLRUThresholdInMills < now) { 5590 if (DEBUG_DEXOPT) { 5591 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 5592 ((then == 0) ? "never" : new Date(then))); 5593 } 5594 i.remove(); 5595 skipped++; 5596 } 5597 } 5598 if (DEBUG_DEXOPT) { 5599 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 5600 } 5601 } 5602 } 5603 5604 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 5605 List<ResolveInfo> ris = null; 5606 try { 5607 ris = AppGlobals.getPackageManager().queryIntentReceivers( 5608 intent, null, 0, UserHandle.USER_OWNER); 5609 } catch (RemoteException e) { 5610 } 5611 ArraySet<String> pkgNames = new ArraySet<String>(); 5612 if (ris != null) { 5613 for (ResolveInfo ri : ris) { 5614 pkgNames.add(ri.activityInfo.packageName); 5615 } 5616 } 5617 return pkgNames; 5618 } 5619 5620 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 5621 if (DEBUG_DEXOPT) { 5622 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 5623 } 5624 if (!isFirstBoot()) { 5625 try { 5626 ActivityManagerNative.getDefault().showBootMessage( 5627 mContext.getResources().getString(R.string.android_upgrading_apk, 5628 curr, total), true); 5629 } catch (RemoteException e) { 5630 } 5631 } 5632 PackageParser.Package p = pkg; 5633 synchronized (mInstallLock) { 5634 mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */, 5635 false /* force dex */, false /* defer */, true /* include dependencies */); 5636 } 5637 } 5638 5639 @Override 5640 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 5641 return performDexOpt(packageName, instructionSet, false); 5642 } 5643 5644 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 5645 boolean dexopt = mLazyDexOpt || backgroundDexopt; 5646 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 5647 if (!dexopt && !updateUsage) { 5648 // We aren't going to dexopt or update usage, so bail early. 5649 return false; 5650 } 5651 PackageParser.Package p; 5652 final String targetInstructionSet; 5653 synchronized (mPackages) { 5654 p = mPackages.get(packageName); 5655 if (p == null) { 5656 return false; 5657 } 5658 if (updateUsage) { 5659 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 5660 } 5661 mPackageUsage.write(false); 5662 if (!dexopt) { 5663 // We aren't going to dexopt, so bail early. 5664 return false; 5665 } 5666 5667 targetInstructionSet = instructionSet != null ? instructionSet : 5668 getPrimaryInstructionSet(p.applicationInfo); 5669 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 5670 return false; 5671 } 5672 } 5673 5674 synchronized (mInstallLock) { 5675 final String[] instructionSets = new String[] { targetInstructionSet }; 5676 int result = mPackageDexOptimizer.performDexOpt(p, instructionSets, 5677 false /* forceDex */, false /* defer */, true /* inclDependencies */); 5678 return result == PackageDexOptimizer.DEX_OPT_PERFORMED; 5679 } 5680 } 5681 5682 public ArraySet<String> getPackagesThatNeedDexOpt() { 5683 ArraySet<String> pkgs = null; 5684 synchronized (mPackages) { 5685 for (PackageParser.Package p : mPackages.values()) { 5686 if (DEBUG_DEXOPT) { 5687 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 5688 } 5689 if (!p.mDexOptPerformed.isEmpty()) { 5690 continue; 5691 } 5692 if (pkgs == null) { 5693 pkgs = new ArraySet<String>(); 5694 } 5695 pkgs.add(p.packageName); 5696 } 5697 } 5698 return pkgs; 5699 } 5700 5701 public void shutdown() { 5702 mPackageUsage.write(true); 5703 } 5704 5705 @Override 5706 public void forceDexOpt(String packageName) { 5707 enforceSystemOrRoot("forceDexOpt"); 5708 5709 PackageParser.Package pkg; 5710 synchronized (mPackages) { 5711 pkg = mPackages.get(packageName); 5712 if (pkg == null) { 5713 throw new IllegalArgumentException("Missing package: " + packageName); 5714 } 5715 } 5716 5717 synchronized (mInstallLock) { 5718 final String[] instructionSets = new String[] { 5719 getPrimaryInstructionSet(pkg.applicationInfo) }; 5720 final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets, 5721 true /*forceDex*/, false /* defer */, true /* inclDependencies */); 5722 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 5723 throw new IllegalStateException("Failed to dexopt: " + res); 5724 } 5725 } 5726 } 5727 5728 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5729 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5730 Slog.w(TAG, "Unable to update from " + oldPkg.name 5731 + " to " + newPkg.packageName 5732 + ": old package not in system partition"); 5733 return false; 5734 } else if (mPackages.get(oldPkg.name) != null) { 5735 Slog.w(TAG, "Unable to update from " + oldPkg.name 5736 + " to " + newPkg.packageName 5737 + ": old package still exists"); 5738 return false; 5739 } 5740 return true; 5741 } 5742 5743 private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) { 5744 int[] users = sUserManager.getUserIds(); 5745 int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo); 5746 if (res < 0) { 5747 return res; 5748 } 5749 for (int user : users) { 5750 if (user != 0) { 5751 res = mInstaller.createUserData(volumeUuid, packageName, 5752 UserHandle.getUid(user, uid), user, seinfo); 5753 if (res < 0) { 5754 return res; 5755 } 5756 } 5757 } 5758 return res; 5759 } 5760 5761 private int removeDataDirsLI(String volumeUuid, String packageName) { 5762 int[] users = sUserManager.getUserIds(); 5763 int res = 0; 5764 for (int user : users) { 5765 int resInner = mInstaller.remove(volumeUuid, packageName, user); 5766 if (resInner < 0) { 5767 res = resInner; 5768 } 5769 } 5770 5771 return res; 5772 } 5773 5774 private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) { 5775 int[] users = sUserManager.getUserIds(); 5776 int res = 0; 5777 for (int user : users) { 5778 int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user); 5779 if (resInner < 0) { 5780 res = resInner; 5781 } 5782 } 5783 return res; 5784 } 5785 5786 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5787 PackageParser.Package changingLib) { 5788 if (file.path != null) { 5789 usesLibraryFiles.add(file.path); 5790 return; 5791 } 5792 PackageParser.Package p = mPackages.get(file.apk); 5793 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5794 // If we are doing this while in the middle of updating a library apk, 5795 // then we need to make sure to use that new apk for determining the 5796 // dependencies here. (We haven't yet finished committing the new apk 5797 // to the package manager state.) 5798 if (p == null || p.packageName.equals(changingLib.packageName)) { 5799 p = changingLib; 5800 } 5801 } 5802 if (p != null) { 5803 usesLibraryFiles.addAll(p.getAllCodePaths()); 5804 } 5805 } 5806 5807 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5808 PackageParser.Package changingLib) throws PackageManagerException { 5809 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5810 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5811 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5812 for (int i=0; i<N; i++) { 5813 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5814 if (file == null) { 5815 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5816 "Package " + pkg.packageName + " requires unavailable shared library " 5817 + pkg.usesLibraries.get(i) + "; failing!"); 5818 } 5819 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5820 } 5821 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5822 for (int i=0; i<N; i++) { 5823 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5824 if (file == null) { 5825 Slog.w(TAG, "Package " + pkg.packageName 5826 + " desires unavailable shared library " 5827 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5828 } else { 5829 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5830 } 5831 } 5832 N = usesLibraryFiles.size(); 5833 if (N > 0) { 5834 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5835 } else { 5836 pkg.usesLibraryFiles = null; 5837 } 5838 } 5839 } 5840 5841 private static boolean hasString(List<String> list, List<String> which) { 5842 if (list == null) { 5843 return false; 5844 } 5845 for (int i=list.size()-1; i>=0; i--) { 5846 for (int j=which.size()-1; j>=0; j--) { 5847 if (which.get(j).equals(list.get(i))) { 5848 return true; 5849 } 5850 } 5851 } 5852 return false; 5853 } 5854 5855 private void updateAllSharedLibrariesLPw() { 5856 for (PackageParser.Package pkg : mPackages.values()) { 5857 try { 5858 updateSharedLibrariesLPw(pkg, null); 5859 } catch (PackageManagerException e) { 5860 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5861 } 5862 } 5863 } 5864 5865 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5866 PackageParser.Package changingPkg) { 5867 ArrayList<PackageParser.Package> res = null; 5868 for (PackageParser.Package pkg : mPackages.values()) { 5869 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5870 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5871 if (res == null) { 5872 res = new ArrayList<PackageParser.Package>(); 5873 } 5874 res.add(pkg); 5875 try { 5876 updateSharedLibrariesLPw(pkg, changingPkg); 5877 } catch (PackageManagerException e) { 5878 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5879 } 5880 } 5881 } 5882 return res; 5883 } 5884 5885 /** 5886 * Derive the value of the {@code cpuAbiOverride} based on the provided 5887 * value and an optional stored value from the package settings. 5888 */ 5889 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5890 String cpuAbiOverride = null; 5891 5892 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5893 cpuAbiOverride = null; 5894 } else if (abiOverride != null) { 5895 cpuAbiOverride = abiOverride; 5896 } else if (settings != null) { 5897 cpuAbiOverride = settings.cpuAbiOverrideString; 5898 } 5899 5900 return cpuAbiOverride; 5901 } 5902 5903 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5904 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5905 boolean success = false; 5906 try { 5907 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5908 currentTime, user); 5909 success = true; 5910 return res; 5911 } finally { 5912 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5913 removeDataDirsLI(pkg.volumeUuid, pkg.packageName); 5914 } 5915 } 5916 } 5917 5918 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5919 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5920 final File scanFile = new File(pkg.codePath); 5921 if (pkg.applicationInfo.getCodePath() == null || 5922 pkg.applicationInfo.getResourcePath() == null) { 5923 // Bail out. The resource and code paths haven't been set. 5924 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5925 "Code and resource paths haven't been set correctly"); 5926 } 5927 5928 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5929 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5930 } else { 5931 // Only allow system apps to be flagged as core apps. 5932 pkg.coreApp = false; 5933 } 5934 5935 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5936 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5937 } 5938 5939 if (mCustomResolverComponentName != null && 5940 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5941 setUpCustomResolverActivity(pkg); 5942 } 5943 5944 if (pkg.packageName.equals("android")) { 5945 synchronized (mPackages) { 5946 if (mAndroidApplication != null) { 5947 Slog.w(TAG, "*************************************************"); 5948 Slog.w(TAG, "Core android package being redefined. Skipping."); 5949 Slog.w(TAG, " file=" + scanFile); 5950 Slog.w(TAG, "*************************************************"); 5951 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5952 "Core android package being redefined. Skipping."); 5953 } 5954 5955 // Set up information for our fall-back user intent resolution activity. 5956 mPlatformPackage = pkg; 5957 pkg.mVersionCode = mSdkVersion; 5958 mAndroidApplication = pkg.applicationInfo; 5959 5960 if (!mResolverReplaced) { 5961 mResolveActivity.applicationInfo = mAndroidApplication; 5962 mResolveActivity.name = ResolverActivity.class.getName(); 5963 mResolveActivity.packageName = mAndroidApplication.packageName; 5964 mResolveActivity.processName = "system:ui"; 5965 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5966 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5967 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5968 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5969 mResolveActivity.exported = true; 5970 mResolveActivity.enabled = true; 5971 mResolveInfo.activityInfo = mResolveActivity; 5972 mResolveInfo.priority = 0; 5973 mResolveInfo.preferredOrder = 0; 5974 mResolveInfo.match = 0; 5975 mResolveComponentName = new ComponentName( 5976 mAndroidApplication.packageName, mResolveActivity.name); 5977 } 5978 } 5979 } 5980 5981 if (DEBUG_PACKAGE_SCANNING) { 5982 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5983 Log.d(TAG, "Scanning package " + pkg.packageName); 5984 } 5985 5986 if (mPackages.containsKey(pkg.packageName) 5987 || mSharedLibraries.containsKey(pkg.packageName)) { 5988 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5989 "Application package " + pkg.packageName 5990 + " already installed. Skipping duplicate."); 5991 } 5992 5993 // If we're only installing presumed-existing packages, require that the 5994 // scanned APK is both already known and at the path previously established 5995 // for it. Previously unknown packages we pick up normally, but if we have an 5996 // a priori expectation about this package's install presence, enforce it. 5997 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 5998 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 5999 if (known != null) { 6000 if (DEBUG_PACKAGE_SCANNING) { 6001 Log.d(TAG, "Examining " + pkg.codePath 6002 + " and requiring known paths " + known.codePathString 6003 + " & " + known.resourcePathString); 6004 } 6005 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 6006 || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) { 6007 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 6008 "Application package " + pkg.packageName 6009 + " found at " + pkg.applicationInfo.getCodePath() 6010 + " but expected at " + known.codePathString + "; ignoring."); 6011 } 6012 } 6013 } 6014 6015 // Initialize package source and resource directories 6016 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 6017 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 6018 6019 SharedUserSetting suid = null; 6020 PackageSetting pkgSetting = null; 6021 6022 if (!isSystemApp(pkg)) { 6023 // Only system apps can use these features. 6024 pkg.mOriginalPackages = null; 6025 pkg.mRealPackage = null; 6026 pkg.mAdoptPermissions = null; 6027 } 6028 6029 // writer 6030 synchronized (mPackages) { 6031 if (pkg.mSharedUserId != null) { 6032 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 6033 if (suid == null) { 6034 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6035 "Creating application package " + pkg.packageName 6036 + " for shared user failed"); 6037 } 6038 if (DEBUG_PACKAGE_SCANNING) { 6039 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6040 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 6041 + "): packages=" + suid.packages); 6042 } 6043 } 6044 6045 // Check if we are renaming from an original package name. 6046 PackageSetting origPackage = null; 6047 String realName = null; 6048 if (pkg.mOriginalPackages != null) { 6049 // This package may need to be renamed to a previously 6050 // installed name. Let's check on that... 6051 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 6052 if (pkg.mOriginalPackages.contains(renamed)) { 6053 // This package had originally been installed as the 6054 // original name, and we have already taken care of 6055 // transitioning to the new one. Just update the new 6056 // one to continue using the old name. 6057 realName = pkg.mRealPackage; 6058 if (!pkg.packageName.equals(renamed)) { 6059 // Callers into this function may have already taken 6060 // care of renaming the package; only do it here if 6061 // it is not already done. 6062 pkg.setPackageName(renamed); 6063 } 6064 6065 } else { 6066 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 6067 if ((origPackage = mSettings.peekPackageLPr( 6068 pkg.mOriginalPackages.get(i))) != null) { 6069 // We do have the package already installed under its 6070 // original name... should we use it? 6071 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 6072 // New package is not compatible with original. 6073 origPackage = null; 6074 continue; 6075 } else if (origPackage.sharedUser != null) { 6076 // Make sure uid is compatible between packages. 6077 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 6078 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 6079 + " to " + pkg.packageName + ": old uid " 6080 + origPackage.sharedUser.name 6081 + " differs from " + pkg.mSharedUserId); 6082 origPackage = null; 6083 continue; 6084 } 6085 } else { 6086 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 6087 + pkg.packageName + " to old name " + origPackage.name); 6088 } 6089 break; 6090 } 6091 } 6092 } 6093 } 6094 6095 if (mTransferedPackages.contains(pkg.packageName)) { 6096 Slog.w(TAG, "Package " + pkg.packageName 6097 + " was transferred to another, but its .apk remains"); 6098 } 6099 6100 // Just create the setting, don't add it yet. For already existing packages 6101 // the PkgSetting exists already and doesn't have to be created. 6102 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 6103 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 6104 pkg.applicationInfo.primaryCpuAbi, 6105 pkg.applicationInfo.secondaryCpuAbi, 6106 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 6107 user, false); 6108 if (pkgSetting == null) { 6109 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6110 "Creating application package " + pkg.packageName + " failed"); 6111 } 6112 6113 if (pkgSetting.origPackage != null) { 6114 // If we are first transitioning from an original package, 6115 // fix up the new package's name now. We need to do this after 6116 // looking up the package under its new name, so getPackageLP 6117 // can take care of fiddling things correctly. 6118 pkg.setPackageName(origPackage.name); 6119 6120 // File a report about this. 6121 String msg = "New package " + pkgSetting.realName 6122 + " renamed to replace old package " + pkgSetting.name; 6123 reportSettingsProblem(Log.WARN, msg); 6124 6125 // Make a note of it. 6126 mTransferedPackages.add(origPackage.name); 6127 6128 // No longer need to retain this. 6129 pkgSetting.origPackage = null; 6130 } 6131 6132 if (realName != null) { 6133 // Make a note of it. 6134 mTransferedPackages.add(pkg.packageName); 6135 } 6136 6137 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 6138 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 6139 } 6140 6141 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6142 // Check all shared libraries and map to their actual file path. 6143 // We only do this here for apps not on a system dir, because those 6144 // are the only ones that can fail an install due to this. We 6145 // will take care of the system apps by updating all of their 6146 // library paths after the scan is done. 6147 updateSharedLibrariesLPw(pkg, null); 6148 } 6149 6150 if (mFoundPolicyFile) { 6151 SELinuxMMAC.assignSeinfoValue(pkg); 6152 } 6153 6154 pkg.applicationInfo.uid = pkgSetting.appId; 6155 pkg.mExtras = pkgSetting; 6156 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 6157 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 6158 // We just determined the app is signed correctly, so bring 6159 // over the latest parsed certs. 6160 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6161 } else { 6162 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6163 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6164 "Package " + pkg.packageName + " upgrade keys do not match the " 6165 + "previously installed version"); 6166 } else { 6167 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6168 String msg = "System package " + pkg.packageName 6169 + " signature changed; retaining data."; 6170 reportSettingsProblem(Log.WARN, msg); 6171 } 6172 } 6173 } else { 6174 try { 6175 verifySignaturesLP(pkgSetting, pkg); 6176 // We just determined the app is signed correctly, so bring 6177 // over the latest parsed certs. 6178 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6179 } catch (PackageManagerException e) { 6180 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6181 throw e; 6182 } 6183 // The signature has changed, but this package is in the system 6184 // image... let's recover! 6185 pkgSetting.signatures.mSignatures = pkg.mSignatures; 6186 // However... if this package is part of a shared user, but it 6187 // doesn't match the signature of the shared user, let's fail. 6188 // What this means is that you can't change the signatures 6189 // associated with an overall shared user, which doesn't seem all 6190 // that unreasonable. 6191 if (pkgSetting.sharedUser != null) { 6192 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6193 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 6194 throw new PackageManagerException( 6195 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 6196 "Signature mismatch for shared user : " 6197 + pkgSetting.sharedUser); 6198 } 6199 } 6200 // File a report about this. 6201 String msg = "System package " + pkg.packageName 6202 + " signature changed; retaining data."; 6203 reportSettingsProblem(Log.WARN, msg); 6204 } 6205 } 6206 // Verify that this new package doesn't have any content providers 6207 // that conflict with existing packages. Only do this if the 6208 // package isn't already installed, since we don't want to break 6209 // things that are installed. 6210 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 6211 final int N = pkg.providers.size(); 6212 int i; 6213 for (i=0; i<N; i++) { 6214 PackageParser.Provider p = pkg.providers.get(i); 6215 if (p.info.authority != null) { 6216 String names[] = p.info.authority.split(";"); 6217 for (int j = 0; j < names.length; j++) { 6218 if (mProvidersByAuthority.containsKey(names[j])) { 6219 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6220 final String otherPackageName = 6221 ((other != null && other.getComponentName() != null) ? 6222 other.getComponentName().getPackageName() : "?"); 6223 throw new PackageManagerException( 6224 INSTALL_FAILED_CONFLICTING_PROVIDER, 6225 "Can't install because provider name " + names[j] 6226 + " (in package " + pkg.applicationInfo.packageName 6227 + ") is already used by " + otherPackageName); 6228 } 6229 } 6230 } 6231 } 6232 } 6233 6234 if (pkg.mAdoptPermissions != null) { 6235 // This package wants to adopt ownership of permissions from 6236 // another package. 6237 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 6238 final String origName = pkg.mAdoptPermissions.get(i); 6239 final PackageSetting orig = mSettings.peekPackageLPr(origName); 6240 if (orig != null) { 6241 if (verifyPackageUpdateLPr(orig, pkg)) { 6242 Slog.i(TAG, "Adopting permissions from " + origName + " to " 6243 + pkg.packageName); 6244 mSettings.transferPermissionsLPw(origName, pkg.packageName); 6245 } 6246 } 6247 } 6248 } 6249 } 6250 6251 final String pkgName = pkg.packageName; 6252 6253 final long scanFileTime = scanFile.lastModified(); 6254 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 6255 pkg.applicationInfo.processName = fixProcessName( 6256 pkg.applicationInfo.packageName, 6257 pkg.applicationInfo.processName, 6258 pkg.applicationInfo.uid); 6259 6260 File dataPath; 6261 if (mPlatformPackage == pkg) { 6262 // The system package is special. 6263 dataPath = new File(Environment.getDataDirectory(), "system"); 6264 6265 pkg.applicationInfo.dataDir = dataPath.getPath(); 6266 6267 } else { 6268 // This is a normal package, need to make its data directory. 6269 dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName, 6270 UserHandle.USER_OWNER); 6271 6272 boolean uidError = false; 6273 if (dataPath.exists()) { 6274 int currentUid = 0; 6275 try { 6276 StructStat stat = Os.stat(dataPath.getPath()); 6277 currentUid = stat.st_uid; 6278 } catch (ErrnoException e) { 6279 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 6280 } 6281 6282 // If we have mismatched owners for the data path, we have a problem. 6283 if (currentUid != pkg.applicationInfo.uid) { 6284 boolean recovered = false; 6285 if (currentUid == 0) { 6286 // The directory somehow became owned by root. Wow. 6287 // This is probably because the system was stopped while 6288 // installd was in the middle of messing with its libs 6289 // directory. Ask installd to fix that. 6290 int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName, 6291 pkg.applicationInfo.uid, pkg.applicationInfo.uid); 6292 if (ret >= 0) { 6293 recovered = true; 6294 String msg = "Package " + pkg.packageName 6295 + " unexpectedly changed to uid 0; recovered to " + 6296 + pkg.applicationInfo.uid; 6297 reportSettingsProblem(Log.WARN, msg); 6298 } 6299 } 6300 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6301 || (scanFlags&SCAN_BOOTING) != 0)) { 6302 // If this is a system app, we can at least delete its 6303 // current data so the application will still work. 6304 int ret = removeDataDirsLI(pkg.volumeUuid, pkgName); 6305 if (ret >= 0) { 6306 // TODO: Kill the processes first 6307 // Old data gone! 6308 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 6309 ? "System package " : "Third party package "; 6310 String msg = prefix + pkg.packageName 6311 + " has changed from uid: " 6312 + currentUid + " to " 6313 + pkg.applicationInfo.uid + "; old data erased"; 6314 reportSettingsProblem(Log.WARN, msg); 6315 recovered = true; 6316 6317 // And now re-install the app. 6318 ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6319 pkg.applicationInfo.seinfo); 6320 if (ret == -1) { 6321 // Ack should not happen! 6322 msg = prefix + pkg.packageName 6323 + " could not have data directory re-created after delete."; 6324 reportSettingsProblem(Log.WARN, msg); 6325 throw new PackageManagerException( 6326 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 6327 } 6328 } 6329 if (!recovered) { 6330 mHasSystemUidErrors = true; 6331 } 6332 } else if (!recovered) { 6333 // If we allow this install to proceed, we will be broken. 6334 // Abort, abort! 6335 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 6336 "scanPackageLI"); 6337 } 6338 if (!recovered) { 6339 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 6340 + pkg.applicationInfo.uid + "/fs_" 6341 + currentUid; 6342 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 6343 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 6344 String msg = "Package " + pkg.packageName 6345 + " has mismatched uid: " 6346 + currentUid + " on disk, " 6347 + pkg.applicationInfo.uid + " in settings"; 6348 // writer 6349 synchronized (mPackages) { 6350 mSettings.mReadMessages.append(msg); 6351 mSettings.mReadMessages.append('\n'); 6352 uidError = true; 6353 if (!pkgSetting.uidError) { 6354 reportSettingsProblem(Log.ERROR, msg); 6355 } 6356 } 6357 } 6358 } 6359 pkg.applicationInfo.dataDir = dataPath.getPath(); 6360 if (mShouldRestoreconData) { 6361 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 6362 mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName, 6363 pkg.applicationInfo.seinfo, pkg.applicationInfo.uid); 6364 } 6365 } else { 6366 if (DEBUG_PACKAGE_SCANNING) { 6367 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6368 Log.v(TAG, "Want this data dir: " + dataPath); 6369 } 6370 //invoke installer to do the actual installation 6371 int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid, 6372 pkg.applicationInfo.seinfo); 6373 if (ret < 0) { 6374 // Error from installer 6375 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 6376 "Unable to create data dirs [errorCode=" + ret + "]"); 6377 } 6378 6379 if (dataPath.exists()) { 6380 pkg.applicationInfo.dataDir = dataPath.getPath(); 6381 } else { 6382 Slog.w(TAG, "Unable to create data directory: " + dataPath); 6383 pkg.applicationInfo.dataDir = null; 6384 } 6385 } 6386 6387 pkgSetting.uidError = uidError; 6388 } 6389 6390 final String path = scanFile.getPath(); 6391 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 6392 6393 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 6394 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 6395 6396 // Some system apps still use directory structure for native libraries 6397 // in which case we might end up not detecting abi solely based on apk 6398 // structure. Try to detect abi based on directory structure. 6399 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 6400 pkg.applicationInfo.primaryCpuAbi == null) { 6401 setBundledAppAbisAndRoots(pkg, pkgSetting); 6402 setNativeLibraryPaths(pkg); 6403 } 6404 6405 } else { 6406 if ((scanFlags & SCAN_MOVE) != 0) { 6407 // We haven't run dex-opt for this move (since we've moved the compiled output too) 6408 // but we already have this packages package info in the PackageSetting. We just 6409 // use that and derive the native library path based on the new codepath. 6410 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 6411 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 6412 } 6413 6414 // Set native library paths again. For moves, the path will be updated based on the 6415 // ABIs we've determined above. For non-moves, the path will be updated based on the 6416 // ABIs we determined during compilation, but the path will depend on the final 6417 // package path (after the rename away from the stage path). 6418 setNativeLibraryPaths(pkg); 6419 } 6420 6421 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 6422 final int[] userIds = sUserManager.getUserIds(); 6423 synchronized (mInstallLock) { 6424 // Create a native library symlink only if we have native libraries 6425 // and if the native libraries are 32 bit libraries. We do not provide 6426 // this symlink for 64 bit libraries. 6427 if (pkg.applicationInfo.primaryCpuAbi != null && 6428 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 6429 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 6430 for (int userId : userIds) { 6431 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 6432 nativeLibPath, userId) < 0) { 6433 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 6434 "Failed linking native library dir (user=" + userId + ")"); 6435 } 6436 } 6437 } 6438 } 6439 6440 // This is a special case for the "system" package, where the ABI is 6441 // dictated by the zygote configuration (and init.rc). We should keep track 6442 // of this ABI so that we can deal with "normal" applications that run under 6443 // the same UID correctly. 6444 if (mPlatformPackage == pkg) { 6445 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 6446 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 6447 } 6448 6449 // If there's a mismatch between the abi-override in the package setting 6450 // and the abiOverride specified for the install. Warn about this because we 6451 // would've already compiled the app without taking the package setting into 6452 // account. 6453 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 6454 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 6455 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 6456 " for package: " + pkg.packageName); 6457 } 6458 } 6459 6460 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6461 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6462 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 6463 6464 // Copy the derived override back to the parsed package, so that we can 6465 // update the package settings accordingly. 6466 pkg.cpuAbiOverride = cpuAbiOverride; 6467 6468 if (DEBUG_ABI_SELECTION) { 6469 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 6470 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 6471 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 6472 } 6473 6474 // Push the derived path down into PackageSettings so we know what to 6475 // clean up at uninstall time. 6476 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 6477 6478 if (DEBUG_ABI_SELECTION) { 6479 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 6480 " primary=" + pkg.applicationInfo.primaryCpuAbi + 6481 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 6482 } 6483 6484 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 6485 // We don't do this here during boot because we can do it all 6486 // at once after scanning all existing packages. 6487 // 6488 // We also do this *before* we perform dexopt on this package, so that 6489 // we can avoid redundant dexopts, and also to make sure we've got the 6490 // code and package path correct. 6491 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 6492 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 6493 } 6494 6495 if ((scanFlags & SCAN_NO_DEX) == 0) { 6496 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */, 6497 forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */); 6498 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6499 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 6500 } 6501 } 6502 if (mFactoryTest && pkg.requestedPermissions.contains( 6503 android.Manifest.permission.FACTORY_TEST)) { 6504 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 6505 } 6506 6507 ArrayList<PackageParser.Package> clientLibPkgs = null; 6508 6509 // writer 6510 synchronized (mPackages) { 6511 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6512 // Only system apps can add new shared libraries. 6513 if (pkg.libraryNames != null) { 6514 for (int i=0; i<pkg.libraryNames.size(); i++) { 6515 String name = pkg.libraryNames.get(i); 6516 boolean allowed = false; 6517 if (pkg.isUpdatedSystemApp()) { 6518 // New library entries can only be added through the 6519 // system image. This is important to get rid of a lot 6520 // of nasty edge cases: for example if we allowed a non- 6521 // system update of the app to add a library, then uninstalling 6522 // the update would make the library go away, and assumptions 6523 // we made such as through app install filtering would now 6524 // have allowed apps on the device which aren't compatible 6525 // with it. Better to just have the restriction here, be 6526 // conservative, and create many fewer cases that can negatively 6527 // impact the user experience. 6528 final PackageSetting sysPs = mSettings 6529 .getDisabledSystemPkgLPr(pkg.packageName); 6530 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6531 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6532 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6533 allowed = true; 6534 allowed = true; 6535 break; 6536 } 6537 } 6538 } 6539 } else { 6540 allowed = true; 6541 } 6542 if (allowed) { 6543 if (!mSharedLibraries.containsKey(name)) { 6544 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6545 } else if (!name.equals(pkg.packageName)) { 6546 Slog.w(TAG, "Package " + pkg.packageName + " library " 6547 + name + " already exists; skipping"); 6548 } 6549 } else { 6550 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6551 + name + " that is not declared on system image; skipping"); 6552 } 6553 } 6554 if ((scanFlags&SCAN_BOOTING) == 0) { 6555 // If we are not booting, we need to update any applications 6556 // that are clients of our shared library. If we are booting, 6557 // this will all be done once the scan is complete. 6558 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6559 } 6560 } 6561 } 6562 } 6563 6564 // We also need to dexopt any apps that are dependent on this library. Note that 6565 // if these fail, we should abort the install since installing the library will 6566 // result in some apps being broken. 6567 if (clientLibPkgs != null) { 6568 if ((scanFlags & SCAN_NO_DEX) == 0) { 6569 for (int i = 0; i < clientLibPkgs.size(); i++) { 6570 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6571 int result = mPackageDexOptimizer.performDexOpt(clientPkg, 6572 null /* instruction sets */, forceDex, 6573 (scanFlags & SCAN_DEFER_DEX) != 0, false); 6574 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 6575 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6576 "scanPackageLI failed to dexopt clientLibPkgs"); 6577 } 6578 } 6579 } 6580 } 6581 6582 // Also need to kill any apps that are dependent on the library. 6583 if (clientLibPkgs != null) { 6584 for (int i=0; i<clientLibPkgs.size(); i++) { 6585 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6586 killApplication(clientPkg.applicationInfo.packageName, 6587 clientPkg.applicationInfo.uid, "update lib"); 6588 } 6589 } 6590 6591 // writer 6592 synchronized (mPackages) { 6593 // We don't expect installation to fail beyond this point 6594 6595 // Add the new setting to mSettings 6596 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6597 // Add the new setting to mPackages 6598 mPackages.put(pkg.applicationInfo.packageName, pkg); 6599 // Make sure we don't accidentally delete its data. 6600 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6601 while (iter.hasNext()) { 6602 PackageCleanItem item = iter.next(); 6603 if (pkgName.equals(item.packageName)) { 6604 iter.remove(); 6605 } 6606 } 6607 6608 // Take care of first install / last update times. 6609 if (currentTime != 0) { 6610 if (pkgSetting.firstInstallTime == 0) { 6611 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6612 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6613 pkgSetting.lastUpdateTime = currentTime; 6614 } 6615 } else if (pkgSetting.firstInstallTime == 0) { 6616 // We need *something*. Take time time stamp of the file. 6617 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6618 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6619 if (scanFileTime != pkgSetting.timeStamp) { 6620 // A package on the system image has changed; consider this 6621 // to be an update. 6622 pkgSetting.lastUpdateTime = scanFileTime; 6623 } 6624 } 6625 6626 // Add the package's KeySets to the global KeySetManagerService 6627 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6628 try { 6629 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6630 if (pkg.mKeySetMapping != null) { 6631 ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping); 6632 if (pkg.mUpgradeKeySets != null) { 6633 ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets); 6634 } 6635 } 6636 } catch (NullPointerException e) { 6637 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6638 } catch (IllegalArgumentException e) { 6639 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6640 } 6641 6642 int N = pkg.providers.size(); 6643 StringBuilder r = null; 6644 int i; 6645 for (i=0; i<N; i++) { 6646 PackageParser.Provider p = pkg.providers.get(i); 6647 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6648 p.info.processName, pkg.applicationInfo.uid); 6649 mProviders.addProvider(p); 6650 p.syncable = p.info.isSyncable; 6651 if (p.info.authority != null) { 6652 String names[] = p.info.authority.split(";"); 6653 p.info.authority = null; 6654 for (int j = 0; j < names.length; j++) { 6655 if (j == 1 && p.syncable) { 6656 // We only want the first authority for a provider to possibly be 6657 // syncable, so if we already added this provider using a different 6658 // authority clear the syncable flag. We copy the provider before 6659 // changing it because the mProviders object contains a reference 6660 // to a provider that we don't want to change. 6661 // Only do this for the second authority since the resulting provider 6662 // object can be the same for all future authorities for this provider. 6663 p = new PackageParser.Provider(p); 6664 p.syncable = false; 6665 } 6666 if (!mProvidersByAuthority.containsKey(names[j])) { 6667 mProvidersByAuthority.put(names[j], p); 6668 if (p.info.authority == null) { 6669 p.info.authority = names[j]; 6670 } else { 6671 p.info.authority = p.info.authority + ";" + names[j]; 6672 } 6673 if (DEBUG_PACKAGE_SCANNING) { 6674 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6675 Log.d(TAG, "Registered content provider: " + names[j] 6676 + ", className = " + p.info.name + ", isSyncable = " 6677 + p.info.isSyncable); 6678 } 6679 } else { 6680 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6681 Slog.w(TAG, "Skipping provider name " + names[j] + 6682 " (in package " + pkg.applicationInfo.packageName + 6683 "): name already used by " 6684 + ((other != null && other.getComponentName() != null) 6685 ? other.getComponentName().getPackageName() : "?")); 6686 } 6687 } 6688 } 6689 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6690 if (r == null) { 6691 r = new StringBuilder(256); 6692 } else { 6693 r.append(' '); 6694 } 6695 r.append(p.info.name); 6696 } 6697 } 6698 if (r != null) { 6699 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6700 } 6701 6702 N = pkg.services.size(); 6703 r = null; 6704 for (i=0; i<N; i++) { 6705 PackageParser.Service s = pkg.services.get(i); 6706 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6707 s.info.processName, pkg.applicationInfo.uid); 6708 mServices.addService(s); 6709 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6710 if (r == null) { 6711 r = new StringBuilder(256); 6712 } else { 6713 r.append(' '); 6714 } 6715 r.append(s.info.name); 6716 } 6717 } 6718 if (r != null) { 6719 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6720 } 6721 6722 N = pkg.receivers.size(); 6723 r = null; 6724 for (i=0; i<N; i++) { 6725 PackageParser.Activity a = pkg.receivers.get(i); 6726 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6727 a.info.processName, pkg.applicationInfo.uid); 6728 mReceivers.addActivity(a, "receiver"); 6729 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6730 if (r == null) { 6731 r = new StringBuilder(256); 6732 } else { 6733 r.append(' '); 6734 } 6735 r.append(a.info.name); 6736 } 6737 } 6738 if (r != null) { 6739 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6740 } 6741 6742 N = pkg.activities.size(); 6743 r = null; 6744 for (i=0; i<N; i++) { 6745 PackageParser.Activity a = pkg.activities.get(i); 6746 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6747 a.info.processName, pkg.applicationInfo.uid); 6748 mActivities.addActivity(a, "activity"); 6749 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6750 if (r == null) { 6751 r = new StringBuilder(256); 6752 } else { 6753 r.append(' '); 6754 } 6755 r.append(a.info.name); 6756 } 6757 } 6758 if (r != null) { 6759 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6760 } 6761 6762 N = pkg.permissionGroups.size(); 6763 r = null; 6764 for (i=0; i<N; i++) { 6765 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6766 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6767 if (cur == null) { 6768 mPermissionGroups.put(pg.info.name, pg); 6769 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6770 if (r == null) { 6771 r = new StringBuilder(256); 6772 } else { 6773 r.append(' '); 6774 } 6775 r.append(pg.info.name); 6776 } 6777 } else { 6778 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6779 + pg.info.packageName + " ignored: original from " 6780 + cur.info.packageName); 6781 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6782 if (r == null) { 6783 r = new StringBuilder(256); 6784 } else { 6785 r.append(' '); 6786 } 6787 r.append("DUP:"); 6788 r.append(pg.info.name); 6789 } 6790 } 6791 } 6792 if (r != null) { 6793 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6794 } 6795 6796 N = pkg.permissions.size(); 6797 r = null; 6798 for (i=0; i<N; i++) { 6799 PackageParser.Permission p = pkg.permissions.get(i); 6800 6801 // Now that permission groups have a special meaning, we ignore permission 6802 // groups for legacy apps to prevent unexpected behavior. In particular, 6803 // permissions for one app being granted to someone just becuase they happen 6804 // to be in a group defined by another app (before this had no implications). 6805 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 6806 p.group = mPermissionGroups.get(p.info.group); 6807 // Warn for a permission in an unknown group. 6808 if (p.info.group != null && p.group == null) { 6809 Slog.w(TAG, "Permission " + p.info.name + " from package " 6810 + p.info.packageName + " in an unknown group " + p.info.group); 6811 } 6812 } 6813 6814 ArrayMap<String, BasePermission> permissionMap = 6815 p.tree ? mSettings.mPermissionTrees 6816 : mSettings.mPermissions; 6817 BasePermission bp = permissionMap.get(p.info.name); 6818 6819 // Allow system apps to redefine non-system permissions 6820 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6821 final boolean currentOwnerIsSystem = (bp.perm != null 6822 && isSystemApp(bp.perm.owner)); 6823 if (isSystemApp(p.owner)) { 6824 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6825 // It's a built-in permission and no owner, take ownership now 6826 bp.packageSetting = pkgSetting; 6827 bp.perm = p; 6828 bp.uid = pkg.applicationInfo.uid; 6829 bp.sourcePackage = p.info.packageName; 6830 } else if (!currentOwnerIsSystem) { 6831 String msg = "New decl " + p.owner + " of permission " 6832 + p.info.name + " is system; overriding " + bp.sourcePackage; 6833 reportSettingsProblem(Log.WARN, msg); 6834 bp = null; 6835 } 6836 } 6837 } 6838 6839 if (bp == null) { 6840 bp = new BasePermission(p.info.name, p.info.packageName, 6841 BasePermission.TYPE_NORMAL); 6842 permissionMap.put(p.info.name, bp); 6843 } 6844 6845 if (bp.perm == null) { 6846 if (bp.sourcePackage == null 6847 || bp.sourcePackage.equals(p.info.packageName)) { 6848 BasePermission tree = findPermissionTreeLP(p.info.name); 6849 if (tree == null 6850 || tree.sourcePackage.equals(p.info.packageName)) { 6851 bp.packageSetting = pkgSetting; 6852 bp.perm = p; 6853 bp.uid = pkg.applicationInfo.uid; 6854 bp.sourcePackage = p.info.packageName; 6855 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6856 if (r == null) { 6857 r = new StringBuilder(256); 6858 } else { 6859 r.append(' '); 6860 } 6861 r.append(p.info.name); 6862 } 6863 } else { 6864 Slog.w(TAG, "Permission " + p.info.name + " from package " 6865 + p.info.packageName + " ignored: base tree " 6866 + tree.name + " is from package " 6867 + tree.sourcePackage); 6868 } 6869 } else { 6870 Slog.w(TAG, "Permission " + p.info.name + " from package " 6871 + p.info.packageName + " ignored: original from " 6872 + bp.sourcePackage); 6873 } 6874 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6875 if (r == null) { 6876 r = new StringBuilder(256); 6877 } else { 6878 r.append(' '); 6879 } 6880 r.append("DUP:"); 6881 r.append(p.info.name); 6882 } 6883 if (bp.perm == p) { 6884 bp.protectionLevel = p.info.protectionLevel; 6885 } 6886 } 6887 6888 if (r != null) { 6889 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6890 } 6891 6892 N = pkg.instrumentation.size(); 6893 r = null; 6894 for (i=0; i<N; i++) { 6895 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6896 a.info.packageName = pkg.applicationInfo.packageName; 6897 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6898 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6899 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6900 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6901 a.info.dataDir = pkg.applicationInfo.dataDir; 6902 6903 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6904 // need other information about the application, like the ABI and what not ? 6905 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6906 mInstrumentation.put(a.getComponentName(), a); 6907 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6908 if (r == null) { 6909 r = new StringBuilder(256); 6910 } else { 6911 r.append(' '); 6912 } 6913 r.append(a.info.name); 6914 } 6915 } 6916 if (r != null) { 6917 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6918 } 6919 6920 if (pkg.protectedBroadcasts != null) { 6921 N = pkg.protectedBroadcasts.size(); 6922 for (i=0; i<N; i++) { 6923 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6924 } 6925 } 6926 6927 pkgSetting.setTimeStamp(scanFileTime); 6928 6929 // Create idmap files for pairs of (packages, overlay packages). 6930 // Note: "android", ie framework-res.apk, is handled by native layers. 6931 if (pkg.mOverlayTarget != null) { 6932 // This is an overlay package. 6933 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6934 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6935 mOverlays.put(pkg.mOverlayTarget, 6936 new ArrayMap<String, PackageParser.Package>()); 6937 } 6938 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6939 map.put(pkg.packageName, pkg); 6940 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6941 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6942 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6943 "scanPackageLI failed to createIdmap"); 6944 } 6945 } 6946 } else if (mOverlays.containsKey(pkg.packageName) && 6947 !pkg.packageName.equals("android")) { 6948 // This is a regular package, with one or more known overlay packages. 6949 createIdmapsForPackageLI(pkg); 6950 } 6951 } 6952 6953 return pkg; 6954 } 6955 6956 /** 6957 * Derive the ABI of a non-system package located at {@code scanFile}. This information 6958 * is derived purely on the basis of the contents of {@code scanFile} and 6959 * {@code cpuAbiOverride}. 6960 * 6961 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 6962 */ 6963 public void derivePackageAbi(PackageParser.Package pkg, File scanFile, 6964 String cpuAbiOverride, boolean extractLibs) 6965 throws PackageManagerException { 6966 // TODO: We can probably be smarter about this stuff. For installed apps, 6967 // we can calculate this information at install time once and for all. For 6968 // system apps, we can probably assume that this information doesn't change 6969 // after the first boot scan. As things stand, we do lots of unnecessary work. 6970 6971 // Give ourselves some initial paths; we'll come back for another 6972 // pass once we've determined ABI below. 6973 setNativeLibraryPaths(pkg); 6974 6975 // We would never need to extract libs for forward-locked and external packages, 6976 // since the container service will do it for us. We shouldn't attempt to 6977 // extract libs from system app when it was not updated. 6978 if (pkg.isForwardLocked() || isExternal(pkg) || 6979 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) { 6980 extractLibs = false; 6981 } 6982 6983 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 6984 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 6985 6986 NativeLibraryHelper.Handle handle = null; 6987 try { 6988 handle = NativeLibraryHelper.Handle.create(scanFile); 6989 // TODO(multiArch): This can be null for apps that didn't go through the 6990 // usual installation process. We can calculate it again, like we 6991 // do during install time. 6992 // 6993 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 6994 // unnecessary. 6995 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 6996 6997 // Null out the abis so that they can be recalculated. 6998 pkg.applicationInfo.primaryCpuAbi = null; 6999 pkg.applicationInfo.secondaryCpuAbi = null; 7000 if (isMultiArch(pkg.applicationInfo)) { 7001 // Warn if we've set an abiOverride for multi-lib packages.. 7002 // By definition, we need to copy both 32 and 64 bit libraries for 7003 // such packages. 7004 if (pkg.cpuAbiOverride != null 7005 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 7006 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 7007 } 7008 7009 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 7010 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 7011 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 7012 if (extractLibs) { 7013 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7014 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 7015 useIsaSpecificSubdirs); 7016 } else { 7017 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 7018 } 7019 } 7020 7021 maybeThrowExceptionForMultiArchCopy( 7022 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 7023 7024 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 7025 if (extractLibs) { 7026 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7027 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 7028 useIsaSpecificSubdirs); 7029 } else { 7030 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 7031 } 7032 } 7033 7034 maybeThrowExceptionForMultiArchCopy( 7035 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 7036 7037 if (abi64 >= 0) { 7038 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 7039 } 7040 7041 if (abi32 >= 0) { 7042 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 7043 if (abi64 >= 0) { 7044 pkg.applicationInfo.secondaryCpuAbi = abi; 7045 } else { 7046 pkg.applicationInfo.primaryCpuAbi = abi; 7047 } 7048 } 7049 } else { 7050 String[] abiList = (cpuAbiOverride != null) ? 7051 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 7052 7053 // Enable gross and lame hacks for apps that are built with old 7054 // SDK tools. We must scan their APKs for renderscript bitcode and 7055 // not launch them if it's present. Don't bother checking on devices 7056 // that don't have 64 bit support. 7057 boolean needsRenderScriptOverride = false; 7058 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 7059 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 7060 abiList = Build.SUPPORTED_32_BIT_ABIS; 7061 needsRenderScriptOverride = true; 7062 } 7063 7064 final int copyRet; 7065 if (extractLibs) { 7066 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 7067 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 7068 } else { 7069 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 7070 } 7071 7072 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 7073 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 7074 "Error unpackaging native libs for app, errorCode=" + copyRet); 7075 } 7076 7077 if (copyRet >= 0) { 7078 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 7079 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 7080 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 7081 } else if (needsRenderScriptOverride) { 7082 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 7083 } 7084 } 7085 } catch (IOException ioe) { 7086 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 7087 } finally { 7088 IoUtils.closeQuietly(handle); 7089 } 7090 7091 // Now that we've calculated the ABIs and determined if it's an internal app, 7092 // we will go ahead and populate the nativeLibraryPath. 7093 setNativeLibraryPaths(pkg); 7094 } 7095 7096 /** 7097 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 7098 * i.e, so that all packages can be run inside a single process if required. 7099 * 7100 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 7101 * this function will either try and make the ABI for all packages in {@code packagesForUser} 7102 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 7103 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 7104 * updating a package that belongs to a shared user. 7105 * 7106 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 7107 * adds unnecessary complexity. 7108 */ 7109 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 7110 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 7111 String requiredInstructionSet = null; 7112 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 7113 requiredInstructionSet = VMRuntime.getInstructionSet( 7114 scannedPackage.applicationInfo.primaryCpuAbi); 7115 } 7116 7117 PackageSetting requirer = null; 7118 for (PackageSetting ps : packagesForUser) { 7119 // If packagesForUser contains scannedPackage, we skip it. This will happen 7120 // when scannedPackage is an update of an existing package. Without this check, 7121 // we will never be able to change the ABI of any package belonging to a shared 7122 // user, even if it's compatible with other packages. 7123 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7124 if (ps.primaryCpuAbiString == null) { 7125 continue; 7126 } 7127 7128 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 7129 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 7130 // We have a mismatch between instruction sets (say arm vs arm64) warn about 7131 // this but there's not much we can do. 7132 String errorMessage = "Instruction set mismatch, " 7133 + ((requirer == null) ? "[caller]" : requirer) 7134 + " requires " + requiredInstructionSet + " whereas " + ps 7135 + " requires " + instructionSet; 7136 Slog.w(TAG, errorMessage); 7137 } 7138 7139 if (requiredInstructionSet == null) { 7140 requiredInstructionSet = instructionSet; 7141 requirer = ps; 7142 } 7143 } 7144 } 7145 7146 if (requiredInstructionSet != null) { 7147 String adjustedAbi; 7148 if (requirer != null) { 7149 // requirer != null implies that either scannedPackage was null or that scannedPackage 7150 // did not require an ABI, in which case we have to adjust scannedPackage to match 7151 // the ABI of the set (which is the same as requirer's ABI) 7152 adjustedAbi = requirer.primaryCpuAbiString; 7153 if (scannedPackage != null) { 7154 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 7155 } 7156 } else { 7157 // requirer == null implies that we're updating all ABIs in the set to 7158 // match scannedPackage. 7159 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 7160 } 7161 7162 for (PackageSetting ps : packagesForUser) { 7163 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 7164 if (ps.primaryCpuAbiString != null) { 7165 continue; 7166 } 7167 7168 ps.primaryCpuAbiString = adjustedAbi; 7169 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7170 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 7171 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 7172 7173 int result = mPackageDexOptimizer.performDexOpt(ps.pkg, 7174 null /* instruction sets */, forceDexOpt, deferDexOpt, true); 7175 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 7176 ps.primaryCpuAbiString = null; 7177 ps.pkg.applicationInfo.primaryCpuAbi = null; 7178 return; 7179 } else { 7180 mInstaller.rmdex(ps.codePathString, 7181 getDexCodeInstructionSet(getPreferredInstructionSet())); 7182 } 7183 } 7184 } 7185 } 7186 } 7187 } 7188 7189 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 7190 synchronized (mPackages) { 7191 mResolverReplaced = true; 7192 // Set up information for custom user intent resolution activity. 7193 mResolveActivity.applicationInfo = pkg.applicationInfo; 7194 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7195 mResolveActivity.packageName = pkg.applicationInfo.packageName; 7196 mResolveActivity.processName = pkg.applicationInfo.packageName; 7197 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7198 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 7199 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 7200 mResolveActivity.theme = 0; 7201 mResolveActivity.exported = true; 7202 mResolveActivity.enabled = true; 7203 mResolveInfo.activityInfo = mResolveActivity; 7204 mResolveInfo.priority = 0; 7205 mResolveInfo.preferredOrder = 0; 7206 mResolveInfo.match = 0; 7207 mResolveComponentName = mCustomResolverComponentName; 7208 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 7209 mResolveComponentName); 7210 } 7211 } 7212 7213 private static String calculateBundledApkRoot(final String codePathString) { 7214 final File codePath = new File(codePathString); 7215 final File codeRoot; 7216 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 7217 codeRoot = Environment.getRootDirectory(); 7218 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 7219 codeRoot = Environment.getOemDirectory(); 7220 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 7221 codeRoot = Environment.getVendorDirectory(); 7222 } else { 7223 // Unrecognized code path; take its top real segment as the apk root: 7224 // e.g. /something/app/blah.apk => /something 7225 try { 7226 File f = codePath.getCanonicalFile(); 7227 File parent = f.getParentFile(); // non-null because codePath is a file 7228 File tmp; 7229 while ((tmp = parent.getParentFile()) != null) { 7230 f = parent; 7231 parent = tmp; 7232 } 7233 codeRoot = f; 7234 Slog.w(TAG, "Unrecognized code path " 7235 + codePath + " - using " + codeRoot); 7236 } catch (IOException e) { 7237 // Can't canonicalize the code path -- shenanigans? 7238 Slog.w(TAG, "Can't canonicalize code path " + codePath); 7239 return Environment.getRootDirectory().getPath(); 7240 } 7241 } 7242 return codeRoot.getPath(); 7243 } 7244 7245 /** 7246 * Derive and set the location of native libraries for the given package, 7247 * which varies depending on where and how the package was installed. 7248 */ 7249 private void setNativeLibraryPaths(PackageParser.Package pkg) { 7250 final ApplicationInfo info = pkg.applicationInfo; 7251 final String codePath = pkg.codePath; 7252 final File codeFile = new File(codePath); 7253 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 7254 final boolean asecApp = info.isForwardLocked() || isExternal(info); 7255 7256 info.nativeLibraryRootDir = null; 7257 info.nativeLibraryRootRequiresIsa = false; 7258 info.nativeLibraryDir = null; 7259 info.secondaryNativeLibraryDir = null; 7260 7261 if (isApkFile(codeFile)) { 7262 // Monolithic install 7263 if (bundledApp) { 7264 // If "/system/lib64/apkname" exists, assume that is the per-package 7265 // native library directory to use; otherwise use "/system/lib/apkname". 7266 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 7267 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 7268 getPrimaryInstructionSet(info)); 7269 7270 // This is a bundled system app so choose the path based on the ABI. 7271 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 7272 // is just the default path. 7273 final String apkName = deriveCodePathName(codePath); 7274 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 7275 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 7276 apkName).getAbsolutePath(); 7277 7278 if (info.secondaryCpuAbi != null) { 7279 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 7280 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 7281 secondaryLibDir, apkName).getAbsolutePath(); 7282 } 7283 } else if (asecApp) { 7284 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 7285 .getAbsolutePath(); 7286 } else { 7287 final String apkName = deriveCodePathName(codePath); 7288 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 7289 .getAbsolutePath(); 7290 } 7291 7292 info.nativeLibraryRootRequiresIsa = false; 7293 info.nativeLibraryDir = info.nativeLibraryRootDir; 7294 } else { 7295 // Cluster install 7296 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 7297 info.nativeLibraryRootRequiresIsa = true; 7298 7299 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 7300 getPrimaryInstructionSet(info)).getAbsolutePath(); 7301 7302 if (info.secondaryCpuAbi != null) { 7303 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 7304 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 7305 } 7306 } 7307 } 7308 7309 /** 7310 * Calculate the abis and roots for a bundled app. These can uniquely 7311 * be determined from the contents of the system partition, i.e whether 7312 * it contains 64 or 32 bit shared libraries etc. We do not validate any 7313 * of this information, and instead assume that the system was built 7314 * sensibly. 7315 */ 7316 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 7317 PackageSetting pkgSetting) { 7318 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 7319 7320 // If "/system/lib64/apkname" exists, assume that is the per-package 7321 // native library directory to use; otherwise use "/system/lib/apkname". 7322 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 7323 setBundledAppAbi(pkg, apkRoot, apkName); 7324 // pkgSetting might be null during rescan following uninstall of updates 7325 // to a bundled app, so accommodate that possibility. The settings in 7326 // that case will be established later from the parsed package. 7327 // 7328 // If the settings aren't null, sync them up with what we've just derived. 7329 // note that apkRoot isn't stored in the package settings. 7330 if (pkgSetting != null) { 7331 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 7332 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 7333 } 7334 } 7335 7336 /** 7337 * Deduces the ABI of a bundled app and sets the relevant fields on the 7338 * parsed pkg object. 7339 * 7340 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 7341 * under which system libraries are installed. 7342 * @param apkName the name of the installed package. 7343 */ 7344 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 7345 final File codeFile = new File(pkg.codePath); 7346 7347 final boolean has64BitLibs; 7348 final boolean has32BitLibs; 7349 if (isApkFile(codeFile)) { 7350 // Monolithic install 7351 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 7352 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 7353 } else { 7354 // Cluster install 7355 final File rootDir = new File(codeFile, LIB_DIR_NAME); 7356 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 7357 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 7358 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 7359 has64BitLibs = (new File(rootDir, isa)).exists(); 7360 } else { 7361 has64BitLibs = false; 7362 } 7363 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 7364 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 7365 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 7366 has32BitLibs = (new File(rootDir, isa)).exists(); 7367 } else { 7368 has32BitLibs = false; 7369 } 7370 } 7371 7372 if (has64BitLibs && !has32BitLibs) { 7373 // The package has 64 bit libs, but not 32 bit libs. Its primary 7374 // ABI should be 64 bit. We can safely assume here that the bundled 7375 // native libraries correspond to the most preferred ABI in the list. 7376 7377 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7378 pkg.applicationInfo.secondaryCpuAbi = null; 7379 } else if (has32BitLibs && !has64BitLibs) { 7380 // The package has 32 bit libs but not 64 bit libs. Its primary 7381 // ABI should be 32 bit. 7382 7383 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7384 pkg.applicationInfo.secondaryCpuAbi = null; 7385 } else if (has32BitLibs && has64BitLibs) { 7386 // The application has both 64 and 32 bit bundled libraries. We check 7387 // here that the app declares multiArch support, and warn if it doesn't. 7388 // 7389 // We will be lenient here and record both ABIs. The primary will be the 7390 // ABI that's higher on the list, i.e, a device that's configured to prefer 7391 // 64 bit apps will see a 64 bit primary ABI, 7392 7393 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 7394 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 7395 } 7396 7397 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 7398 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7399 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7400 } else { 7401 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 7402 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 7403 } 7404 } else { 7405 pkg.applicationInfo.primaryCpuAbi = null; 7406 pkg.applicationInfo.secondaryCpuAbi = null; 7407 } 7408 } 7409 7410 private void killApplication(String pkgName, int appId, String reason) { 7411 // Request the ActivityManager to kill the process(only for existing packages) 7412 // so that we do not end up in a confused state while the user is still using the older 7413 // version of the application while the new one gets installed. 7414 IActivityManager am = ActivityManagerNative.getDefault(); 7415 if (am != null) { 7416 try { 7417 am.killApplicationWithAppId(pkgName, appId, reason); 7418 } catch (RemoteException e) { 7419 } 7420 } 7421 } 7422 7423 void removePackageLI(PackageSetting ps, boolean chatty) { 7424 if (DEBUG_INSTALL) { 7425 if (chatty) 7426 Log.d(TAG, "Removing package " + ps.name); 7427 } 7428 7429 // writer 7430 synchronized (mPackages) { 7431 mPackages.remove(ps.name); 7432 final PackageParser.Package pkg = ps.pkg; 7433 if (pkg != null) { 7434 cleanPackageDataStructuresLILPw(pkg, chatty); 7435 } 7436 } 7437 } 7438 7439 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 7440 if (DEBUG_INSTALL) { 7441 if (chatty) 7442 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 7443 } 7444 7445 // writer 7446 synchronized (mPackages) { 7447 mPackages.remove(pkg.applicationInfo.packageName); 7448 cleanPackageDataStructuresLILPw(pkg, chatty); 7449 } 7450 } 7451 7452 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 7453 int N = pkg.providers.size(); 7454 StringBuilder r = null; 7455 int i; 7456 for (i=0; i<N; i++) { 7457 PackageParser.Provider p = pkg.providers.get(i); 7458 mProviders.removeProvider(p); 7459 if (p.info.authority == null) { 7460 7461 /* There was another ContentProvider with this authority when 7462 * this app was installed so this authority is null, 7463 * Ignore it as we don't have to unregister the provider. 7464 */ 7465 continue; 7466 } 7467 String names[] = p.info.authority.split(";"); 7468 for (int j = 0; j < names.length; j++) { 7469 if (mProvidersByAuthority.get(names[j]) == p) { 7470 mProvidersByAuthority.remove(names[j]); 7471 if (DEBUG_REMOVE) { 7472 if (chatty) 7473 Log.d(TAG, "Unregistered content provider: " + names[j] 7474 + ", className = " + p.info.name + ", isSyncable = " 7475 + p.info.isSyncable); 7476 } 7477 } 7478 } 7479 if (DEBUG_REMOVE && chatty) { 7480 if (r == null) { 7481 r = new StringBuilder(256); 7482 } else { 7483 r.append(' '); 7484 } 7485 r.append(p.info.name); 7486 } 7487 } 7488 if (r != null) { 7489 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 7490 } 7491 7492 N = pkg.services.size(); 7493 r = null; 7494 for (i=0; i<N; i++) { 7495 PackageParser.Service s = pkg.services.get(i); 7496 mServices.removeService(s); 7497 if (chatty) { 7498 if (r == null) { 7499 r = new StringBuilder(256); 7500 } else { 7501 r.append(' '); 7502 } 7503 r.append(s.info.name); 7504 } 7505 } 7506 if (r != null) { 7507 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 7508 } 7509 7510 N = pkg.receivers.size(); 7511 r = null; 7512 for (i=0; i<N; i++) { 7513 PackageParser.Activity a = pkg.receivers.get(i); 7514 mReceivers.removeActivity(a, "receiver"); 7515 if (DEBUG_REMOVE && chatty) { 7516 if (r == null) { 7517 r = new StringBuilder(256); 7518 } else { 7519 r.append(' '); 7520 } 7521 r.append(a.info.name); 7522 } 7523 } 7524 if (r != null) { 7525 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 7526 } 7527 7528 N = pkg.activities.size(); 7529 r = null; 7530 for (i=0; i<N; i++) { 7531 PackageParser.Activity a = pkg.activities.get(i); 7532 mActivities.removeActivity(a, "activity"); 7533 if (DEBUG_REMOVE && chatty) { 7534 if (r == null) { 7535 r = new StringBuilder(256); 7536 } else { 7537 r.append(' '); 7538 } 7539 r.append(a.info.name); 7540 } 7541 } 7542 if (r != null) { 7543 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 7544 } 7545 7546 N = pkg.permissions.size(); 7547 r = null; 7548 for (i=0; i<N; i++) { 7549 PackageParser.Permission p = pkg.permissions.get(i); 7550 BasePermission bp = mSettings.mPermissions.get(p.info.name); 7551 if (bp == null) { 7552 bp = mSettings.mPermissionTrees.get(p.info.name); 7553 } 7554 if (bp != null && bp.perm == p) { 7555 bp.perm = null; 7556 if (DEBUG_REMOVE && chatty) { 7557 if (r == null) { 7558 r = new StringBuilder(256); 7559 } else { 7560 r.append(' '); 7561 } 7562 r.append(p.info.name); 7563 } 7564 } 7565 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7566 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 7567 if (appOpPerms != null) { 7568 appOpPerms.remove(pkg.packageName); 7569 } 7570 } 7571 } 7572 if (r != null) { 7573 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7574 } 7575 7576 N = pkg.requestedPermissions.size(); 7577 r = null; 7578 for (i=0; i<N; i++) { 7579 String perm = pkg.requestedPermissions.get(i); 7580 BasePermission bp = mSettings.mPermissions.get(perm); 7581 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7582 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 7583 if (appOpPerms != null) { 7584 appOpPerms.remove(pkg.packageName); 7585 if (appOpPerms.isEmpty()) { 7586 mAppOpPermissionPackages.remove(perm); 7587 } 7588 } 7589 } 7590 } 7591 if (r != null) { 7592 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 7593 } 7594 7595 N = pkg.instrumentation.size(); 7596 r = null; 7597 for (i=0; i<N; i++) { 7598 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 7599 mInstrumentation.remove(a.getComponentName()); 7600 if (DEBUG_REMOVE && chatty) { 7601 if (r == null) { 7602 r = new StringBuilder(256); 7603 } else { 7604 r.append(' '); 7605 } 7606 r.append(a.info.name); 7607 } 7608 } 7609 if (r != null) { 7610 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 7611 } 7612 7613 r = null; 7614 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 7615 // Only system apps can hold shared libraries. 7616 if (pkg.libraryNames != null) { 7617 for (i=0; i<pkg.libraryNames.size(); i++) { 7618 String name = pkg.libraryNames.get(i); 7619 SharedLibraryEntry cur = mSharedLibraries.get(name); 7620 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 7621 mSharedLibraries.remove(name); 7622 if (DEBUG_REMOVE && chatty) { 7623 if (r == null) { 7624 r = new StringBuilder(256); 7625 } else { 7626 r.append(' '); 7627 } 7628 r.append(name); 7629 } 7630 } 7631 } 7632 } 7633 } 7634 if (r != null) { 7635 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 7636 } 7637 } 7638 7639 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 7640 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 7641 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 7642 return true; 7643 } 7644 } 7645 return false; 7646 } 7647 7648 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 7649 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 7650 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 7651 7652 private void updatePermissionsLPw(String changingPkg, 7653 PackageParser.Package pkgInfo, int flags) { 7654 // Make sure there are no dangling permission trees. 7655 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 7656 while (it.hasNext()) { 7657 final BasePermission bp = it.next(); 7658 if (bp.packageSetting == null) { 7659 // We may not yet have parsed the package, so just see if 7660 // we still know about its settings. 7661 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7662 } 7663 if (bp.packageSetting == null) { 7664 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7665 + " from package " + bp.sourcePackage); 7666 it.remove(); 7667 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7668 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7669 Slog.i(TAG, "Removing old permission tree: " + bp.name 7670 + " from package " + bp.sourcePackage); 7671 flags |= UPDATE_PERMISSIONS_ALL; 7672 it.remove(); 7673 } 7674 } 7675 } 7676 7677 // Make sure all dynamic permissions have been assigned to a package, 7678 // and make sure there are no dangling permissions. 7679 it = mSettings.mPermissions.values().iterator(); 7680 while (it.hasNext()) { 7681 final BasePermission bp = it.next(); 7682 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7683 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7684 + bp.name + " pkg=" + bp.sourcePackage 7685 + " info=" + bp.pendingInfo); 7686 if (bp.packageSetting == null && bp.pendingInfo != null) { 7687 final BasePermission tree = findPermissionTreeLP(bp.name); 7688 if (tree != null && tree.perm != null) { 7689 bp.packageSetting = tree.packageSetting; 7690 bp.perm = new PackageParser.Permission(tree.perm.owner, 7691 new PermissionInfo(bp.pendingInfo)); 7692 bp.perm.info.packageName = tree.perm.info.packageName; 7693 bp.perm.info.name = bp.name; 7694 bp.uid = tree.uid; 7695 } 7696 } 7697 } 7698 if (bp.packageSetting == null) { 7699 // We may not yet have parsed the package, so just see if 7700 // we still know about its settings. 7701 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7702 } 7703 if (bp.packageSetting == null) { 7704 Slog.w(TAG, "Removing dangling permission: " + bp.name 7705 + " from package " + bp.sourcePackage); 7706 it.remove(); 7707 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7708 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7709 Slog.i(TAG, "Removing old permission: " + bp.name 7710 + " from package " + bp.sourcePackage); 7711 flags |= UPDATE_PERMISSIONS_ALL; 7712 it.remove(); 7713 } 7714 } 7715 } 7716 7717 // Now update the permissions for all packages, in particular 7718 // replace the granted permissions of the system packages. 7719 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7720 for (PackageParser.Package pkg : mPackages.values()) { 7721 if (pkg != pkgInfo) { 7722 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7723 changingPkg); 7724 } 7725 } 7726 } 7727 7728 if (pkgInfo != null) { 7729 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7730 } 7731 } 7732 7733 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7734 String packageOfInterest) { 7735 // IMPORTANT: There are two types of permissions: install and runtime. 7736 // Install time permissions are granted when the app is installed to 7737 // all device users and users added in the future. Runtime permissions 7738 // are granted at runtime explicitly to specific users. Normal and signature 7739 // protected permissions are install time permissions. Dangerous permissions 7740 // are install permissions if the app's target SDK is Lollipop MR1 or older, 7741 // otherwise they are runtime permissions. This function does not manage 7742 // runtime permissions except for the case an app targeting Lollipop MR1 7743 // being upgraded to target a newer SDK, in which case dangerous permissions 7744 // are transformed from install time to runtime ones. 7745 7746 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7747 if (ps == null) { 7748 return; 7749 } 7750 7751 PermissionsState permissionsState = ps.getPermissionsState(); 7752 PermissionsState origPermissions = permissionsState; 7753 7754 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 7755 7756 int[] upgradeUserIds = EMPTY_INT_ARRAY; 7757 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 7758 7759 boolean changedInstallPermission = false; 7760 7761 if (replace) { 7762 ps.installPermissionsFixed = false; 7763 if (!ps.isSharedUser()) { 7764 origPermissions = new PermissionsState(permissionsState); 7765 permissionsState.reset(); 7766 } 7767 } 7768 7769 permissionsState.setGlobalGids(mGlobalGids); 7770 7771 final int N = pkg.requestedPermissions.size(); 7772 for (int i=0; i<N; i++) { 7773 final String name = pkg.requestedPermissions.get(i); 7774 final BasePermission bp = mSettings.mPermissions.get(name); 7775 7776 if (DEBUG_INSTALL) { 7777 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7778 } 7779 7780 if (bp == null || bp.packageSetting == null) { 7781 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7782 Slog.w(TAG, "Unknown permission " + name 7783 + " in package " + pkg.packageName); 7784 } 7785 continue; 7786 } 7787 7788 final String perm = bp.name; 7789 boolean allowedSig = false; 7790 int grant = GRANT_DENIED; 7791 7792 // Keep track of app op permissions. 7793 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7794 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7795 if (pkgs == null) { 7796 pkgs = new ArraySet<>(); 7797 mAppOpPermissionPackages.put(bp.name, pkgs); 7798 } 7799 pkgs.add(pkg.packageName); 7800 } 7801 7802 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7803 switch (level) { 7804 case PermissionInfo.PROTECTION_NORMAL: { 7805 // For all apps normal permissions are install time ones. 7806 grant = GRANT_INSTALL; 7807 } break; 7808 7809 case PermissionInfo.PROTECTION_DANGEROUS: { 7810 if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) { 7811 // For legacy apps dangerous permissions are install time ones. 7812 grant = GRANT_INSTALL_LEGACY; 7813 } else if (ps.isSystem()) { 7814 final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds(); 7815 if (origPermissions.hasInstallPermission(bp.name)) { 7816 // If a system app had an install permission, then the app was 7817 // upgraded and we grant the permissions as runtime to all users. 7818 grant = GRANT_UPGRADE; 7819 upgradeUserIds = currentUserIds; 7820 } else if (!Arrays.equals(updatedUserIds, currentUserIds)) { 7821 // If users changed since the last permissions update for a 7822 // system app, we grant the permission as runtime to the new users. 7823 grant = GRANT_UPGRADE; 7824 upgradeUserIds = currentUserIds; 7825 for (int userId : updatedUserIds) { 7826 upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId); 7827 } 7828 } else { 7829 // Otherwise, we grant the permission as runtime if the app 7830 // already had it, i.e. we preserve runtime permissions. 7831 grant = GRANT_RUNTIME; 7832 } 7833 } else if (origPermissions.hasInstallPermission(bp.name)) { 7834 // For legacy apps that became modern, install becomes runtime. 7835 grant = GRANT_UPGRADE; 7836 upgradeUserIds = currentUserIds; 7837 } else if (replace) { 7838 // For upgraded modern apps keep runtime permissions unchanged. 7839 grant = GRANT_RUNTIME; 7840 } 7841 } break; 7842 7843 case PermissionInfo.PROTECTION_SIGNATURE: { 7844 // For all apps signature permissions are install time ones. 7845 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 7846 if (allowedSig) { 7847 grant = GRANT_INSTALL; 7848 } 7849 } break; 7850 } 7851 7852 if (DEBUG_INSTALL) { 7853 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7854 } 7855 7856 if (grant != GRANT_DENIED) { 7857 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 7858 // If this is an existing, non-system package, then 7859 // we can't add any new permissions to it. 7860 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 7861 // Except... if this is a permission that was added 7862 // to the platform (note: need to only do this when 7863 // updating the platform). 7864 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 7865 grant = GRANT_DENIED; 7866 } 7867 } 7868 } 7869 7870 switch (grant) { 7871 case GRANT_INSTALL: { 7872 // Revoke this as runtime permission to handle the case of 7873 // a runtime permssion being downgraded to an install one. 7874 for (int userId : UserManagerService.getInstance().getUserIds()) { 7875 if (origPermissions.getRuntimePermissionState( 7876 bp.name, userId) != null) { 7877 // Revoke the runtime permission and clear the flags. 7878 origPermissions.revokeRuntimePermission(bp, userId); 7879 origPermissions.updatePermissionFlags(bp, userId, 7880 PackageManager.MASK_PERMISSION_FLAGS, 0); 7881 // If we revoked a permission permission, we have to write. 7882 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7883 changedRuntimePermissionUserIds, userId); 7884 } 7885 } 7886 // Grant an install permission. 7887 if (permissionsState.grantInstallPermission(bp) != 7888 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7889 changedInstallPermission = true; 7890 } 7891 } break; 7892 7893 case GRANT_INSTALL_LEGACY: { 7894 // Grant an install permission. 7895 if (permissionsState.grantInstallPermission(bp) != 7896 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7897 changedInstallPermission = true; 7898 } 7899 } break; 7900 7901 case GRANT_RUNTIME: { 7902 // Grant previously granted runtime permissions. 7903 for (int userId : UserManagerService.getInstance().getUserIds()) { 7904 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 7905 PermissionState permissionState = origPermissions 7906 .getRuntimePermissionState(bp.name, userId); 7907 final int flags = permissionState.getFlags(); 7908 if (permissionsState.grantRuntimePermission(bp, userId) == 7909 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7910 // If we cannot put the permission as it was, we have to write. 7911 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7912 changedRuntimePermissionUserIds, userId); 7913 } else { 7914 // System components not only get the permissions but 7915 // they are also fixed, so nothing can change that. 7916 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7917 ? flags 7918 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7919 // Propagate the permission flags. 7920 permissionsState.updatePermissionFlags(bp, userId, 7921 newFlags, newFlags); 7922 } 7923 } 7924 } 7925 } break; 7926 7927 case GRANT_UPGRADE: { 7928 // Grant runtime permissions for a previously held install permission. 7929 PermissionState permissionState = origPermissions 7930 .getInstallPermissionState(bp.name); 7931 final int flags = permissionState != null ? permissionState.getFlags() : 0; 7932 7933 origPermissions.revokeInstallPermission(bp); 7934 // We will be transferring the permission flags, so clear them. 7935 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 7936 PackageManager.MASK_PERMISSION_FLAGS, 0); 7937 7938 // If the permission is not to be promoted to runtime we ignore it and 7939 // also its other flags as they are not applicable to install permissions. 7940 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 7941 for (int userId : upgradeUserIds) { 7942 if (permissionsState.grantRuntimePermission(bp, userId) != 7943 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7944 // System components not only get the permissions but 7945 // they are also fixed so nothing can change that. 7946 final int newFlags = !isSystemComponentOrPersistentPrivApp(pkg) 7947 ? flags 7948 : flags | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 7949 // Transfer the permission flags. 7950 permissionsState.updatePermissionFlags(bp, userId, 7951 newFlags, newFlags); 7952 // If we granted the permission, we have to write. 7953 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 7954 changedRuntimePermissionUserIds, userId); 7955 } 7956 } 7957 } 7958 } break; 7959 7960 default: { 7961 if (packageOfInterest == null 7962 || packageOfInterest.equals(pkg.packageName)) { 7963 Slog.w(TAG, "Not granting permission " + perm 7964 + " to package " + pkg.packageName 7965 + " because it was previously installed without"); 7966 } 7967 } break; 7968 } 7969 } else { 7970 if (permissionsState.revokeInstallPermission(bp) != 7971 PermissionsState.PERMISSION_OPERATION_FAILURE) { 7972 // Also drop the permission flags. 7973 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 7974 PackageManager.MASK_PERMISSION_FLAGS, 0); 7975 changedInstallPermission = true; 7976 Slog.i(TAG, "Un-granting permission " + perm 7977 + " from package " + pkg.packageName 7978 + " (protectionLevel=" + bp.protectionLevel 7979 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7980 + ")"); 7981 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7982 // Don't print warning for app op permissions, since it is fine for them 7983 // not to be granted, there is a UI for the user to decide. 7984 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7985 Slog.w(TAG, "Not granting permission " + perm 7986 + " to package " + pkg.packageName 7987 + " (protectionLevel=" + bp.protectionLevel 7988 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7989 + ")"); 7990 } 7991 } 7992 } 7993 } 7994 7995 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 7996 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7997 // This is the first that we have heard about this package, so the 7998 // permissions we have now selected are fixed until explicitly 7999 // changed. 8000 ps.installPermissionsFixed = true; 8001 } 8002 8003 ps.setPermissionsUpdatedForUserIds(currentUserIds); 8004 8005 // Persist the runtime permissions state for users with changes. 8006 for (int userId : changedRuntimePermissionUserIds) { 8007 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 8008 } 8009 } 8010 8011 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 8012 boolean allowed = false; 8013 final int NP = PackageParser.NEW_PERMISSIONS.length; 8014 for (int ip=0; ip<NP; ip++) { 8015 final PackageParser.NewPermissionInfo npi 8016 = PackageParser.NEW_PERMISSIONS[ip]; 8017 if (npi.name.equals(perm) 8018 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 8019 allowed = true; 8020 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 8021 + pkg.packageName); 8022 break; 8023 } 8024 } 8025 return allowed; 8026 } 8027 8028 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 8029 BasePermission bp, PermissionsState origPermissions) { 8030 boolean allowed; 8031 allowed = (compareSignatures( 8032 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 8033 == PackageManager.SIGNATURE_MATCH) 8034 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 8035 == PackageManager.SIGNATURE_MATCH); 8036 if (!allowed && (bp.protectionLevel 8037 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 8038 if (isSystemApp(pkg)) { 8039 // For updated system applications, a system permission 8040 // is granted only if it had been defined by the original application. 8041 if (pkg.isUpdatedSystemApp()) { 8042 final PackageSetting sysPs = mSettings 8043 .getDisabledSystemPkgLPr(pkg.packageName); 8044 if (sysPs.getPermissionsState().hasInstallPermission(perm)) { 8045 // If the original was granted this permission, we take 8046 // that grant decision as read and propagate it to the 8047 // update. 8048 if (sysPs.isPrivileged()) { 8049 allowed = true; 8050 } 8051 } else { 8052 // The system apk may have been updated with an older 8053 // version of the one on the data partition, but which 8054 // granted a new system permission that it didn't have 8055 // before. In this case we do want to allow the app to 8056 // now get the new permission if the ancestral apk is 8057 // privileged to get it. 8058 if (sysPs.pkg != null && sysPs.isPrivileged()) { 8059 for (int j=0; 8060 j<sysPs.pkg.requestedPermissions.size(); j++) { 8061 if (perm.equals( 8062 sysPs.pkg.requestedPermissions.get(j))) { 8063 allowed = true; 8064 break; 8065 } 8066 } 8067 } 8068 } 8069 } else { 8070 allowed = isPrivilegedApp(pkg); 8071 } 8072 } 8073 } 8074 if (!allowed && (bp.protectionLevel 8075 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 8076 // For development permissions, a development permission 8077 // is granted only if it was already granted. 8078 allowed = origPermissions.hasInstallPermission(perm); 8079 } 8080 return allowed; 8081 } 8082 8083 final class ActivityIntentResolver 8084 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 8085 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8086 boolean defaultOnly, int userId) { 8087 if (!sUserManager.exists(userId)) return null; 8088 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8089 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8090 } 8091 8092 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8093 int userId) { 8094 if (!sUserManager.exists(userId)) return null; 8095 mFlags = flags; 8096 return super.queryIntent(intent, resolvedType, 8097 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8098 } 8099 8100 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8101 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 8102 if (!sUserManager.exists(userId)) return null; 8103 if (packageActivities == null) { 8104 return null; 8105 } 8106 mFlags = flags; 8107 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8108 final int N = packageActivities.size(); 8109 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 8110 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 8111 8112 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 8113 for (int i = 0; i < N; ++i) { 8114 intentFilters = packageActivities.get(i).intents; 8115 if (intentFilters != null && intentFilters.size() > 0) { 8116 PackageParser.ActivityIntentInfo[] array = 8117 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 8118 intentFilters.toArray(array); 8119 listCut.add(array); 8120 } 8121 } 8122 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8123 } 8124 8125 public final void addActivity(PackageParser.Activity a, String type) { 8126 final boolean systemApp = a.info.applicationInfo.isSystemApp(); 8127 mActivities.put(a.getComponentName(), a); 8128 if (DEBUG_SHOW_INFO) 8129 Log.v( 8130 TAG, " " + type + " " + 8131 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 8132 if (DEBUG_SHOW_INFO) 8133 Log.v(TAG, " Class=" + a.info.name); 8134 final int NI = a.intents.size(); 8135 for (int j=0; j<NI; j++) { 8136 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8137 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 8138 intent.setPriority(0); 8139 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 8140 + a.className + " with priority > 0, forcing to 0"); 8141 } 8142 if (DEBUG_SHOW_INFO) { 8143 Log.v(TAG, " IntentFilter:"); 8144 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8145 } 8146 if (!intent.debugCheck()) { 8147 Log.w(TAG, "==> For Activity " + a.info.name); 8148 } 8149 addFilter(intent); 8150 } 8151 } 8152 8153 public final void removeActivity(PackageParser.Activity a, String type) { 8154 mActivities.remove(a.getComponentName()); 8155 if (DEBUG_SHOW_INFO) { 8156 Log.v(TAG, " " + type + " " 8157 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 8158 : a.info.name) + ":"); 8159 Log.v(TAG, " Class=" + a.info.name); 8160 } 8161 final int NI = a.intents.size(); 8162 for (int j=0; j<NI; j++) { 8163 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 8164 if (DEBUG_SHOW_INFO) { 8165 Log.v(TAG, " IntentFilter:"); 8166 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8167 } 8168 removeFilter(intent); 8169 } 8170 } 8171 8172 @Override 8173 protected boolean allowFilterResult( 8174 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 8175 ActivityInfo filterAi = filter.activity.info; 8176 for (int i=dest.size()-1; i>=0; i--) { 8177 ActivityInfo destAi = dest.get(i).activityInfo; 8178 if (destAi.name == filterAi.name 8179 && destAi.packageName == filterAi.packageName) { 8180 return false; 8181 } 8182 } 8183 return true; 8184 } 8185 8186 @Override 8187 protected ActivityIntentInfo[] newArray(int size) { 8188 return new ActivityIntentInfo[size]; 8189 } 8190 8191 @Override 8192 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 8193 if (!sUserManager.exists(userId)) return true; 8194 PackageParser.Package p = filter.activity.owner; 8195 if (p != null) { 8196 PackageSetting ps = (PackageSetting)p.mExtras; 8197 if (ps != null) { 8198 // System apps are never considered stopped for purposes of 8199 // filtering, because there may be no way for the user to 8200 // actually re-launch them. 8201 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 8202 && ps.getStopped(userId); 8203 } 8204 } 8205 return false; 8206 } 8207 8208 @Override 8209 protected boolean isPackageForFilter(String packageName, 8210 PackageParser.ActivityIntentInfo info) { 8211 return packageName.equals(info.activity.owner.packageName); 8212 } 8213 8214 @Override 8215 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 8216 int match, int userId) { 8217 if (!sUserManager.exists(userId)) return null; 8218 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 8219 return null; 8220 } 8221 final PackageParser.Activity activity = info.activity; 8222 if (mSafeMode && (activity.info.applicationInfo.flags 8223 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8224 return null; 8225 } 8226 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 8227 if (ps == null) { 8228 return null; 8229 } 8230 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 8231 ps.readUserState(userId), userId); 8232 if (ai == null) { 8233 return null; 8234 } 8235 final ResolveInfo res = new ResolveInfo(); 8236 res.activityInfo = ai; 8237 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8238 res.filter = info; 8239 } 8240 if (info != null) { 8241 res.handleAllWebDataURI = info.handleAllWebDataURI(); 8242 } 8243 res.priority = info.getPriority(); 8244 res.preferredOrder = activity.owner.mPreferredOrder; 8245 //System.out.println("Result: " + res.activityInfo.className + 8246 // " = " + res.priority); 8247 res.match = match; 8248 res.isDefault = info.hasDefault; 8249 res.labelRes = info.labelRes; 8250 res.nonLocalizedLabel = info.nonLocalizedLabel; 8251 if (userNeedsBadging(userId)) { 8252 res.noResourceId = true; 8253 } else { 8254 res.icon = info.icon; 8255 } 8256 res.system = res.activityInfo.applicationInfo.isSystemApp(); 8257 return res; 8258 } 8259 8260 @Override 8261 protected void sortResults(List<ResolveInfo> results) { 8262 Collections.sort(results, mResolvePrioritySorter); 8263 } 8264 8265 @Override 8266 protected void dumpFilter(PrintWriter out, String prefix, 8267 PackageParser.ActivityIntentInfo filter) { 8268 out.print(prefix); out.print( 8269 Integer.toHexString(System.identityHashCode(filter.activity))); 8270 out.print(' '); 8271 filter.activity.printComponentShortName(out); 8272 out.print(" filter "); 8273 out.println(Integer.toHexString(System.identityHashCode(filter))); 8274 } 8275 8276 @Override 8277 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 8278 return filter.activity; 8279 } 8280 8281 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8282 PackageParser.Activity activity = (PackageParser.Activity)label; 8283 out.print(prefix); out.print( 8284 Integer.toHexString(System.identityHashCode(activity))); 8285 out.print(' '); 8286 activity.printComponentShortName(out); 8287 if (count > 1) { 8288 out.print(" ("); out.print(count); out.print(" filters)"); 8289 } 8290 out.println(); 8291 } 8292 8293// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8294// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8295// final List<ResolveInfo> retList = Lists.newArrayList(); 8296// while (i.hasNext()) { 8297// final ResolveInfo resolveInfo = i.next(); 8298// if (isEnabledLP(resolveInfo.activityInfo)) { 8299// retList.add(resolveInfo); 8300// } 8301// } 8302// return retList; 8303// } 8304 8305 // Keys are String (activity class name), values are Activity. 8306 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 8307 = new ArrayMap<ComponentName, PackageParser.Activity>(); 8308 private int mFlags; 8309 } 8310 8311 private final class ServiceIntentResolver 8312 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 8313 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8314 boolean defaultOnly, int userId) { 8315 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8316 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8317 } 8318 8319 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8320 int userId) { 8321 if (!sUserManager.exists(userId)) return null; 8322 mFlags = flags; 8323 return super.queryIntent(intent, resolvedType, 8324 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8325 } 8326 8327 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8328 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 8329 if (!sUserManager.exists(userId)) return null; 8330 if (packageServices == null) { 8331 return null; 8332 } 8333 mFlags = flags; 8334 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 8335 final int N = packageServices.size(); 8336 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 8337 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 8338 8339 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 8340 for (int i = 0; i < N; ++i) { 8341 intentFilters = packageServices.get(i).intents; 8342 if (intentFilters != null && intentFilters.size() > 0) { 8343 PackageParser.ServiceIntentInfo[] array = 8344 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 8345 intentFilters.toArray(array); 8346 listCut.add(array); 8347 } 8348 } 8349 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8350 } 8351 8352 public final void addService(PackageParser.Service s) { 8353 mServices.put(s.getComponentName(), s); 8354 if (DEBUG_SHOW_INFO) { 8355 Log.v(TAG, " " 8356 + (s.info.nonLocalizedLabel != null 8357 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8358 Log.v(TAG, " Class=" + s.info.name); 8359 } 8360 final int NI = s.intents.size(); 8361 int j; 8362 for (j=0; j<NI; j++) { 8363 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8364 if (DEBUG_SHOW_INFO) { 8365 Log.v(TAG, " IntentFilter:"); 8366 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8367 } 8368 if (!intent.debugCheck()) { 8369 Log.w(TAG, "==> For Service " + s.info.name); 8370 } 8371 addFilter(intent); 8372 } 8373 } 8374 8375 public final void removeService(PackageParser.Service s) { 8376 mServices.remove(s.getComponentName()); 8377 if (DEBUG_SHOW_INFO) { 8378 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 8379 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 8380 Log.v(TAG, " Class=" + s.info.name); 8381 } 8382 final int NI = s.intents.size(); 8383 int j; 8384 for (j=0; j<NI; j++) { 8385 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 8386 if (DEBUG_SHOW_INFO) { 8387 Log.v(TAG, " IntentFilter:"); 8388 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8389 } 8390 removeFilter(intent); 8391 } 8392 } 8393 8394 @Override 8395 protected boolean allowFilterResult( 8396 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 8397 ServiceInfo filterSi = filter.service.info; 8398 for (int i=dest.size()-1; i>=0; i--) { 8399 ServiceInfo destAi = dest.get(i).serviceInfo; 8400 if (destAi.name == filterSi.name 8401 && destAi.packageName == filterSi.packageName) { 8402 return false; 8403 } 8404 } 8405 return true; 8406 } 8407 8408 @Override 8409 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 8410 return new PackageParser.ServiceIntentInfo[size]; 8411 } 8412 8413 @Override 8414 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 8415 if (!sUserManager.exists(userId)) return true; 8416 PackageParser.Package p = filter.service.owner; 8417 if (p != null) { 8418 PackageSetting ps = (PackageSetting)p.mExtras; 8419 if (ps != null) { 8420 // System apps are never considered stopped for purposes of 8421 // filtering, because there may be no way for the user to 8422 // actually re-launch them. 8423 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8424 && ps.getStopped(userId); 8425 } 8426 } 8427 return false; 8428 } 8429 8430 @Override 8431 protected boolean isPackageForFilter(String packageName, 8432 PackageParser.ServiceIntentInfo info) { 8433 return packageName.equals(info.service.owner.packageName); 8434 } 8435 8436 @Override 8437 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 8438 int match, int userId) { 8439 if (!sUserManager.exists(userId)) return null; 8440 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 8441 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 8442 return null; 8443 } 8444 final PackageParser.Service service = info.service; 8445 if (mSafeMode && (service.info.applicationInfo.flags 8446 &ApplicationInfo.FLAG_SYSTEM) == 0) { 8447 return null; 8448 } 8449 PackageSetting ps = (PackageSetting) service.owner.mExtras; 8450 if (ps == null) { 8451 return null; 8452 } 8453 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 8454 ps.readUserState(userId), userId); 8455 if (si == null) { 8456 return null; 8457 } 8458 final ResolveInfo res = new ResolveInfo(); 8459 res.serviceInfo = si; 8460 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 8461 res.filter = filter; 8462 } 8463 res.priority = info.getPriority(); 8464 res.preferredOrder = service.owner.mPreferredOrder; 8465 res.match = match; 8466 res.isDefault = info.hasDefault; 8467 res.labelRes = info.labelRes; 8468 res.nonLocalizedLabel = info.nonLocalizedLabel; 8469 res.icon = info.icon; 8470 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 8471 return res; 8472 } 8473 8474 @Override 8475 protected void sortResults(List<ResolveInfo> results) { 8476 Collections.sort(results, mResolvePrioritySorter); 8477 } 8478 8479 @Override 8480 protected void dumpFilter(PrintWriter out, String prefix, 8481 PackageParser.ServiceIntentInfo filter) { 8482 out.print(prefix); out.print( 8483 Integer.toHexString(System.identityHashCode(filter.service))); 8484 out.print(' '); 8485 filter.service.printComponentShortName(out); 8486 out.print(" filter "); 8487 out.println(Integer.toHexString(System.identityHashCode(filter))); 8488 } 8489 8490 @Override 8491 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 8492 return filter.service; 8493 } 8494 8495 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8496 PackageParser.Service service = (PackageParser.Service)label; 8497 out.print(prefix); out.print( 8498 Integer.toHexString(System.identityHashCode(service))); 8499 out.print(' '); 8500 service.printComponentShortName(out); 8501 if (count > 1) { 8502 out.print(" ("); out.print(count); out.print(" filters)"); 8503 } 8504 out.println(); 8505 } 8506 8507// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 8508// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 8509// final List<ResolveInfo> retList = Lists.newArrayList(); 8510// while (i.hasNext()) { 8511// final ResolveInfo resolveInfo = (ResolveInfo) i; 8512// if (isEnabledLP(resolveInfo.serviceInfo)) { 8513// retList.add(resolveInfo); 8514// } 8515// } 8516// return retList; 8517// } 8518 8519 // Keys are String (activity class name), values are Activity. 8520 private final ArrayMap<ComponentName, PackageParser.Service> mServices 8521 = new ArrayMap<ComponentName, PackageParser.Service>(); 8522 private int mFlags; 8523 }; 8524 8525 private final class ProviderIntentResolver 8526 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 8527 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 8528 boolean defaultOnly, int userId) { 8529 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 8530 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 8531 } 8532 8533 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 8534 int userId) { 8535 if (!sUserManager.exists(userId)) 8536 return null; 8537 mFlags = flags; 8538 return super.queryIntent(intent, resolvedType, 8539 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 8540 } 8541 8542 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 8543 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 8544 if (!sUserManager.exists(userId)) 8545 return null; 8546 if (packageProviders == null) { 8547 return null; 8548 } 8549 mFlags = flags; 8550 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 8551 final int N = packageProviders.size(); 8552 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 8553 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 8554 8555 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 8556 for (int i = 0; i < N; ++i) { 8557 intentFilters = packageProviders.get(i).intents; 8558 if (intentFilters != null && intentFilters.size() > 0) { 8559 PackageParser.ProviderIntentInfo[] array = 8560 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 8561 intentFilters.toArray(array); 8562 listCut.add(array); 8563 } 8564 } 8565 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 8566 } 8567 8568 public final void addProvider(PackageParser.Provider p) { 8569 if (mProviders.containsKey(p.getComponentName())) { 8570 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 8571 return; 8572 } 8573 8574 mProviders.put(p.getComponentName(), p); 8575 if (DEBUG_SHOW_INFO) { 8576 Log.v(TAG, " " 8577 + (p.info.nonLocalizedLabel != null 8578 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8579 Log.v(TAG, " Class=" + p.info.name); 8580 } 8581 final int NI = p.intents.size(); 8582 int j; 8583 for (j = 0; j < NI; j++) { 8584 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8585 if (DEBUG_SHOW_INFO) { 8586 Log.v(TAG, " IntentFilter:"); 8587 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8588 } 8589 if (!intent.debugCheck()) { 8590 Log.w(TAG, "==> For Provider " + p.info.name); 8591 } 8592 addFilter(intent); 8593 } 8594 } 8595 8596 public final void removeProvider(PackageParser.Provider p) { 8597 mProviders.remove(p.getComponentName()); 8598 if (DEBUG_SHOW_INFO) { 8599 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 8600 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 8601 Log.v(TAG, " Class=" + p.info.name); 8602 } 8603 final int NI = p.intents.size(); 8604 int j; 8605 for (j = 0; j < NI; j++) { 8606 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 8607 if (DEBUG_SHOW_INFO) { 8608 Log.v(TAG, " IntentFilter:"); 8609 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 8610 } 8611 removeFilter(intent); 8612 } 8613 } 8614 8615 @Override 8616 protected boolean allowFilterResult( 8617 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 8618 ProviderInfo filterPi = filter.provider.info; 8619 for (int i = dest.size() - 1; i >= 0; i--) { 8620 ProviderInfo destPi = dest.get(i).providerInfo; 8621 if (destPi.name == filterPi.name 8622 && destPi.packageName == filterPi.packageName) { 8623 return false; 8624 } 8625 } 8626 return true; 8627 } 8628 8629 @Override 8630 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 8631 return new PackageParser.ProviderIntentInfo[size]; 8632 } 8633 8634 @Override 8635 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 8636 if (!sUserManager.exists(userId)) 8637 return true; 8638 PackageParser.Package p = filter.provider.owner; 8639 if (p != null) { 8640 PackageSetting ps = (PackageSetting) p.mExtras; 8641 if (ps != null) { 8642 // System apps are never considered stopped for purposes of 8643 // filtering, because there may be no way for the user to 8644 // actually re-launch them. 8645 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 8646 && ps.getStopped(userId); 8647 } 8648 } 8649 return false; 8650 } 8651 8652 @Override 8653 protected boolean isPackageForFilter(String packageName, 8654 PackageParser.ProviderIntentInfo info) { 8655 return packageName.equals(info.provider.owner.packageName); 8656 } 8657 8658 @Override 8659 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 8660 int match, int userId) { 8661 if (!sUserManager.exists(userId)) 8662 return null; 8663 final PackageParser.ProviderIntentInfo info = filter; 8664 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 8665 return null; 8666 } 8667 final PackageParser.Provider provider = info.provider; 8668 if (mSafeMode && (provider.info.applicationInfo.flags 8669 & ApplicationInfo.FLAG_SYSTEM) == 0) { 8670 return null; 8671 } 8672 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 8673 if (ps == null) { 8674 return null; 8675 } 8676 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 8677 ps.readUserState(userId), userId); 8678 if (pi == null) { 8679 return null; 8680 } 8681 final ResolveInfo res = new ResolveInfo(); 8682 res.providerInfo = pi; 8683 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 8684 res.filter = filter; 8685 } 8686 res.priority = info.getPriority(); 8687 res.preferredOrder = provider.owner.mPreferredOrder; 8688 res.match = match; 8689 res.isDefault = info.hasDefault; 8690 res.labelRes = info.labelRes; 8691 res.nonLocalizedLabel = info.nonLocalizedLabel; 8692 res.icon = info.icon; 8693 res.system = res.providerInfo.applicationInfo.isSystemApp(); 8694 return res; 8695 } 8696 8697 @Override 8698 protected void sortResults(List<ResolveInfo> results) { 8699 Collections.sort(results, mResolvePrioritySorter); 8700 } 8701 8702 @Override 8703 protected void dumpFilter(PrintWriter out, String prefix, 8704 PackageParser.ProviderIntentInfo filter) { 8705 out.print(prefix); 8706 out.print( 8707 Integer.toHexString(System.identityHashCode(filter.provider))); 8708 out.print(' '); 8709 filter.provider.printComponentShortName(out); 8710 out.print(" filter "); 8711 out.println(Integer.toHexString(System.identityHashCode(filter))); 8712 } 8713 8714 @Override 8715 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 8716 return filter.provider; 8717 } 8718 8719 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 8720 PackageParser.Provider provider = (PackageParser.Provider)label; 8721 out.print(prefix); out.print( 8722 Integer.toHexString(System.identityHashCode(provider))); 8723 out.print(' '); 8724 provider.printComponentShortName(out); 8725 if (count > 1) { 8726 out.print(" ("); out.print(count); out.print(" filters)"); 8727 } 8728 out.println(); 8729 } 8730 8731 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 8732 = new ArrayMap<ComponentName, PackageParser.Provider>(); 8733 private int mFlags; 8734 }; 8735 8736 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 8737 new Comparator<ResolveInfo>() { 8738 public int compare(ResolveInfo r1, ResolveInfo r2) { 8739 int v1 = r1.priority; 8740 int v2 = r2.priority; 8741 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 8742 if (v1 != v2) { 8743 return (v1 > v2) ? -1 : 1; 8744 } 8745 v1 = r1.preferredOrder; 8746 v2 = r2.preferredOrder; 8747 if (v1 != v2) { 8748 return (v1 > v2) ? -1 : 1; 8749 } 8750 if (r1.isDefault != r2.isDefault) { 8751 return r1.isDefault ? -1 : 1; 8752 } 8753 v1 = r1.match; 8754 v2 = r2.match; 8755 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 8756 if (v1 != v2) { 8757 return (v1 > v2) ? -1 : 1; 8758 } 8759 if (r1.system != r2.system) { 8760 return r1.system ? -1 : 1; 8761 } 8762 return 0; 8763 } 8764 }; 8765 8766 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 8767 new Comparator<ProviderInfo>() { 8768 public int compare(ProviderInfo p1, ProviderInfo p2) { 8769 final int v1 = p1.initOrder; 8770 final int v2 = p2.initOrder; 8771 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 8772 } 8773 }; 8774 8775 final void sendPackageBroadcast(final String action, final String pkg, 8776 final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver, 8777 final int[] userIds) { 8778 mHandler.post(new Runnable() { 8779 @Override 8780 public void run() { 8781 try { 8782 final IActivityManager am = ActivityManagerNative.getDefault(); 8783 if (am == null) return; 8784 final int[] resolvedUserIds; 8785 if (userIds == null) { 8786 resolvedUserIds = am.getRunningUserIds(); 8787 } else { 8788 resolvedUserIds = userIds; 8789 } 8790 for (int id : resolvedUserIds) { 8791 final Intent intent = new Intent(action, 8792 pkg != null ? Uri.fromParts("package", pkg, null) : null); 8793 if (extras != null) { 8794 intent.putExtras(extras); 8795 } 8796 if (targetPkg != null) { 8797 intent.setPackage(targetPkg); 8798 } 8799 // Modify the UID when posting to other users 8800 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8801 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8802 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8803 intent.putExtra(Intent.EXTRA_UID, uid); 8804 } 8805 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8806 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8807 if (DEBUG_BROADCASTS) { 8808 RuntimeException here = new RuntimeException("here"); 8809 here.fillInStackTrace(); 8810 Slog.d(TAG, "Sending to user " + id + ": " 8811 + intent.toShortString(false, true, false, false) 8812 + " " + intent.getExtras(), here); 8813 } 8814 am.broadcastIntent(null, intent, null, finishedReceiver, 8815 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8816 finishedReceiver != null, false, id); 8817 } 8818 } catch (RemoteException ex) { 8819 } 8820 } 8821 }); 8822 } 8823 8824 /** 8825 * Check if the external storage media is available. This is true if there 8826 * is a mounted external storage medium or if the external storage is 8827 * emulated. 8828 */ 8829 private boolean isExternalMediaAvailable() { 8830 return mMediaMounted || Environment.isExternalStorageEmulated(); 8831 } 8832 8833 @Override 8834 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8835 // writer 8836 synchronized (mPackages) { 8837 if (!isExternalMediaAvailable()) { 8838 // If the external storage is no longer mounted at this point, 8839 // the caller may not have been able to delete all of this 8840 // packages files and can not delete any more. Bail. 8841 return null; 8842 } 8843 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8844 if (lastPackage != null) { 8845 pkgs.remove(lastPackage); 8846 } 8847 if (pkgs.size() > 0) { 8848 return pkgs.get(0); 8849 } 8850 } 8851 return null; 8852 } 8853 8854 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8855 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8856 userId, andCode ? 1 : 0, packageName); 8857 if (mSystemReady) { 8858 msg.sendToTarget(); 8859 } else { 8860 if (mPostSystemReadyMessages == null) { 8861 mPostSystemReadyMessages = new ArrayList<>(); 8862 } 8863 mPostSystemReadyMessages.add(msg); 8864 } 8865 } 8866 8867 void startCleaningPackages() { 8868 // reader 8869 synchronized (mPackages) { 8870 if (!isExternalMediaAvailable()) { 8871 return; 8872 } 8873 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8874 return; 8875 } 8876 } 8877 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8878 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8879 IActivityManager am = ActivityManagerNative.getDefault(); 8880 if (am != null) { 8881 try { 8882 am.startService(null, intent, null, UserHandle.USER_OWNER); 8883 } catch (RemoteException e) { 8884 } 8885 } 8886 } 8887 8888 @Override 8889 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8890 int installFlags, String installerPackageName, VerificationParams verificationParams, 8891 String packageAbiOverride) { 8892 installPackageAsUser(originPath, observer, installFlags, installerPackageName, 8893 verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); 8894 } 8895 8896 @Override 8897 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8898 int installFlags, String installerPackageName, VerificationParams verificationParams, 8899 String packageAbiOverride, int userId) { 8900 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8901 8902 final int callingUid = Binder.getCallingUid(); 8903 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8904 8905 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8906 try { 8907 if (observer != null) { 8908 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8909 } 8910 } catch (RemoteException re) { 8911 } 8912 return; 8913 } 8914 8915 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8916 installFlags |= PackageManager.INSTALL_FROM_ADB; 8917 8918 } else { 8919 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8920 // about installerPackageName. 8921 8922 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8923 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8924 } 8925 8926 UserHandle user; 8927 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8928 user = UserHandle.ALL; 8929 } else { 8930 user = new UserHandle(userId); 8931 } 8932 8933 // Only system components can circumvent runtime permissions when installing. 8934 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 8935 && mContext.checkCallingOrSelfPermission(Manifest.permission 8936 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 8937 throw new SecurityException("You need the " 8938 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 8939 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 8940 } 8941 8942 verificationParams.setInstallerUid(callingUid); 8943 8944 final File originFile = new File(originPath); 8945 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8946 8947 final Message msg = mHandler.obtainMessage(INIT_COPY); 8948 msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName, 8949 null, verificationParams, user, packageAbiOverride); 8950 mHandler.sendMessage(msg); 8951 } 8952 8953 void installStage(String packageName, File stagedDir, String stagedCid, 8954 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8955 String installerPackageName, int installerUid, UserHandle user) { 8956 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8957 params.referrerUri, installerUid, null); 8958 8959 final OriginInfo origin; 8960 if (stagedDir != null) { 8961 origin = OriginInfo.fromStagedFile(stagedDir); 8962 } else { 8963 origin = OriginInfo.fromStagedContainer(stagedCid); 8964 } 8965 8966 final Message msg = mHandler.obtainMessage(INIT_COPY); 8967 msg.obj = new InstallParams(origin, null, observer, params.installFlags, 8968 installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride); 8969 mHandler.sendMessage(msg); 8970 } 8971 8972 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8973 Bundle extras = new Bundle(1); 8974 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8975 8976 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8977 packageName, extras, null, null, new int[] {userId}); 8978 try { 8979 IActivityManager am = ActivityManagerNative.getDefault(); 8980 final boolean isSystem = 8981 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8982 if (isSystem && am.isUserRunning(userId, false)) { 8983 // The just-installed/enabled app is bundled on the system, so presumed 8984 // to be able to run automatically without needing an explicit launch. 8985 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8986 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8987 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8988 .setPackage(packageName); 8989 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8990 android.app.AppOpsManager.OP_NONE, false, false, userId); 8991 } 8992 } catch (RemoteException e) { 8993 // shouldn't happen 8994 Slog.w(TAG, "Unable to bootstrap installed package", e); 8995 } 8996 } 8997 8998 @Override 8999 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 9000 int userId) { 9001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9002 PackageSetting pkgSetting; 9003 final int uid = Binder.getCallingUid(); 9004 enforceCrossUserPermission(uid, userId, true, true, 9005 "setApplicationHiddenSetting for user " + userId); 9006 9007 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 9008 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 9009 return false; 9010 } 9011 9012 long callingId = Binder.clearCallingIdentity(); 9013 try { 9014 boolean sendAdded = false; 9015 boolean sendRemoved = false; 9016 // writer 9017 synchronized (mPackages) { 9018 pkgSetting = mSettings.mPackages.get(packageName); 9019 if (pkgSetting == null) { 9020 return false; 9021 } 9022 if (pkgSetting.getHidden(userId) != hidden) { 9023 pkgSetting.setHidden(hidden, userId); 9024 mSettings.writePackageRestrictionsLPr(userId); 9025 if (hidden) { 9026 sendRemoved = true; 9027 } else { 9028 sendAdded = true; 9029 } 9030 } 9031 } 9032 if (sendAdded) { 9033 sendPackageAddedForUser(packageName, pkgSetting, userId); 9034 return true; 9035 } 9036 if (sendRemoved) { 9037 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 9038 "hiding pkg"); 9039 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 9040 } 9041 } finally { 9042 Binder.restoreCallingIdentity(callingId); 9043 } 9044 return false; 9045 } 9046 9047 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 9048 int userId) { 9049 final PackageRemovedInfo info = new PackageRemovedInfo(); 9050 info.removedPackage = packageName; 9051 info.removedUsers = new int[] {userId}; 9052 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 9053 info.sendBroadcast(false, false, false); 9054 } 9055 9056 /** 9057 * Returns true if application is not found or there was an error. Otherwise it returns 9058 * the hidden state of the package for the given user. 9059 */ 9060 @Override 9061 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 9062 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 9063 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 9064 false, "getApplicationHidden for user " + userId); 9065 PackageSetting pkgSetting; 9066 long callingId = Binder.clearCallingIdentity(); 9067 try { 9068 // writer 9069 synchronized (mPackages) { 9070 pkgSetting = mSettings.mPackages.get(packageName); 9071 if (pkgSetting == null) { 9072 return true; 9073 } 9074 return pkgSetting.getHidden(userId); 9075 } 9076 } finally { 9077 Binder.restoreCallingIdentity(callingId); 9078 } 9079 } 9080 9081 /** 9082 * @hide 9083 */ 9084 @Override 9085 public int installExistingPackageAsUser(String packageName, int userId) { 9086 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 9087 null); 9088 PackageSetting pkgSetting; 9089 final int uid = Binder.getCallingUid(); 9090 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 9091 + userId); 9092 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 9093 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 9094 } 9095 9096 long callingId = Binder.clearCallingIdentity(); 9097 try { 9098 boolean sendAdded = false; 9099 9100 // writer 9101 synchronized (mPackages) { 9102 pkgSetting = mSettings.mPackages.get(packageName); 9103 if (pkgSetting == null) { 9104 return PackageManager.INSTALL_FAILED_INVALID_URI; 9105 } 9106 if (!pkgSetting.getInstalled(userId)) { 9107 pkgSetting.setInstalled(true, userId); 9108 pkgSetting.setHidden(false, userId); 9109 mSettings.writePackageRestrictionsLPr(userId); 9110 sendAdded = true; 9111 } 9112 } 9113 9114 if (sendAdded) { 9115 sendPackageAddedForUser(packageName, pkgSetting, userId); 9116 } 9117 } finally { 9118 Binder.restoreCallingIdentity(callingId); 9119 } 9120 9121 return PackageManager.INSTALL_SUCCEEDED; 9122 } 9123 9124 boolean isUserRestricted(int userId, String restrictionKey) { 9125 Bundle restrictions = sUserManager.getUserRestrictions(userId); 9126 if (restrictions.getBoolean(restrictionKey, false)) { 9127 Log.w(TAG, "User is restricted: " + restrictionKey); 9128 return true; 9129 } 9130 return false; 9131 } 9132 9133 @Override 9134 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 9135 mContext.enforceCallingOrSelfPermission( 9136 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9137 "Only package verification agents can verify applications"); 9138 9139 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9140 final PackageVerificationResponse response = new PackageVerificationResponse( 9141 verificationCode, Binder.getCallingUid()); 9142 msg.arg1 = id; 9143 msg.obj = response; 9144 mHandler.sendMessage(msg); 9145 } 9146 9147 @Override 9148 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 9149 long millisecondsToDelay) { 9150 mContext.enforceCallingOrSelfPermission( 9151 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9152 "Only package verification agents can extend verification timeouts"); 9153 9154 final PackageVerificationState state = mPendingVerification.get(id); 9155 final PackageVerificationResponse response = new PackageVerificationResponse( 9156 verificationCodeAtTimeout, Binder.getCallingUid()); 9157 9158 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 9159 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 9160 } 9161 if (millisecondsToDelay < 0) { 9162 millisecondsToDelay = 0; 9163 } 9164 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 9165 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 9166 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 9167 } 9168 9169 if ((state != null) && !state.timeoutExtended()) { 9170 state.extendTimeout(); 9171 9172 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 9173 msg.arg1 = id; 9174 msg.obj = response; 9175 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 9176 } 9177 } 9178 9179 private void broadcastPackageVerified(int verificationId, Uri packageUri, 9180 int verificationCode, UserHandle user) { 9181 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 9182 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 9183 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9184 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9185 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 9186 9187 mContext.sendBroadcastAsUser(intent, user, 9188 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 9189 } 9190 9191 private ComponentName matchComponentForVerifier(String packageName, 9192 List<ResolveInfo> receivers) { 9193 ActivityInfo targetReceiver = null; 9194 9195 final int NR = receivers.size(); 9196 for (int i = 0; i < NR; i++) { 9197 final ResolveInfo info = receivers.get(i); 9198 if (info.activityInfo == null) { 9199 continue; 9200 } 9201 9202 if (packageName.equals(info.activityInfo.packageName)) { 9203 targetReceiver = info.activityInfo; 9204 break; 9205 } 9206 } 9207 9208 if (targetReceiver == null) { 9209 return null; 9210 } 9211 9212 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 9213 } 9214 9215 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 9216 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 9217 if (pkgInfo.verifiers.length == 0) { 9218 return null; 9219 } 9220 9221 final int N = pkgInfo.verifiers.length; 9222 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 9223 for (int i = 0; i < N; i++) { 9224 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 9225 9226 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 9227 receivers); 9228 if (comp == null) { 9229 continue; 9230 } 9231 9232 final int verifierUid = getUidForVerifier(verifierInfo); 9233 if (verifierUid == -1) { 9234 continue; 9235 } 9236 9237 if (DEBUG_VERIFY) { 9238 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 9239 + " with the correct signature"); 9240 } 9241 sufficientVerifiers.add(comp); 9242 verificationState.addSufficientVerifier(verifierUid); 9243 } 9244 9245 return sufficientVerifiers; 9246 } 9247 9248 private int getUidForVerifier(VerifierInfo verifierInfo) { 9249 synchronized (mPackages) { 9250 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 9251 if (pkg == null) { 9252 return -1; 9253 } else if (pkg.mSignatures.length != 1) { 9254 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9255 + " has more than one signature; ignoring"); 9256 return -1; 9257 } 9258 9259 /* 9260 * If the public key of the package's signature does not match 9261 * our expected public key, then this is a different package and 9262 * we should skip. 9263 */ 9264 9265 final byte[] expectedPublicKey; 9266 try { 9267 final Signature verifierSig = pkg.mSignatures[0]; 9268 final PublicKey publicKey = verifierSig.getPublicKey(); 9269 expectedPublicKey = publicKey.getEncoded(); 9270 } catch (CertificateException e) { 9271 return -1; 9272 } 9273 9274 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 9275 9276 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 9277 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 9278 + " does not have the expected public key; ignoring"); 9279 return -1; 9280 } 9281 9282 return pkg.applicationInfo.uid; 9283 } 9284 } 9285 9286 @Override 9287 public void finishPackageInstall(int token) { 9288 enforceSystemOrRoot("Only the system is allowed to finish installs"); 9289 9290 if (DEBUG_INSTALL) { 9291 Slog.v(TAG, "BM finishing package install for " + token); 9292 } 9293 9294 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9295 mHandler.sendMessage(msg); 9296 } 9297 9298 /** 9299 * Get the verification agent timeout. 9300 * 9301 * @return verification timeout in milliseconds 9302 */ 9303 private long getVerificationTimeout() { 9304 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 9305 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 9306 DEFAULT_VERIFICATION_TIMEOUT); 9307 } 9308 9309 /** 9310 * Get the default verification agent response code. 9311 * 9312 * @return default verification response code 9313 */ 9314 private int getDefaultVerificationResponse() { 9315 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9316 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 9317 DEFAULT_VERIFICATION_RESPONSE); 9318 } 9319 9320 /** 9321 * Check whether or not package verification has been enabled. 9322 * 9323 * @return true if verification should be performed 9324 */ 9325 private boolean isVerificationEnabled(int userId, int installFlags) { 9326 if (!DEFAULT_VERIFY_ENABLE) { 9327 return false; 9328 } 9329 9330 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 9331 9332 // Check if installing from ADB 9333 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 9334 // Do not run verification in a test harness environment 9335 if (ActivityManager.isRunningInTestHarness()) { 9336 return false; 9337 } 9338 if (ensureVerifyAppsEnabled) { 9339 return true; 9340 } 9341 // Check if the developer does not want package verification for ADB installs 9342 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9343 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 9344 return false; 9345 } 9346 } 9347 9348 if (ensureVerifyAppsEnabled) { 9349 return true; 9350 } 9351 9352 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9353 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 9354 } 9355 9356 @Override 9357 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 9358 throws RemoteException { 9359 mContext.enforceCallingOrSelfPermission( 9360 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 9361 "Only intentfilter verification agents can verify applications"); 9362 9363 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 9364 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 9365 Binder.getCallingUid(), verificationCode, failedDomains); 9366 msg.arg1 = id; 9367 msg.obj = response; 9368 mHandler.sendMessage(msg); 9369 } 9370 9371 @Override 9372 public int getIntentVerificationStatus(String packageName, int userId) { 9373 synchronized (mPackages) { 9374 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 9375 } 9376 } 9377 9378 @Override 9379 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 9380 boolean result = false; 9381 synchronized (mPackages) { 9382 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 9383 } 9384 if (result) { 9385 scheduleWritePackageRestrictionsLocked(userId); 9386 } 9387 return result; 9388 } 9389 9390 @Override 9391 public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) { 9392 synchronized (mPackages) { 9393 return mSettings.getIntentFilterVerificationsLPr(packageName); 9394 } 9395 } 9396 9397 @Override 9398 public List<IntentFilter> getAllIntentFilters(String packageName) { 9399 if (TextUtils.isEmpty(packageName)) { 9400 return Collections.<IntentFilter>emptyList(); 9401 } 9402 synchronized (mPackages) { 9403 PackageParser.Package pkg = mPackages.get(packageName); 9404 if (pkg == null || pkg.activities == null) { 9405 return Collections.<IntentFilter>emptyList(); 9406 } 9407 final int count = pkg.activities.size(); 9408 ArrayList<IntentFilter> result = new ArrayList<>(); 9409 for (int n=0; n<count; n++) { 9410 PackageParser.Activity activity = pkg.activities.get(n); 9411 if (activity.intents != null || activity.intents.size() > 0) { 9412 result.addAll(activity.intents); 9413 } 9414 } 9415 return result; 9416 } 9417 } 9418 9419 @Override 9420 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 9421 synchronized (mPackages) { 9422 boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId); 9423 if (packageName != null) { 9424 result |= updateIntentVerificationStatus(packageName, 9425 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 9426 UserHandle.myUserId()); 9427 } 9428 return result; 9429 } 9430 } 9431 9432 @Override 9433 public String getDefaultBrowserPackageName(int userId) { 9434 synchronized (mPackages) { 9435 return mSettings.getDefaultBrowserPackageNameLPw(userId); 9436 } 9437 } 9438 9439 /** 9440 * Get the "allow unknown sources" setting. 9441 * 9442 * @return the current "allow unknown sources" setting 9443 */ 9444 private int getUnknownSourcesSettings() { 9445 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 9446 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 9447 -1); 9448 } 9449 9450 @Override 9451 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 9452 final int uid = Binder.getCallingUid(); 9453 // writer 9454 synchronized (mPackages) { 9455 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 9456 if (targetPackageSetting == null) { 9457 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 9458 } 9459 9460 PackageSetting installerPackageSetting; 9461 if (installerPackageName != null) { 9462 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 9463 if (installerPackageSetting == null) { 9464 throw new IllegalArgumentException("Unknown installer package: " 9465 + installerPackageName); 9466 } 9467 } else { 9468 installerPackageSetting = null; 9469 } 9470 9471 Signature[] callerSignature; 9472 Object obj = mSettings.getUserIdLPr(uid); 9473 if (obj != null) { 9474 if (obj instanceof SharedUserSetting) { 9475 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 9476 } else if (obj instanceof PackageSetting) { 9477 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 9478 } else { 9479 throw new SecurityException("Bad object " + obj + " for uid " + uid); 9480 } 9481 } else { 9482 throw new SecurityException("Unknown calling uid " + uid); 9483 } 9484 9485 // Verify: can't set installerPackageName to a package that is 9486 // not signed with the same cert as the caller. 9487 if (installerPackageSetting != null) { 9488 if (compareSignatures(callerSignature, 9489 installerPackageSetting.signatures.mSignatures) 9490 != PackageManager.SIGNATURE_MATCH) { 9491 throw new SecurityException( 9492 "Caller does not have same cert as new installer package " 9493 + installerPackageName); 9494 } 9495 } 9496 9497 // Verify: if target already has an installer package, it must 9498 // be signed with the same cert as the caller. 9499 if (targetPackageSetting.installerPackageName != null) { 9500 PackageSetting setting = mSettings.mPackages.get( 9501 targetPackageSetting.installerPackageName); 9502 // If the currently set package isn't valid, then it's always 9503 // okay to change it. 9504 if (setting != null) { 9505 if (compareSignatures(callerSignature, 9506 setting.signatures.mSignatures) 9507 != PackageManager.SIGNATURE_MATCH) { 9508 throw new SecurityException( 9509 "Caller does not have same cert as old installer package " 9510 + targetPackageSetting.installerPackageName); 9511 } 9512 } 9513 } 9514 9515 // Okay! 9516 targetPackageSetting.installerPackageName = installerPackageName; 9517 scheduleWriteSettingsLocked(); 9518 } 9519 } 9520 9521 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 9522 // Queue up an async operation since the package installation may take a little while. 9523 mHandler.post(new Runnable() { 9524 public void run() { 9525 mHandler.removeCallbacks(this); 9526 // Result object to be returned 9527 PackageInstalledInfo res = new PackageInstalledInfo(); 9528 res.returnCode = currentStatus; 9529 res.uid = -1; 9530 res.pkg = null; 9531 res.removedInfo = new PackageRemovedInfo(); 9532 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 9533 args.doPreInstall(res.returnCode); 9534 synchronized (mInstallLock) { 9535 installPackageLI(args, res); 9536 } 9537 args.doPostInstall(res.returnCode, res.uid); 9538 } 9539 9540 // A restore should be performed at this point if (a) the install 9541 // succeeded, (b) the operation is not an update, and (c) the new 9542 // package has not opted out of backup participation. 9543 final boolean update = res.removedInfo.removedPackage != null; 9544 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 9545 boolean doRestore = !update 9546 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 9547 9548 // Set up the post-install work request bookkeeping. This will be used 9549 // and cleaned up by the post-install event handling regardless of whether 9550 // there's a restore pass performed. Token values are >= 1. 9551 int token; 9552 if (mNextInstallToken < 0) mNextInstallToken = 1; 9553 token = mNextInstallToken++; 9554 9555 PostInstallData data = new PostInstallData(args, res); 9556 mRunningInstalls.put(token, data); 9557 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 9558 9559 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 9560 // Pass responsibility to the Backup Manager. It will perform a 9561 // restore if appropriate, then pass responsibility back to the 9562 // Package Manager to run the post-install observer callbacks 9563 // and broadcasts. 9564 IBackupManager bm = IBackupManager.Stub.asInterface( 9565 ServiceManager.getService(Context.BACKUP_SERVICE)); 9566 if (bm != null) { 9567 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 9568 + " to BM for possible restore"); 9569 try { 9570 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 9571 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 9572 } else { 9573 doRestore = false; 9574 } 9575 } catch (RemoteException e) { 9576 // can't happen; the backup manager is local 9577 } catch (Exception e) { 9578 Slog.e(TAG, "Exception trying to enqueue restore", e); 9579 doRestore = false; 9580 } 9581 } else { 9582 Slog.e(TAG, "Backup Manager not found!"); 9583 doRestore = false; 9584 } 9585 } 9586 9587 if (!doRestore) { 9588 // No restore possible, or the Backup Manager was mysteriously not 9589 // available -- just fire the post-install work request directly. 9590 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 9591 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 9592 mHandler.sendMessage(msg); 9593 } 9594 } 9595 }); 9596 } 9597 9598 private abstract class HandlerParams { 9599 private static final int MAX_RETRIES = 4; 9600 9601 /** 9602 * Number of times startCopy() has been attempted and had a non-fatal 9603 * error. 9604 */ 9605 private int mRetries = 0; 9606 9607 /** User handle for the user requesting the information or installation. */ 9608 private final UserHandle mUser; 9609 9610 HandlerParams(UserHandle user) { 9611 mUser = user; 9612 } 9613 9614 UserHandle getUser() { 9615 return mUser; 9616 } 9617 9618 final boolean startCopy() { 9619 boolean res; 9620 try { 9621 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 9622 9623 if (++mRetries > MAX_RETRIES) { 9624 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 9625 mHandler.sendEmptyMessage(MCS_GIVE_UP); 9626 handleServiceError(); 9627 return false; 9628 } else { 9629 handleStartCopy(); 9630 res = true; 9631 } 9632 } catch (RemoteException e) { 9633 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 9634 mHandler.sendEmptyMessage(MCS_RECONNECT); 9635 res = false; 9636 } 9637 handleReturnCode(); 9638 return res; 9639 } 9640 9641 final void serviceError() { 9642 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 9643 handleServiceError(); 9644 handleReturnCode(); 9645 } 9646 9647 abstract void handleStartCopy() throws RemoteException; 9648 abstract void handleServiceError(); 9649 abstract void handleReturnCode(); 9650 } 9651 9652 class MeasureParams extends HandlerParams { 9653 private final PackageStats mStats; 9654 private boolean mSuccess; 9655 9656 private final IPackageStatsObserver mObserver; 9657 9658 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 9659 super(new UserHandle(stats.userHandle)); 9660 mObserver = observer; 9661 mStats = stats; 9662 } 9663 9664 @Override 9665 public String toString() { 9666 return "MeasureParams{" 9667 + Integer.toHexString(System.identityHashCode(this)) 9668 + " " + mStats.packageName + "}"; 9669 } 9670 9671 @Override 9672 void handleStartCopy() throws RemoteException { 9673 synchronized (mInstallLock) { 9674 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 9675 } 9676 9677 if (mSuccess) { 9678 final boolean mounted; 9679 if (Environment.isExternalStorageEmulated()) { 9680 mounted = true; 9681 } else { 9682 final String status = Environment.getExternalStorageState(); 9683 mounted = (Environment.MEDIA_MOUNTED.equals(status) 9684 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 9685 } 9686 9687 if (mounted) { 9688 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 9689 9690 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 9691 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 9692 9693 mStats.externalDataSize = calculateDirectorySize(mContainerService, 9694 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 9695 9696 // Always subtract cache size, since it's a subdirectory 9697 mStats.externalDataSize -= mStats.externalCacheSize; 9698 9699 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 9700 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 9701 9702 mStats.externalObbSize = calculateDirectorySize(mContainerService, 9703 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 9704 } 9705 } 9706 } 9707 9708 @Override 9709 void handleReturnCode() { 9710 if (mObserver != null) { 9711 try { 9712 mObserver.onGetStatsCompleted(mStats, mSuccess); 9713 } catch (RemoteException e) { 9714 Slog.i(TAG, "Observer no longer exists."); 9715 } 9716 } 9717 } 9718 9719 @Override 9720 void handleServiceError() { 9721 Slog.e(TAG, "Could not measure application " + mStats.packageName 9722 + " external storage"); 9723 } 9724 } 9725 9726 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 9727 throws RemoteException { 9728 long result = 0; 9729 for (File path : paths) { 9730 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 9731 } 9732 return result; 9733 } 9734 9735 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 9736 for (File path : paths) { 9737 try { 9738 mcs.clearDirectory(path.getAbsolutePath()); 9739 } catch (RemoteException e) { 9740 } 9741 } 9742 } 9743 9744 static class OriginInfo { 9745 /** 9746 * Location where install is coming from, before it has been 9747 * copied/renamed into place. This could be a single monolithic APK 9748 * file, or a cluster directory. This location may be untrusted. 9749 */ 9750 final File file; 9751 final String cid; 9752 9753 /** 9754 * Flag indicating that {@link #file} or {@link #cid} has already been 9755 * staged, meaning downstream users don't need to defensively copy the 9756 * contents. 9757 */ 9758 final boolean staged; 9759 9760 /** 9761 * Flag indicating that {@link #file} or {@link #cid} is an already 9762 * installed app that is being moved. 9763 */ 9764 final boolean existing; 9765 9766 final String resolvedPath; 9767 final File resolvedFile; 9768 9769 static OriginInfo fromNothing() { 9770 return new OriginInfo(null, null, false, false); 9771 } 9772 9773 static OriginInfo fromUntrustedFile(File file) { 9774 return new OriginInfo(file, null, false, false); 9775 } 9776 9777 static OriginInfo fromExistingFile(File file) { 9778 return new OriginInfo(file, null, false, true); 9779 } 9780 9781 static OriginInfo fromStagedFile(File file) { 9782 return new OriginInfo(file, null, true, false); 9783 } 9784 9785 static OriginInfo fromStagedContainer(String cid) { 9786 return new OriginInfo(null, cid, true, false); 9787 } 9788 9789 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 9790 this.file = file; 9791 this.cid = cid; 9792 this.staged = staged; 9793 this.existing = existing; 9794 9795 if (cid != null) { 9796 resolvedPath = PackageHelper.getSdDir(cid); 9797 resolvedFile = new File(resolvedPath); 9798 } else if (file != null) { 9799 resolvedPath = file.getAbsolutePath(); 9800 resolvedFile = file; 9801 } else { 9802 resolvedPath = null; 9803 resolvedFile = null; 9804 } 9805 } 9806 } 9807 9808 class MoveInfo { 9809 final int moveId; 9810 final String fromUuid; 9811 final String toUuid; 9812 final String packageName; 9813 final String dataAppName; 9814 final int appId; 9815 final String seinfo; 9816 9817 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 9818 String dataAppName, int appId, String seinfo) { 9819 this.moveId = moveId; 9820 this.fromUuid = fromUuid; 9821 this.toUuid = toUuid; 9822 this.packageName = packageName; 9823 this.dataAppName = dataAppName; 9824 this.appId = appId; 9825 this.seinfo = seinfo; 9826 } 9827 } 9828 9829 class InstallParams extends HandlerParams { 9830 final OriginInfo origin; 9831 final MoveInfo move; 9832 final IPackageInstallObserver2 observer; 9833 int installFlags; 9834 final String installerPackageName; 9835 final String volumeUuid; 9836 final VerificationParams verificationParams; 9837 private InstallArgs mArgs; 9838 private int mRet; 9839 final String packageAbiOverride; 9840 9841 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 9842 int installFlags, String installerPackageName, String volumeUuid, 9843 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 9844 super(user); 9845 this.origin = origin; 9846 this.move = move; 9847 this.observer = observer; 9848 this.installFlags = installFlags; 9849 this.installerPackageName = installerPackageName; 9850 this.volumeUuid = volumeUuid; 9851 this.verificationParams = verificationParams; 9852 this.packageAbiOverride = packageAbiOverride; 9853 } 9854 9855 @Override 9856 public String toString() { 9857 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 9858 + " file=" + origin.file + " cid=" + origin.cid + "}"; 9859 } 9860 9861 public ManifestDigest getManifestDigest() { 9862 if (verificationParams == null) { 9863 return null; 9864 } 9865 return verificationParams.getManifestDigest(); 9866 } 9867 9868 private int installLocationPolicy(PackageInfoLite pkgLite) { 9869 String packageName = pkgLite.packageName; 9870 int installLocation = pkgLite.installLocation; 9871 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9872 // reader 9873 synchronized (mPackages) { 9874 PackageParser.Package pkg = mPackages.get(packageName); 9875 if (pkg != null) { 9876 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9877 // Check for downgrading. 9878 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 9879 try { 9880 checkDowngrade(pkg, pkgLite); 9881 } catch (PackageManagerException e) { 9882 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 9883 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 9884 } 9885 } 9886 // Check for updated system application. 9887 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9888 if (onSd) { 9889 Slog.w(TAG, "Cannot install update to system app on sdcard"); 9890 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 9891 } 9892 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9893 } else { 9894 if (onSd) { 9895 // Install flag overrides everything. 9896 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9897 } 9898 // If current upgrade specifies particular preference 9899 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 9900 // Application explicitly specified internal. 9901 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9902 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 9903 // App explictly prefers external. Let policy decide 9904 } else { 9905 // Prefer previous location 9906 if (isExternal(pkg)) { 9907 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9908 } 9909 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 9910 } 9911 } 9912 } else { 9913 // Invalid install. Return error code 9914 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 9915 } 9916 } 9917 } 9918 // All the special cases have been taken care of. 9919 // Return result based on recommended install location. 9920 if (onSd) { 9921 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9922 } 9923 return pkgLite.recommendedInstallLocation; 9924 } 9925 9926 /* 9927 * Invoke remote method to get package information and install 9928 * location values. Override install location based on default 9929 * policy if needed and then create install arguments based 9930 * on the install location. 9931 */ 9932 public void handleStartCopy() throws RemoteException { 9933 int ret = PackageManager.INSTALL_SUCCEEDED; 9934 9935 // If we're already staged, we've firmly committed to an install location 9936 if (origin.staged) { 9937 if (origin.file != null) { 9938 installFlags |= PackageManager.INSTALL_INTERNAL; 9939 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9940 } else if (origin.cid != null) { 9941 installFlags |= PackageManager.INSTALL_EXTERNAL; 9942 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9943 } else { 9944 throw new IllegalStateException("Invalid stage location"); 9945 } 9946 } 9947 9948 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9949 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9950 9951 PackageInfoLite pkgLite = null; 9952 9953 if (onInt && onSd) { 9954 // Check if both bits are set. 9955 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9956 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9957 } else { 9958 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9959 packageAbiOverride); 9960 9961 /* 9962 * If we have too little free space, try to free cache 9963 * before giving up. 9964 */ 9965 if (!origin.staged && pkgLite.recommendedInstallLocation 9966 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9967 // TODO: focus freeing disk space on the target device 9968 final StorageManager storage = StorageManager.from(mContext); 9969 final long lowThreshold = storage.getStorageLowBytes( 9970 Environment.getDataDirectory()); 9971 9972 final long sizeBytes = mContainerService.calculateInstalledSize( 9973 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9974 9975 if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) { 9976 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9977 installFlags, packageAbiOverride); 9978 } 9979 9980 /* 9981 * The cache free must have deleted the file we 9982 * downloaded to install. 9983 * 9984 * TODO: fix the "freeCache" call to not delete 9985 * the file we care about. 9986 */ 9987 if (pkgLite.recommendedInstallLocation 9988 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9989 pkgLite.recommendedInstallLocation 9990 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9991 } 9992 } 9993 } 9994 9995 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9996 int loc = pkgLite.recommendedInstallLocation; 9997 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9998 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9999 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 10000 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 10001 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 10002 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10003 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 10004 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 10005 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 10006 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 10007 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 10008 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 10009 } else { 10010 // Override with defaults if needed. 10011 loc = installLocationPolicy(pkgLite); 10012 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 10013 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 10014 } else if (!onSd && !onInt) { 10015 // Override install location with flags 10016 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 10017 // Set the flag to install on external media. 10018 installFlags |= PackageManager.INSTALL_EXTERNAL; 10019 installFlags &= ~PackageManager.INSTALL_INTERNAL; 10020 } else { 10021 // Make sure the flag for installing on external 10022 // media is unset 10023 installFlags |= PackageManager.INSTALL_INTERNAL; 10024 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 10025 } 10026 } 10027 } 10028 } 10029 10030 final InstallArgs args = createInstallArgs(this); 10031 mArgs = args; 10032 10033 if (ret == PackageManager.INSTALL_SUCCEEDED) { 10034 /* 10035 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 10036 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 10037 */ 10038 int userIdentifier = getUser().getIdentifier(); 10039 if (userIdentifier == UserHandle.USER_ALL 10040 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 10041 userIdentifier = UserHandle.USER_OWNER; 10042 } 10043 10044 /* 10045 * Determine if we have any installed package verifiers. If we 10046 * do, then we'll defer to them to verify the packages. 10047 */ 10048 final int requiredUid = mRequiredVerifierPackage == null ? -1 10049 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 10050 if (!origin.existing && requiredUid != -1 10051 && isVerificationEnabled(userIdentifier, installFlags)) { 10052 final Intent verification = new Intent( 10053 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 10054 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 10055 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 10056 PACKAGE_MIME_TYPE); 10057 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 10058 10059 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 10060 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 10061 0 /* TODO: Which userId? */); 10062 10063 if (DEBUG_VERIFY) { 10064 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 10065 + verification.toString() + " with " + pkgLite.verifiers.length 10066 + " optional verifiers"); 10067 } 10068 10069 final int verificationId = mPendingVerificationToken++; 10070 10071 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 10072 10073 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 10074 installerPackageName); 10075 10076 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 10077 installFlags); 10078 10079 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 10080 pkgLite.packageName); 10081 10082 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 10083 pkgLite.versionCode); 10084 10085 if (verificationParams != null) { 10086 if (verificationParams.getVerificationURI() != null) { 10087 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 10088 verificationParams.getVerificationURI()); 10089 } 10090 if (verificationParams.getOriginatingURI() != null) { 10091 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 10092 verificationParams.getOriginatingURI()); 10093 } 10094 if (verificationParams.getReferrer() != null) { 10095 verification.putExtra(Intent.EXTRA_REFERRER, 10096 verificationParams.getReferrer()); 10097 } 10098 if (verificationParams.getOriginatingUid() >= 0) { 10099 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 10100 verificationParams.getOriginatingUid()); 10101 } 10102 if (verificationParams.getInstallerUid() >= 0) { 10103 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 10104 verificationParams.getInstallerUid()); 10105 } 10106 } 10107 10108 final PackageVerificationState verificationState = new PackageVerificationState( 10109 requiredUid, args); 10110 10111 mPendingVerification.append(verificationId, verificationState); 10112 10113 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 10114 receivers, verificationState); 10115 10116 /* 10117 * If any sufficient verifiers were listed in the package 10118 * manifest, attempt to ask them. 10119 */ 10120 if (sufficientVerifiers != null) { 10121 final int N = sufficientVerifiers.size(); 10122 if (N == 0) { 10123 Slog.i(TAG, "Additional verifiers required, but none installed."); 10124 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 10125 } else { 10126 for (int i = 0; i < N; i++) { 10127 final ComponentName verifierComponent = sufficientVerifiers.get(i); 10128 10129 final Intent sufficientIntent = new Intent(verification); 10130 sufficientIntent.setComponent(verifierComponent); 10131 10132 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 10133 } 10134 } 10135 } 10136 10137 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 10138 mRequiredVerifierPackage, receivers); 10139 if (ret == PackageManager.INSTALL_SUCCEEDED 10140 && mRequiredVerifierPackage != null) { 10141 /* 10142 * Send the intent to the required verification agent, 10143 * but only start the verification timeout after the 10144 * target BroadcastReceivers have run. 10145 */ 10146 verification.setComponent(requiredVerifierComponent); 10147 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 10148 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10149 new BroadcastReceiver() { 10150 @Override 10151 public void onReceive(Context context, Intent intent) { 10152 final Message msg = mHandler 10153 .obtainMessage(CHECK_PENDING_VERIFICATION); 10154 msg.arg1 = verificationId; 10155 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 10156 } 10157 }, null, 0, null, null); 10158 10159 /* 10160 * We don't want the copy to proceed until verification 10161 * succeeds, so null out this field. 10162 */ 10163 mArgs = null; 10164 } 10165 } else { 10166 /* 10167 * No package verification is enabled, so immediately start 10168 * the remote call to initiate copy using temporary file. 10169 */ 10170 ret = args.copyApk(mContainerService, true); 10171 } 10172 } 10173 10174 mRet = ret; 10175 } 10176 10177 @Override 10178 void handleReturnCode() { 10179 // If mArgs is null, then MCS couldn't be reached. When it 10180 // reconnects, it will try again to install. At that point, this 10181 // will succeed. 10182 if (mArgs != null) { 10183 processPendingInstall(mArgs, mRet); 10184 } 10185 } 10186 10187 @Override 10188 void handleServiceError() { 10189 mArgs = createInstallArgs(this); 10190 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10191 } 10192 10193 public boolean isForwardLocked() { 10194 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10195 } 10196 } 10197 10198 /** 10199 * Used during creation of InstallArgs 10200 * 10201 * @param installFlags package installation flags 10202 * @return true if should be installed on external storage 10203 */ 10204 private static boolean installOnExternalAsec(int installFlags) { 10205 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 10206 return false; 10207 } 10208 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 10209 return true; 10210 } 10211 return false; 10212 } 10213 10214 /** 10215 * Used during creation of InstallArgs 10216 * 10217 * @param installFlags package installation flags 10218 * @return true if should be installed as forward locked 10219 */ 10220 private static boolean installForwardLocked(int installFlags) { 10221 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10222 } 10223 10224 private InstallArgs createInstallArgs(InstallParams params) { 10225 if (params.move != null) { 10226 return new MoveInstallArgs(params); 10227 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 10228 return new AsecInstallArgs(params); 10229 } else { 10230 return new FileInstallArgs(params); 10231 } 10232 } 10233 10234 /** 10235 * Create args that describe an existing installed package. Typically used 10236 * when cleaning up old installs, or used as a move source. 10237 */ 10238 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 10239 String resourcePath, String[] instructionSets) { 10240 final boolean isInAsec; 10241 if (installOnExternalAsec(installFlags)) { 10242 /* Apps on SD card are always in ASEC containers. */ 10243 isInAsec = true; 10244 } else if (installForwardLocked(installFlags) 10245 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 10246 /* 10247 * Forward-locked apps are only in ASEC containers if they're the 10248 * new style 10249 */ 10250 isInAsec = true; 10251 } else { 10252 isInAsec = false; 10253 } 10254 10255 if (isInAsec) { 10256 return new AsecInstallArgs(codePath, instructionSets, 10257 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 10258 } else { 10259 return new FileInstallArgs(codePath, resourcePath, instructionSets); 10260 } 10261 } 10262 10263 static abstract class InstallArgs { 10264 /** @see InstallParams#origin */ 10265 final OriginInfo origin; 10266 /** @see InstallParams#move */ 10267 final MoveInfo move; 10268 10269 final IPackageInstallObserver2 observer; 10270 // Always refers to PackageManager flags only 10271 final int installFlags; 10272 final String installerPackageName; 10273 final String volumeUuid; 10274 final ManifestDigest manifestDigest; 10275 final UserHandle user; 10276 final String abiOverride; 10277 10278 // The list of instruction sets supported by this app. This is currently 10279 // only used during the rmdex() phase to clean up resources. We can get rid of this 10280 // if we move dex files under the common app path. 10281 /* nullable */ String[] instructionSets; 10282 10283 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 10284 int installFlags, String installerPackageName, String volumeUuid, 10285 ManifestDigest manifestDigest, UserHandle user, String[] instructionSets, 10286 String abiOverride) { 10287 this.origin = origin; 10288 this.move = move; 10289 this.installFlags = installFlags; 10290 this.observer = observer; 10291 this.installerPackageName = installerPackageName; 10292 this.volumeUuid = volumeUuid; 10293 this.manifestDigest = manifestDigest; 10294 this.user = user; 10295 this.instructionSets = instructionSets; 10296 this.abiOverride = abiOverride; 10297 } 10298 10299 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 10300 abstract int doPreInstall(int status); 10301 10302 /** 10303 * Rename package into final resting place. All paths on the given 10304 * scanned package should be updated to reflect the rename. 10305 */ 10306 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 10307 abstract int doPostInstall(int status, int uid); 10308 10309 /** @see PackageSettingBase#codePathString */ 10310 abstract String getCodePath(); 10311 /** @see PackageSettingBase#resourcePathString */ 10312 abstract String getResourcePath(); 10313 10314 // Need installer lock especially for dex file removal. 10315 abstract void cleanUpResourcesLI(); 10316 abstract boolean doPostDeleteLI(boolean delete); 10317 10318 /** 10319 * Called before the source arguments are copied. This is used mostly 10320 * for MoveParams when it needs to read the source file to put it in the 10321 * destination. 10322 */ 10323 int doPreCopy() { 10324 return PackageManager.INSTALL_SUCCEEDED; 10325 } 10326 10327 /** 10328 * Called after the source arguments are copied. This is used mostly for 10329 * MoveParams when it needs to read the source file to put it in the 10330 * destination. 10331 * 10332 * @return 10333 */ 10334 int doPostCopy(int uid) { 10335 return PackageManager.INSTALL_SUCCEEDED; 10336 } 10337 10338 protected boolean isFwdLocked() { 10339 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 10340 } 10341 10342 protected boolean isExternalAsec() { 10343 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 10344 } 10345 10346 UserHandle getUser() { 10347 return user; 10348 } 10349 } 10350 10351 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 10352 if (!allCodePaths.isEmpty()) { 10353 if (instructionSets == null) { 10354 throw new IllegalStateException("instructionSet == null"); 10355 } 10356 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10357 for (String codePath : allCodePaths) { 10358 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10359 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 10360 if (retCode < 0) { 10361 Slog.w(TAG, "Couldn't remove dex file for package: " 10362 + " at location " + codePath + ", retcode=" + retCode); 10363 // we don't consider this to be a failure of the core package deletion 10364 } 10365 } 10366 } 10367 } 10368 } 10369 10370 /** 10371 * Logic to handle installation of non-ASEC applications, including copying 10372 * and renaming logic. 10373 */ 10374 class FileInstallArgs extends InstallArgs { 10375 private File codeFile; 10376 private File resourceFile; 10377 10378 // Example topology: 10379 // /data/app/com.example/base.apk 10380 // /data/app/com.example/split_foo.apk 10381 // /data/app/com.example/lib/arm/libfoo.so 10382 // /data/app/com.example/lib/arm64/libfoo.so 10383 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 10384 10385 /** New install */ 10386 FileInstallArgs(InstallParams params) { 10387 super(params.origin, params.move, params.observer, params.installFlags, 10388 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10389 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10390 if (isFwdLocked()) { 10391 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 10392 } 10393 } 10394 10395 /** Existing install */ 10396 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 10397 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets, 10398 null); 10399 this.codeFile = (codePath != null) ? new File(codePath) : null; 10400 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 10401 } 10402 10403 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10404 if (origin.staged) { 10405 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 10406 codeFile = origin.file; 10407 resourceFile = origin.file; 10408 return PackageManager.INSTALL_SUCCEEDED; 10409 } 10410 10411 try { 10412 final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid); 10413 codeFile = tempDir; 10414 resourceFile = tempDir; 10415 } catch (IOException e) { 10416 Slog.w(TAG, "Failed to create copy file: " + e); 10417 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10418 } 10419 10420 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 10421 @Override 10422 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 10423 if (!FileUtils.isValidExtFilename(name)) { 10424 throw new IllegalArgumentException("Invalid filename: " + name); 10425 } 10426 try { 10427 final File file = new File(codeFile, name); 10428 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 10429 O_RDWR | O_CREAT, 0644); 10430 Os.chmod(file.getAbsolutePath(), 0644); 10431 return new ParcelFileDescriptor(fd); 10432 } catch (ErrnoException e) { 10433 throw new RemoteException("Failed to open: " + e.getMessage()); 10434 } 10435 } 10436 }; 10437 10438 int ret = PackageManager.INSTALL_SUCCEEDED; 10439 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 10440 if (ret != PackageManager.INSTALL_SUCCEEDED) { 10441 Slog.e(TAG, "Failed to copy package"); 10442 return ret; 10443 } 10444 10445 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 10446 NativeLibraryHelper.Handle handle = null; 10447 try { 10448 handle = NativeLibraryHelper.Handle.create(codeFile); 10449 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 10450 abiOverride); 10451 } catch (IOException e) { 10452 Slog.e(TAG, "Copying native libraries failed", e); 10453 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10454 } finally { 10455 IoUtils.closeQuietly(handle); 10456 } 10457 10458 return ret; 10459 } 10460 10461 int doPreInstall(int status) { 10462 if (status != PackageManager.INSTALL_SUCCEEDED) { 10463 cleanUp(); 10464 } 10465 return status; 10466 } 10467 10468 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10469 if (status != PackageManager.INSTALL_SUCCEEDED) { 10470 cleanUp(); 10471 return false; 10472 } 10473 10474 final File targetDir = codeFile.getParentFile(); 10475 final File beforeCodeFile = codeFile; 10476 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 10477 10478 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 10479 try { 10480 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 10481 } catch (ErrnoException e) { 10482 Slog.w(TAG, "Failed to rename", e); 10483 return false; 10484 } 10485 10486 if (!SELinux.restoreconRecursive(afterCodeFile)) { 10487 Slog.w(TAG, "Failed to restorecon"); 10488 return false; 10489 } 10490 10491 // Reflect the rename internally 10492 codeFile = afterCodeFile; 10493 resourceFile = afterCodeFile; 10494 10495 // Reflect the rename in scanned details 10496 pkg.codePath = afterCodeFile.getAbsolutePath(); 10497 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10498 pkg.baseCodePath); 10499 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10500 pkg.splitCodePaths); 10501 10502 // Reflect the rename in app info 10503 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10504 pkg.applicationInfo.setCodePath(pkg.codePath); 10505 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10506 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10507 pkg.applicationInfo.setResourcePath(pkg.codePath); 10508 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10509 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10510 10511 return true; 10512 } 10513 10514 int doPostInstall(int status, int uid) { 10515 if (status != PackageManager.INSTALL_SUCCEEDED) { 10516 cleanUp(); 10517 } 10518 return status; 10519 } 10520 10521 @Override 10522 String getCodePath() { 10523 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10524 } 10525 10526 @Override 10527 String getResourcePath() { 10528 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10529 } 10530 10531 private boolean cleanUp() { 10532 if (codeFile == null || !codeFile.exists()) { 10533 return false; 10534 } 10535 10536 if (codeFile.isDirectory()) { 10537 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10538 } else { 10539 codeFile.delete(); 10540 } 10541 10542 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10543 resourceFile.delete(); 10544 } 10545 10546 return true; 10547 } 10548 10549 void cleanUpResourcesLI() { 10550 // Try enumerating all code paths before deleting 10551 List<String> allCodePaths = Collections.EMPTY_LIST; 10552 if (codeFile != null && codeFile.exists()) { 10553 try { 10554 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10555 allCodePaths = pkg.getAllCodePaths(); 10556 } catch (PackageParserException e) { 10557 // Ignored; we tried our best 10558 } 10559 } 10560 10561 cleanUp(); 10562 removeDexFiles(allCodePaths, instructionSets); 10563 } 10564 10565 boolean doPostDeleteLI(boolean delete) { 10566 // XXX err, shouldn't we respect the delete flag? 10567 cleanUpResourcesLI(); 10568 return true; 10569 } 10570 } 10571 10572 private boolean isAsecExternal(String cid) { 10573 final String asecPath = PackageHelper.getSdFilesystem(cid); 10574 return !asecPath.startsWith(mAsecInternalPath); 10575 } 10576 10577 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 10578 PackageManagerException { 10579 if (copyRet < 0) { 10580 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 10581 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 10582 throw new PackageManagerException(copyRet, message); 10583 } 10584 } 10585 } 10586 10587 /** 10588 * Extract the MountService "container ID" from the full code path of an 10589 * .apk. 10590 */ 10591 static String cidFromCodePath(String fullCodePath) { 10592 int eidx = fullCodePath.lastIndexOf("/"); 10593 String subStr1 = fullCodePath.substring(0, eidx); 10594 int sidx = subStr1.lastIndexOf("/"); 10595 return subStr1.substring(sidx+1, eidx); 10596 } 10597 10598 /** 10599 * Logic to handle installation of ASEC applications, including copying and 10600 * renaming logic. 10601 */ 10602 class AsecInstallArgs extends InstallArgs { 10603 static final String RES_FILE_NAME = "pkg.apk"; 10604 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 10605 10606 String cid; 10607 String packagePath; 10608 String resourcePath; 10609 10610 /** New install */ 10611 AsecInstallArgs(InstallParams params) { 10612 super(params.origin, params.move, params.observer, params.installFlags, 10613 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10614 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10615 } 10616 10617 /** Existing install */ 10618 AsecInstallArgs(String fullCodePath, String[] instructionSets, 10619 boolean isExternal, boolean isForwardLocked) { 10620 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 10621 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10622 instructionSets, null); 10623 // Hackily pretend we're still looking at a full code path 10624 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 10625 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 10626 } 10627 10628 // Extract cid from fullCodePath 10629 int eidx = fullCodePath.lastIndexOf("/"); 10630 String subStr1 = fullCodePath.substring(0, eidx); 10631 int sidx = subStr1.lastIndexOf("/"); 10632 cid = subStr1.substring(sidx+1, eidx); 10633 setMountPath(subStr1); 10634 } 10635 10636 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 10637 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 10638 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null, 10639 instructionSets, null); 10640 this.cid = cid; 10641 setMountPath(PackageHelper.getSdDir(cid)); 10642 } 10643 10644 void createCopyFile() { 10645 cid = mInstallerService.allocateExternalStageCidLegacy(); 10646 } 10647 10648 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 10649 if (origin.staged) { 10650 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 10651 cid = origin.cid; 10652 setMountPath(PackageHelper.getSdDir(cid)); 10653 return PackageManager.INSTALL_SUCCEEDED; 10654 } 10655 10656 if (temp) { 10657 createCopyFile(); 10658 } else { 10659 /* 10660 * Pre-emptively destroy the container since it's destroyed if 10661 * copying fails due to it existing anyway. 10662 */ 10663 PackageHelper.destroySdDir(cid); 10664 } 10665 10666 final String newMountPath = imcs.copyPackageToContainer( 10667 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 10668 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 10669 10670 if (newMountPath != null) { 10671 setMountPath(newMountPath); 10672 return PackageManager.INSTALL_SUCCEEDED; 10673 } else { 10674 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10675 } 10676 } 10677 10678 @Override 10679 String getCodePath() { 10680 return packagePath; 10681 } 10682 10683 @Override 10684 String getResourcePath() { 10685 return resourcePath; 10686 } 10687 10688 int doPreInstall(int status) { 10689 if (status != PackageManager.INSTALL_SUCCEEDED) { 10690 // Destroy container 10691 PackageHelper.destroySdDir(cid); 10692 } else { 10693 boolean mounted = PackageHelper.isContainerMounted(cid); 10694 if (!mounted) { 10695 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 10696 Process.SYSTEM_UID); 10697 if (newMountPath != null) { 10698 setMountPath(newMountPath); 10699 } else { 10700 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10701 } 10702 } 10703 } 10704 return status; 10705 } 10706 10707 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10708 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 10709 String newMountPath = null; 10710 if (PackageHelper.isContainerMounted(cid)) { 10711 // Unmount the container 10712 if (!PackageHelper.unMountSdDir(cid)) { 10713 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 10714 return false; 10715 } 10716 } 10717 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10718 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 10719 " which might be stale. Will try to clean up."); 10720 // Clean up the stale container and proceed to recreate. 10721 if (!PackageHelper.destroySdDir(newCacheId)) { 10722 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 10723 return false; 10724 } 10725 // Successfully cleaned up stale container. Try to rename again. 10726 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 10727 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 10728 + " inspite of cleaning it up."); 10729 return false; 10730 } 10731 } 10732 if (!PackageHelper.isContainerMounted(newCacheId)) { 10733 Slog.w(TAG, "Mounting container " + newCacheId); 10734 newMountPath = PackageHelper.mountSdDir(newCacheId, 10735 getEncryptKey(), Process.SYSTEM_UID); 10736 } else { 10737 newMountPath = PackageHelper.getSdDir(newCacheId); 10738 } 10739 if (newMountPath == null) { 10740 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 10741 return false; 10742 } 10743 Log.i(TAG, "Succesfully renamed " + cid + 10744 " to " + newCacheId + 10745 " at new path: " + newMountPath); 10746 cid = newCacheId; 10747 10748 final File beforeCodeFile = new File(packagePath); 10749 setMountPath(newMountPath); 10750 final File afterCodeFile = new File(packagePath); 10751 10752 // Reflect the rename in scanned details 10753 pkg.codePath = afterCodeFile.getAbsolutePath(); 10754 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10755 pkg.baseCodePath); 10756 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 10757 pkg.splitCodePaths); 10758 10759 // Reflect the rename in app info 10760 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10761 pkg.applicationInfo.setCodePath(pkg.codePath); 10762 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10763 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10764 pkg.applicationInfo.setResourcePath(pkg.codePath); 10765 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10766 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10767 10768 return true; 10769 } 10770 10771 private void setMountPath(String mountPath) { 10772 final File mountFile = new File(mountPath); 10773 10774 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 10775 if (monolithicFile.exists()) { 10776 packagePath = monolithicFile.getAbsolutePath(); 10777 if (isFwdLocked()) { 10778 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 10779 } else { 10780 resourcePath = packagePath; 10781 } 10782 } else { 10783 packagePath = mountFile.getAbsolutePath(); 10784 resourcePath = packagePath; 10785 } 10786 } 10787 10788 int doPostInstall(int status, int uid) { 10789 if (status != PackageManager.INSTALL_SUCCEEDED) { 10790 cleanUp(); 10791 } else { 10792 final int groupOwner; 10793 final String protectedFile; 10794 if (isFwdLocked()) { 10795 groupOwner = UserHandle.getSharedAppGid(uid); 10796 protectedFile = RES_FILE_NAME; 10797 } else { 10798 groupOwner = -1; 10799 protectedFile = null; 10800 } 10801 10802 if (uid < Process.FIRST_APPLICATION_UID 10803 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 10804 Slog.e(TAG, "Failed to finalize " + cid); 10805 PackageHelper.destroySdDir(cid); 10806 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10807 } 10808 10809 boolean mounted = PackageHelper.isContainerMounted(cid); 10810 if (!mounted) { 10811 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 10812 } 10813 } 10814 return status; 10815 } 10816 10817 private void cleanUp() { 10818 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 10819 10820 // Destroy secure container 10821 PackageHelper.destroySdDir(cid); 10822 } 10823 10824 private List<String> getAllCodePaths() { 10825 final File codeFile = new File(getCodePath()); 10826 if (codeFile != null && codeFile.exists()) { 10827 try { 10828 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 10829 return pkg.getAllCodePaths(); 10830 } catch (PackageParserException e) { 10831 // Ignored; we tried our best 10832 } 10833 } 10834 return Collections.EMPTY_LIST; 10835 } 10836 10837 void cleanUpResourcesLI() { 10838 // Enumerate all code paths before deleting 10839 cleanUpResourcesLI(getAllCodePaths()); 10840 } 10841 10842 private void cleanUpResourcesLI(List<String> allCodePaths) { 10843 cleanUp(); 10844 removeDexFiles(allCodePaths, instructionSets); 10845 } 10846 10847 String getPackageName() { 10848 return getAsecPackageName(cid); 10849 } 10850 10851 boolean doPostDeleteLI(boolean delete) { 10852 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 10853 final List<String> allCodePaths = getAllCodePaths(); 10854 boolean mounted = PackageHelper.isContainerMounted(cid); 10855 if (mounted) { 10856 // Unmount first 10857 if (PackageHelper.unMountSdDir(cid)) { 10858 mounted = false; 10859 } 10860 } 10861 if (!mounted && delete) { 10862 cleanUpResourcesLI(allCodePaths); 10863 } 10864 return !mounted; 10865 } 10866 10867 @Override 10868 int doPreCopy() { 10869 if (isFwdLocked()) { 10870 if (!PackageHelper.fixSdPermissions(cid, 10871 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10872 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10873 } 10874 } 10875 10876 return PackageManager.INSTALL_SUCCEEDED; 10877 } 10878 10879 @Override 10880 int doPostCopy(int uid) { 10881 if (isFwdLocked()) { 10882 if (uid < Process.FIRST_APPLICATION_UID 10883 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10884 RES_FILE_NAME)) { 10885 Slog.e(TAG, "Failed to finalize " + cid); 10886 PackageHelper.destroySdDir(cid); 10887 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10888 } 10889 } 10890 10891 return PackageManager.INSTALL_SUCCEEDED; 10892 } 10893 } 10894 10895 /** 10896 * Logic to handle movement of existing installed applications. 10897 */ 10898 class MoveInstallArgs extends InstallArgs { 10899 private File codeFile; 10900 private File resourceFile; 10901 10902 /** New install */ 10903 MoveInstallArgs(InstallParams params) { 10904 super(params.origin, params.move, params.observer, params.installFlags, 10905 params.installerPackageName, params.volumeUuid, params.getManifestDigest(), 10906 params.getUser(), null /* instruction sets */, params.packageAbiOverride); 10907 } 10908 10909 int copyApk(IMediaContainerService imcs, boolean temp) { 10910 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 10911 + move.fromUuid + " to " + move.toUuid); 10912 synchronized (mInstaller) { 10913 if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 10914 move.dataAppName, move.appId, move.seinfo) != 0) { 10915 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 10916 } 10917 } 10918 10919 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 10920 resourceFile = codeFile; 10921 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 10922 10923 return PackageManager.INSTALL_SUCCEEDED; 10924 } 10925 10926 int doPreInstall(int status) { 10927 if (status != PackageManager.INSTALL_SUCCEEDED) { 10928 cleanUp(); 10929 } 10930 return status; 10931 } 10932 10933 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 10934 if (status != PackageManager.INSTALL_SUCCEEDED) { 10935 cleanUp(); 10936 return false; 10937 } 10938 10939 // Reflect the move in app info 10940 pkg.applicationInfo.volumeUuid = pkg.volumeUuid; 10941 pkg.applicationInfo.setCodePath(pkg.codePath); 10942 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 10943 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 10944 pkg.applicationInfo.setResourcePath(pkg.codePath); 10945 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 10946 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 10947 10948 return true; 10949 } 10950 10951 int doPostInstall(int status, int uid) { 10952 if (status != PackageManager.INSTALL_SUCCEEDED) { 10953 cleanUp(); 10954 } 10955 return status; 10956 } 10957 10958 @Override 10959 String getCodePath() { 10960 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 10961 } 10962 10963 @Override 10964 String getResourcePath() { 10965 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 10966 } 10967 10968 private boolean cleanUp() { 10969 if (codeFile == null || !codeFile.exists()) { 10970 return false; 10971 } 10972 10973 if (codeFile.isDirectory()) { 10974 mInstaller.rmPackageDir(codeFile.getAbsolutePath()); 10975 } else { 10976 codeFile.delete(); 10977 } 10978 10979 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 10980 resourceFile.delete(); 10981 } 10982 10983 return true; 10984 } 10985 10986 void cleanUpResourcesLI() { 10987 cleanUp(); 10988 } 10989 10990 boolean doPostDeleteLI(boolean delete) { 10991 // XXX err, shouldn't we respect the delete flag? 10992 cleanUpResourcesLI(); 10993 return true; 10994 } 10995 } 10996 10997 static String getAsecPackageName(String packageCid) { 10998 int idx = packageCid.lastIndexOf("-"); 10999 if (idx == -1) { 11000 return packageCid; 11001 } 11002 return packageCid.substring(0, idx); 11003 } 11004 11005 // Utility method used to create code paths based on package name and available index. 11006 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 11007 String idxStr = ""; 11008 int idx = 1; 11009 // Fall back to default value of idx=1 if prefix is not 11010 // part of oldCodePath 11011 if (oldCodePath != null) { 11012 String subStr = oldCodePath; 11013 // Drop the suffix right away 11014 if (suffix != null && subStr.endsWith(suffix)) { 11015 subStr = subStr.substring(0, subStr.length() - suffix.length()); 11016 } 11017 // If oldCodePath already contains prefix find out the 11018 // ending index to either increment or decrement. 11019 int sidx = subStr.lastIndexOf(prefix); 11020 if (sidx != -1) { 11021 subStr = subStr.substring(sidx + prefix.length()); 11022 if (subStr != null) { 11023 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 11024 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 11025 } 11026 try { 11027 idx = Integer.parseInt(subStr); 11028 if (idx <= 1) { 11029 idx++; 11030 } else { 11031 idx--; 11032 } 11033 } catch(NumberFormatException e) { 11034 } 11035 } 11036 } 11037 } 11038 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 11039 return prefix + idxStr; 11040 } 11041 11042 private File getNextCodePath(File targetDir, String packageName) { 11043 int suffix = 1; 11044 File result; 11045 do { 11046 result = new File(targetDir, packageName + "-" + suffix); 11047 suffix++; 11048 } while (result.exists()); 11049 return result; 11050 } 11051 11052 // Utility method that returns the relative package path with respect 11053 // to the installation directory. Like say for /data/data/com.test-1.apk 11054 // string com.test-1 is returned. 11055 static String deriveCodePathName(String codePath) { 11056 if (codePath == null) { 11057 return null; 11058 } 11059 final File codeFile = new File(codePath); 11060 final String name = codeFile.getName(); 11061 if (codeFile.isDirectory()) { 11062 return name; 11063 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 11064 final int lastDot = name.lastIndexOf('.'); 11065 return name.substring(0, lastDot); 11066 } else { 11067 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 11068 return null; 11069 } 11070 } 11071 11072 class PackageInstalledInfo { 11073 String name; 11074 int uid; 11075 // The set of users that originally had this package installed. 11076 int[] origUsers; 11077 // The set of users that now have this package installed. 11078 int[] newUsers; 11079 PackageParser.Package pkg; 11080 int returnCode; 11081 String returnMsg; 11082 PackageRemovedInfo removedInfo; 11083 11084 public void setError(int code, String msg) { 11085 returnCode = code; 11086 returnMsg = msg; 11087 Slog.w(TAG, msg); 11088 } 11089 11090 public void setError(String msg, PackageParserException e) { 11091 returnCode = e.error; 11092 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11093 Slog.w(TAG, msg, e); 11094 } 11095 11096 public void setError(String msg, PackageManagerException e) { 11097 returnCode = e.error; 11098 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 11099 Slog.w(TAG, msg, e); 11100 } 11101 11102 // In some error cases we want to convey more info back to the observer 11103 String origPackage; 11104 String origPermission; 11105 } 11106 11107 /* 11108 * Install a non-existing package. 11109 */ 11110 private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11111 UserHandle user, String installerPackageName, String volumeUuid, 11112 PackageInstalledInfo res) { 11113 // Remember this for later, in case we need to rollback this install 11114 String pkgName = pkg.packageName; 11115 11116 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 11117 final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName, 11118 UserHandle.USER_OWNER).exists(); 11119 synchronized(mPackages) { 11120 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 11121 // A package with the same name is already installed, though 11122 // it has been renamed to an older name. The package we 11123 // are trying to install should be installed as an update to 11124 // the existing one, but that has not been requested, so bail. 11125 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11126 + " without first uninstalling package running as " 11127 + mSettings.mRenamedPackages.get(pkgName)); 11128 return; 11129 } 11130 if (mPackages.containsKey(pkgName)) { 11131 // Don't allow installation over an existing package with the same name. 11132 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 11133 + " without first uninstalling."); 11134 return; 11135 } 11136 } 11137 11138 try { 11139 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 11140 System.currentTimeMillis(), user); 11141 11142 updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user); 11143 // delete the partially installed application. the data directory will have to be 11144 // restored if it was already existing 11145 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11146 // remove package from internal structures. Note that we want deletePackageX to 11147 // delete the package data and cache directories that it created in 11148 // scanPackageLocked, unless those directories existed before we even tried to 11149 // install. 11150 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 11151 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 11152 res.removedInfo, true); 11153 } 11154 11155 } catch (PackageManagerException e) { 11156 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11157 } 11158 } 11159 11160 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 11161 // Can't rotate keys during boot or if sharedUser. 11162 if (oldPs == null || (scanFlags&SCAN_BOOTING) != 0 || oldPs.sharedUser != null 11163 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 11164 return false; 11165 } 11166 // app is using upgradeKeySets; make sure all are valid 11167 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11168 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 11169 for (int i = 0; i < upgradeKeySets.length; i++) { 11170 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 11171 Slog.wtf(TAG, "Package " 11172 + (oldPs.name != null ? oldPs.name : "<null>") 11173 + " contains upgrade-key-set reference to unknown key-set: " 11174 + upgradeKeySets[i] 11175 + " reverting to signatures check."); 11176 return false; 11177 } 11178 } 11179 return true; 11180 } 11181 11182 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 11183 // Upgrade keysets are being used. Determine if new package has a superset of the 11184 // required keys. 11185 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 11186 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11187 for (int i = 0; i < upgradeKeySets.length; i++) { 11188 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 11189 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 11190 return true; 11191 } 11192 } 11193 return false; 11194 } 11195 11196 private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags, 11197 UserHandle user, String installerPackageName, String volumeUuid, 11198 PackageInstalledInfo res) { 11199 final PackageParser.Package oldPackage; 11200 final String pkgName = pkg.packageName; 11201 final int[] allUsers; 11202 final boolean[] perUserInstalled; 11203 final boolean weFroze; 11204 11205 // First find the old package info and check signatures 11206 synchronized(mPackages) { 11207 oldPackage = mPackages.get(pkgName); 11208 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 11209 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11210 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11211 if(!checkUpgradeKeySetLP(ps, pkg)) { 11212 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11213 "New package not signed by keys specified by upgrade-keysets: " 11214 + pkgName); 11215 return; 11216 } 11217 } else { 11218 // default to original signature matching 11219 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 11220 != PackageManager.SIGNATURE_MATCH) { 11221 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 11222 "New package has a different signature: " + pkgName); 11223 return; 11224 } 11225 } 11226 11227 // In case of rollback, remember per-user/profile install state 11228 allUsers = sUserManager.getUserIds(); 11229 perUserInstalled = new boolean[allUsers.length]; 11230 for (int i = 0; i < allUsers.length; i++) { 11231 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 11232 } 11233 11234 // Mark the app as frozen to prevent launching during the upgrade 11235 // process, and then kill all running instances 11236 if (!ps.frozen) { 11237 ps.frozen = true; 11238 weFroze = true; 11239 } else { 11240 weFroze = false; 11241 } 11242 } 11243 11244 // Now that we're guarded by frozen state, kill app during upgrade 11245 killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg"); 11246 11247 try { 11248 boolean sysPkg = (isSystemApp(oldPackage)); 11249 if (sysPkg) { 11250 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11251 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11252 } else { 11253 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 11254 user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res); 11255 } 11256 } finally { 11257 // Regardless of success or failure of upgrade steps above, always 11258 // unfreeze the package if we froze it 11259 if (weFroze) { 11260 unfreezePackage(pkgName); 11261 } 11262 } 11263 } 11264 11265 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 11266 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11267 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11268 String volumeUuid, PackageInstalledInfo res) { 11269 String pkgName = deletedPackage.packageName; 11270 boolean deletedPkg = true; 11271 boolean updatedSettings = false; 11272 11273 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 11274 + deletedPackage); 11275 long origUpdateTime; 11276 if (pkg.mExtras != null) { 11277 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 11278 } else { 11279 origUpdateTime = 0; 11280 } 11281 11282 // First delete the existing package while retaining the data directory 11283 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 11284 res.removedInfo, true)) { 11285 // If the existing package wasn't successfully deleted 11286 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 11287 deletedPkg = false; 11288 } else { 11289 // Successfully deleted the old package; proceed with replace. 11290 11291 // If deleted package lived in a container, give users a chance to 11292 // relinquish resources before killing. 11293 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 11294 if (DEBUG_INSTALL) { 11295 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 11296 } 11297 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 11298 final ArrayList<String> pkgList = new ArrayList<String>(1); 11299 pkgList.add(deletedPackage.applicationInfo.packageName); 11300 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 11301 } 11302 11303 deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName); 11304 try { 11305 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 11306 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 11307 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11308 perUserInstalled, res, user); 11309 updatedSettings = true; 11310 } catch (PackageManagerException e) { 11311 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11312 } 11313 } 11314 11315 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11316 // remove package from internal structures. Note that we want deletePackageX to 11317 // delete the package data and cache directories that it created in 11318 // scanPackageLocked, unless those directories existed before we even tried to 11319 // install. 11320 if(updatedSettings) { 11321 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 11322 deletePackageLI( 11323 pkgName, null, true, allUsers, perUserInstalled, 11324 PackageManager.DELETE_KEEP_DATA, 11325 res.removedInfo, true); 11326 } 11327 // Since we failed to install the new package we need to restore the old 11328 // package that we deleted. 11329 if (deletedPkg) { 11330 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 11331 File restoreFile = new File(deletedPackage.codePath); 11332 // Parse old package 11333 boolean oldExternal = isExternal(deletedPackage); 11334 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 11335 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 11336 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11337 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 11338 try { 11339 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 11340 } catch (PackageManagerException e) { 11341 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 11342 + e.getMessage()); 11343 return; 11344 } 11345 // Restore of old package succeeded. Update permissions. 11346 // writer 11347 synchronized (mPackages) { 11348 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 11349 UPDATE_PERMISSIONS_ALL); 11350 // can downgrade to reader 11351 mSettings.writeLPr(); 11352 } 11353 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 11354 } 11355 } 11356 } 11357 11358 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 11359 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 11360 int[] allUsers, boolean[] perUserInstalled, String installerPackageName, 11361 String volumeUuid, PackageInstalledInfo res) { 11362 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 11363 + ", old=" + deletedPackage); 11364 boolean disabledSystem = false; 11365 boolean updatedSettings = false; 11366 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 11367 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 11368 != 0) { 11369 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11370 } 11371 String packageName = deletedPackage.packageName; 11372 if (packageName == null) { 11373 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11374 "Attempt to delete null packageName."); 11375 return; 11376 } 11377 PackageParser.Package oldPkg; 11378 PackageSetting oldPkgSetting; 11379 // reader 11380 synchronized (mPackages) { 11381 oldPkg = mPackages.get(packageName); 11382 oldPkgSetting = mSettings.mPackages.get(packageName); 11383 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 11384 (oldPkgSetting == null)) { 11385 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 11386 "Couldn't find package:" + packageName + " information"); 11387 return; 11388 } 11389 } 11390 11391 res.removedInfo.uid = oldPkg.applicationInfo.uid; 11392 res.removedInfo.removedPackage = packageName; 11393 // Remove existing system package 11394 removePackageLI(oldPkgSetting, true); 11395 // writer 11396 synchronized (mPackages) { 11397 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 11398 if (!disabledSystem && deletedPackage != null) { 11399 // We didn't need to disable the .apk as a current system package, 11400 // which means we are replacing another update that is already 11401 // installed. We need to make sure to delete the older one's .apk. 11402 res.removedInfo.args = createInstallArgsForExisting(0, 11403 deletedPackage.applicationInfo.getCodePath(), 11404 deletedPackage.applicationInfo.getResourcePath(), 11405 getAppDexInstructionSets(deletedPackage.applicationInfo)); 11406 } else { 11407 res.removedInfo.args = null; 11408 } 11409 } 11410 11411 // Successfully disabled the old package. Now proceed with re-installation 11412 deleteCodeCacheDirsLI(pkg.volumeUuid, packageName); 11413 11414 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11415 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11416 11417 PackageParser.Package newPackage = null; 11418 try { 11419 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 11420 if (newPackage.mExtras != null) { 11421 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 11422 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 11423 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 11424 11425 // is the update attempting to change shared user? that isn't going to work... 11426 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 11427 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 11428 "Forbidding shared user change from " + oldPkgSetting.sharedUser 11429 + " to " + newPkgSetting.sharedUser); 11430 updatedSettings = true; 11431 } 11432 } 11433 11434 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11435 updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers, 11436 perUserInstalled, res, user); 11437 updatedSettings = true; 11438 } 11439 11440 } catch (PackageManagerException e) { 11441 res.setError("Package couldn't be installed in " + pkg.codePath, e); 11442 } 11443 11444 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 11445 // Re installation failed. Restore old information 11446 // Remove new pkg information 11447 if (newPackage != null) { 11448 removeInstalledPackageLI(newPackage, true); 11449 } 11450 // Add back the old system package 11451 try { 11452 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 11453 } catch (PackageManagerException e) { 11454 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 11455 } 11456 // Restore the old system information in Settings 11457 synchronized (mPackages) { 11458 if (disabledSystem) { 11459 mSettings.enableSystemPackageLPw(packageName); 11460 } 11461 if (updatedSettings) { 11462 mSettings.setInstallerPackageName(packageName, 11463 oldPkgSetting.installerPackageName); 11464 } 11465 mSettings.writeLPr(); 11466 } 11467 } 11468 } 11469 11470 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 11471 String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res, 11472 UserHandle user) { 11473 String pkgName = newPackage.packageName; 11474 synchronized (mPackages) { 11475 //write settings. the installStatus will be incomplete at this stage. 11476 //note that the new package setting would have already been 11477 //added to mPackages. It hasn't been persisted yet. 11478 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 11479 mSettings.writeLPr(); 11480 } 11481 11482 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 11483 11484 synchronized (mPackages) { 11485 updatePermissionsLPw(newPackage.packageName, newPackage, 11486 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 11487 ? UPDATE_PERMISSIONS_ALL : 0)); 11488 // For system-bundled packages, we assume that installing an upgraded version 11489 // of the package implies that the user actually wants to run that new code, 11490 // so we enable the package. 11491 PackageSetting ps = mSettings.mPackages.get(pkgName); 11492 if (ps != null) { 11493 if (isSystemApp(newPackage)) { 11494 // NB: implicit assumption that system package upgrades apply to all users 11495 if (DEBUG_INSTALL) { 11496 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 11497 } 11498 if (res.origUsers != null) { 11499 for (int userHandle : res.origUsers) { 11500 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 11501 userHandle, installerPackageName); 11502 } 11503 } 11504 // Also convey the prior install/uninstall state 11505 if (allUsers != null && perUserInstalled != null) { 11506 for (int i = 0; i < allUsers.length; i++) { 11507 if (DEBUG_INSTALL) { 11508 Slog.d(TAG, " user " + allUsers[i] 11509 + " => " + perUserInstalled[i]); 11510 } 11511 ps.setInstalled(perUserInstalled[i], allUsers[i]); 11512 } 11513 // these install state changes will be persisted in the 11514 // upcoming call to mSettings.writeLPr(). 11515 } 11516 } 11517 // It's implied that when a user requests installation, they want the app to be 11518 // installed and enabled. 11519 int userId = user.getIdentifier(); 11520 if (userId != UserHandle.USER_ALL) { 11521 ps.setInstalled(true, userId); 11522 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 11523 } 11524 } 11525 res.name = pkgName; 11526 res.uid = newPackage.applicationInfo.uid; 11527 res.pkg = newPackage; 11528 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 11529 mSettings.setInstallerPackageName(pkgName, installerPackageName); 11530 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11531 //to update install status 11532 mSettings.writeLPr(); 11533 } 11534 } 11535 11536 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 11537 final int installFlags = args.installFlags; 11538 final String installerPackageName = args.installerPackageName; 11539 final String volumeUuid = args.volumeUuid; 11540 final File tmpPackageFile = new File(args.getCodePath()); 11541 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 11542 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 11543 || (args.volumeUuid != null)); 11544 boolean replace = false; 11545 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 11546 // Result object to be returned 11547 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 11548 11549 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 11550 // Retrieve PackageSettings and parse package 11551 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 11552 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 11553 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 11554 PackageParser pp = new PackageParser(); 11555 pp.setSeparateProcesses(mSeparateProcesses); 11556 pp.setDisplayMetrics(mMetrics); 11557 11558 final PackageParser.Package pkg; 11559 try { 11560 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 11561 } catch (PackageParserException e) { 11562 res.setError("Failed parse during installPackageLI", e); 11563 return; 11564 } 11565 11566 // Mark that we have an install time CPU ABI override. 11567 pkg.cpuAbiOverride = args.abiOverride; 11568 11569 String pkgName = res.name = pkg.packageName; 11570 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 11571 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 11572 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 11573 return; 11574 } 11575 } 11576 11577 try { 11578 pp.collectCertificates(pkg, parseFlags); 11579 pp.collectManifestDigest(pkg); 11580 } catch (PackageParserException e) { 11581 res.setError("Failed collect during installPackageLI", e); 11582 return; 11583 } 11584 11585 /* If the installer passed in a manifest digest, compare it now. */ 11586 if (args.manifestDigest != null) { 11587 if (DEBUG_INSTALL) { 11588 final String parsedManifest = pkg.manifestDigest == null ? "null" 11589 : pkg.manifestDigest.toString(); 11590 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 11591 + parsedManifest); 11592 } 11593 11594 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 11595 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 11596 return; 11597 } 11598 } else if (DEBUG_INSTALL) { 11599 final String parsedManifest = pkg.manifestDigest == null 11600 ? "null" : pkg.manifestDigest.toString(); 11601 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 11602 } 11603 11604 // Get rid of all references to package scan path via parser. 11605 pp = null; 11606 String oldCodePath = null; 11607 boolean systemApp = false; 11608 synchronized (mPackages) { 11609 // Check if installing already existing package 11610 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 11611 String oldName = mSettings.mRenamedPackages.get(pkgName); 11612 if (pkg.mOriginalPackages != null 11613 && pkg.mOriginalPackages.contains(oldName) 11614 && mPackages.containsKey(oldName)) { 11615 // This package is derived from an original package, 11616 // and this device has been updating from that original 11617 // name. We must continue using the original name, so 11618 // rename the new package here. 11619 pkg.setPackageName(oldName); 11620 pkgName = pkg.packageName; 11621 replace = true; 11622 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 11623 + oldName + " pkgName=" + pkgName); 11624 } else if (mPackages.containsKey(pkgName)) { 11625 // This package, under its official name, already exists 11626 // on the device; we should replace it. 11627 replace = true; 11628 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 11629 } 11630 11631 // Prevent apps opting out from runtime permissions 11632 if (replace) { 11633 PackageParser.Package oldPackage = mPackages.get(pkgName); 11634 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 11635 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 11636 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 11637 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 11638 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 11639 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 11640 + " doesn't support runtime permissions but the old" 11641 + " target SDK " + oldTargetSdk + " does."); 11642 return; 11643 } 11644 } 11645 } 11646 11647 PackageSetting ps = mSettings.mPackages.get(pkgName); 11648 if (ps != null) { 11649 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 11650 11651 // Quick sanity check that we're signed correctly if updating; 11652 // we'll check this again later when scanning, but we want to 11653 // bail early here before tripping over redefined permissions. 11654 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 11655 if (!checkUpgradeKeySetLP(ps, pkg)) { 11656 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 11657 + pkg.packageName + " upgrade keys do not match the " 11658 + "previously installed version"); 11659 return; 11660 } 11661 } else { 11662 try { 11663 verifySignaturesLP(ps, pkg); 11664 } catch (PackageManagerException e) { 11665 res.setError(e.error, e.getMessage()); 11666 return; 11667 } 11668 } 11669 11670 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 11671 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 11672 systemApp = (ps.pkg.applicationInfo.flags & 11673 ApplicationInfo.FLAG_SYSTEM) != 0; 11674 } 11675 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11676 } 11677 11678 // Check whether the newly-scanned package wants to define an already-defined perm 11679 int N = pkg.permissions.size(); 11680 for (int i = N-1; i >= 0; i--) { 11681 PackageParser.Permission perm = pkg.permissions.get(i); 11682 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 11683 if (bp != null) { 11684 // If the defining package is signed with our cert, it's okay. This 11685 // also includes the "updating the same package" case, of course. 11686 // "updating same package" could also involve key-rotation. 11687 final boolean sigsOk; 11688 if (bp.sourcePackage.equals(pkg.packageName) 11689 && (bp.packageSetting instanceof PackageSetting) 11690 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 11691 scanFlags))) { 11692 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 11693 } else { 11694 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 11695 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 11696 } 11697 if (!sigsOk) { 11698 // If the owning package is the system itself, we log but allow 11699 // install to proceed; we fail the install on all other permission 11700 // redefinitions. 11701 if (!bp.sourcePackage.equals("android")) { 11702 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 11703 + pkg.packageName + " attempting to redeclare permission " 11704 + perm.info.name + " already owned by " + bp.sourcePackage); 11705 res.origPermission = perm.info.name; 11706 res.origPackage = bp.sourcePackage; 11707 return; 11708 } else { 11709 Slog.w(TAG, "Package " + pkg.packageName 11710 + " attempting to redeclare system permission " 11711 + perm.info.name + "; ignoring new declaration"); 11712 pkg.permissions.remove(i); 11713 } 11714 } 11715 } 11716 } 11717 11718 } 11719 11720 if (systemApp && onExternal) { 11721 // Disable updates to system apps on sdcard 11722 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11723 "Cannot install updates to system apps on sdcard"); 11724 return; 11725 } 11726 11727 if (args.move != null) { 11728 // We did an in-place move, so dex is ready to roll 11729 scanFlags |= SCAN_NO_DEX; 11730 scanFlags |= SCAN_MOVE; 11731 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 11732 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 11733 scanFlags |= SCAN_NO_DEX; 11734 11735 try { 11736 derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride, 11737 true /* extract libs */); 11738 } catch (PackageManagerException pme) { 11739 Slog.e(TAG, "Error deriving application ABI", pme); 11740 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 11741 return; 11742 } 11743 11744 // Run dexopt before old package gets removed, to minimize time when app is unavailable 11745 int result = mPackageDexOptimizer 11746 .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */, 11747 false /* defer */, false /* inclDependencies */); 11748 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 11749 res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath); 11750 return; 11751 } 11752 } 11753 11754 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 11755 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 11756 return; 11757 } 11758 11759 startIntentFilterVerifications(args.user.getIdentifier(), pkg); 11760 11761 if (replace) { 11762 replacePackageLI(pkg, parseFlags, scanFlags, args.user, 11763 installerPackageName, volumeUuid, res); 11764 } else { 11765 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 11766 args.user, installerPackageName, volumeUuid, res); 11767 } 11768 synchronized (mPackages) { 11769 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11770 if (ps != null) { 11771 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 11772 } 11773 } 11774 } 11775 11776 private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) { 11777 if (mIntentFilterVerifierComponent == null) { 11778 Slog.w(TAG, "No IntentFilter verification will not be done as " 11779 + "there is no IntentFilterVerifier available!"); 11780 return; 11781 } 11782 11783 final int verifierUid = getPackageUid( 11784 mIntentFilterVerifierComponent.getPackageName(), 11785 (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId); 11786 11787 mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS); 11788 final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 11789 msg.obj = pkg; 11790 msg.arg1 = userId; 11791 msg.arg2 = verifierUid; 11792 11793 mHandler.sendMessage(msg); 11794 } 11795 11796 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, 11797 PackageParser.Package pkg) { 11798 int size = pkg.activities.size(); 11799 if (size == 0) { 11800 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11801 "No activity, so no need to verify any IntentFilter!"); 11802 return; 11803 } 11804 11805 final boolean hasDomainURLs = hasDomainURLs(pkg); 11806 if (!hasDomainURLs) { 11807 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11808 "No domain URLs, so no need to verify any IntentFilter!"); 11809 return; 11810 } 11811 11812 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 11813 + " if any IntentFilter from the " + size 11814 + " Activities needs verification ..."); 11815 11816 final int verificationId = mIntentFilterVerificationToken++; 11817 int count = 0; 11818 final String packageName = pkg.packageName; 11819 boolean needToVerify = false; 11820 11821 synchronized (mPackages) { 11822 // If any filters need to be verified, then all need to be. 11823 for (PackageParser.Activity a : pkg.activities) { 11824 for (ActivityIntentInfo filter : a.intents) { 11825 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 11826 if (DEBUG_DOMAIN_VERIFICATION) { 11827 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 11828 } 11829 needToVerify = true; 11830 break; 11831 } 11832 } 11833 } 11834 if (needToVerify) { 11835 for (PackageParser.Activity a : pkg.activities) { 11836 for (ActivityIntentInfo filter : a.intents) { 11837 boolean needsFilterVerification = filter.hasWebDataURI(); 11838 if (needsFilterVerification && needsNetworkVerificationLPr(filter)) { 11839 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 11840 "Verification needed for IntentFilter:" + filter.toString()); 11841 mIntentFilterVerifier.addOneIntentFilterVerification( 11842 verifierUid, userId, verificationId, filter, packageName); 11843 count++; 11844 } 11845 } 11846 } 11847 } 11848 } 11849 11850 if (count > 0) { 11851 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 11852 + " IntentFilter verification" + (count > 1 ? "s" : "") 11853 + " for userId:" + userId); 11854 mIntentFilterVerifier.startVerifications(userId); 11855 } else { 11856 if (DEBUG_DOMAIN_VERIFICATION) { 11857 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 11858 } 11859 } 11860 } 11861 11862 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 11863 final ComponentName cn = filter.activity.getComponentName(); 11864 final String packageName = cn.getPackageName(); 11865 11866 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 11867 packageName); 11868 if (ivi == null) { 11869 return true; 11870 } 11871 int status = ivi.getStatus(); 11872 switch (status) { 11873 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 11874 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 11875 return true; 11876 11877 default: 11878 // Nothing to do 11879 return false; 11880 } 11881 } 11882 11883 private boolean isSystemComponentOrPersistentPrivApp(PackageParser.Package pkg) { 11884 return UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID 11885 || ((pkg.applicationInfo.privateFlags 11886 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0 11887 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0); 11888 } 11889 11890 private static boolean isMultiArch(PackageSetting ps) { 11891 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11892 } 11893 11894 private static boolean isMultiArch(ApplicationInfo info) { 11895 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 11896 } 11897 11898 private static boolean isExternal(PackageParser.Package pkg) { 11899 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11900 } 11901 11902 private static boolean isExternal(PackageSetting ps) { 11903 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11904 } 11905 11906 private static boolean isExternal(ApplicationInfo info) { 11907 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 11908 } 11909 11910 private static boolean isSystemApp(PackageParser.Package pkg) { 11911 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 11912 } 11913 11914 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 11915 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 11916 } 11917 11918 private static boolean hasDomainURLs(PackageParser.Package pkg) { 11919 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 11920 } 11921 11922 private static boolean isSystemApp(PackageSetting ps) { 11923 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 11924 } 11925 11926 private static boolean isUpdatedSystemApp(PackageSetting ps) { 11927 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 11928 } 11929 11930 private int packageFlagsToInstallFlags(PackageSetting ps) { 11931 int installFlags = 0; 11932 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 11933 // This existing package was an external ASEC install when we have 11934 // the external flag without a UUID 11935 installFlags |= PackageManager.INSTALL_EXTERNAL; 11936 } 11937 if (ps.isForwardLocked()) { 11938 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 11939 } 11940 return installFlags; 11941 } 11942 11943 private void deleteTempPackageFiles() { 11944 final FilenameFilter filter = new FilenameFilter() { 11945 public boolean accept(File dir, String name) { 11946 return name.startsWith("vmdl") && name.endsWith(".tmp"); 11947 } 11948 }; 11949 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 11950 file.delete(); 11951 } 11952 } 11953 11954 @Override 11955 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 11956 int flags) { 11957 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 11958 flags); 11959 } 11960 11961 @Override 11962 public void deletePackage(final String packageName, 11963 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 11964 mContext.enforceCallingOrSelfPermission( 11965 android.Manifest.permission.DELETE_PACKAGES, null); 11966 final int uid = Binder.getCallingUid(); 11967 if (UserHandle.getUserId(uid) != userId) { 11968 mContext.enforceCallingPermission( 11969 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 11970 "deletePackage for user " + userId); 11971 } 11972 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 11973 try { 11974 observer.onPackageDeleted(packageName, 11975 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 11976 } catch (RemoteException re) { 11977 } 11978 return; 11979 } 11980 11981 boolean uninstallBlocked = false; 11982 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 11983 int[] users = sUserManager.getUserIds(); 11984 for (int i = 0; i < users.length; ++i) { 11985 if (getBlockUninstallForUser(packageName, users[i])) { 11986 uninstallBlocked = true; 11987 break; 11988 } 11989 } 11990 } else { 11991 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 11992 } 11993 if (uninstallBlocked) { 11994 try { 11995 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 11996 null); 11997 } catch (RemoteException re) { 11998 } 11999 return; 12000 } 12001 12002 if (DEBUG_REMOVE) { 12003 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 12004 } 12005 // Queue up an async operation since the package deletion may take a little while. 12006 mHandler.post(new Runnable() { 12007 public void run() { 12008 mHandler.removeCallbacks(this); 12009 final int returnCode = deletePackageX(packageName, userId, flags); 12010 if (observer != null) { 12011 try { 12012 observer.onPackageDeleted(packageName, returnCode, null); 12013 } catch (RemoteException e) { 12014 Log.i(TAG, "Observer no longer exists."); 12015 } //end catch 12016 } //end if 12017 } //end run 12018 }); 12019 } 12020 12021 private boolean isPackageDeviceAdmin(String packageName, int userId) { 12022 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12023 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12024 try { 12025 if (dpm != null) { 12026 if (dpm.isDeviceOwner(packageName)) { 12027 return true; 12028 } 12029 int[] users; 12030 if (userId == UserHandle.USER_ALL) { 12031 users = sUserManager.getUserIds(); 12032 } else { 12033 users = new int[]{userId}; 12034 } 12035 for (int i = 0; i < users.length; ++i) { 12036 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 12037 return true; 12038 } 12039 } 12040 } 12041 } catch (RemoteException e) { 12042 } 12043 return false; 12044 } 12045 12046 /** 12047 * This method is an internal method that could be get invoked either 12048 * to delete an installed package or to clean up a failed installation. 12049 * After deleting an installed package, a broadcast is sent to notify any 12050 * listeners that the package has been installed. For cleaning up a failed 12051 * installation, the broadcast is not necessary since the package's 12052 * installation wouldn't have sent the initial broadcast either 12053 * The key steps in deleting a package are 12054 * deleting the package information in internal structures like mPackages, 12055 * deleting the packages base directories through installd 12056 * updating mSettings to reflect current status 12057 * persisting settings for later use 12058 * sending a broadcast if necessary 12059 */ 12060 private int deletePackageX(String packageName, int userId, int flags) { 12061 final PackageRemovedInfo info = new PackageRemovedInfo(); 12062 final boolean res; 12063 12064 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 12065 ? UserHandle.ALL : new UserHandle(userId); 12066 12067 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 12068 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 12069 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 12070 } 12071 12072 boolean removedForAllUsers = false; 12073 boolean systemUpdate = false; 12074 12075 // for the uninstall-updates case and restricted profiles, remember the per- 12076 // userhandle installed state 12077 int[] allUsers; 12078 boolean[] perUserInstalled; 12079 synchronized (mPackages) { 12080 PackageSetting ps = mSettings.mPackages.get(packageName); 12081 allUsers = sUserManager.getUserIds(); 12082 perUserInstalled = new boolean[allUsers.length]; 12083 for (int i = 0; i < allUsers.length; i++) { 12084 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 12085 } 12086 } 12087 12088 synchronized (mInstallLock) { 12089 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 12090 res = deletePackageLI(packageName, removeForUser, 12091 true, allUsers, perUserInstalled, 12092 flags | REMOVE_CHATTY, info, true); 12093 systemUpdate = info.isRemovedPackageSystemUpdate; 12094 if (res && !systemUpdate && mPackages.get(packageName) == null) { 12095 removedForAllUsers = true; 12096 } 12097 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 12098 + " removedForAllUsers=" + removedForAllUsers); 12099 } 12100 12101 if (res) { 12102 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 12103 12104 // If the removed package was a system update, the old system package 12105 // was re-enabled; we need to broadcast this information 12106 if (systemUpdate) { 12107 Bundle extras = new Bundle(1); 12108 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 12109 ? info.removedAppId : info.uid); 12110 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12111 12112 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 12113 extras, null, null, null); 12114 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 12115 extras, null, null, null); 12116 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 12117 null, packageName, null, null); 12118 } 12119 } 12120 // Force a gc here. 12121 Runtime.getRuntime().gc(); 12122 // Delete the resources here after sending the broadcast to let 12123 // other processes clean up before deleting resources. 12124 if (info.args != null) { 12125 synchronized (mInstallLock) { 12126 info.args.doPostDeleteLI(true); 12127 } 12128 } 12129 12130 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 12131 } 12132 12133 class PackageRemovedInfo { 12134 String removedPackage; 12135 int uid = -1; 12136 int removedAppId = -1; 12137 int[] removedUsers = null; 12138 boolean isRemovedPackageSystemUpdate = false; 12139 // Clean up resources deleted packages. 12140 InstallArgs args = null; 12141 12142 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 12143 Bundle extras = new Bundle(1); 12144 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 12145 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 12146 if (replacing) { 12147 extras.putBoolean(Intent.EXTRA_REPLACING, true); 12148 } 12149 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 12150 if (removedPackage != null) { 12151 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 12152 extras, null, null, removedUsers); 12153 if (fullRemove && !replacing) { 12154 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 12155 extras, null, null, removedUsers); 12156 } 12157 } 12158 if (removedAppId >= 0) { 12159 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 12160 removedUsers); 12161 } 12162 } 12163 } 12164 12165 /* 12166 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 12167 * flag is not set, the data directory is removed as well. 12168 * make sure this flag is set for partially installed apps. If not its meaningless to 12169 * delete a partially installed application. 12170 */ 12171 private void removePackageDataLI(PackageSetting ps, 12172 int[] allUserHandles, boolean[] perUserInstalled, 12173 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 12174 String packageName = ps.name; 12175 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 12176 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 12177 // Retrieve object to delete permissions for shared user later on 12178 final PackageSetting deletedPs; 12179 // reader 12180 synchronized (mPackages) { 12181 deletedPs = mSettings.mPackages.get(packageName); 12182 if (outInfo != null) { 12183 outInfo.removedPackage = packageName; 12184 outInfo.removedUsers = deletedPs != null 12185 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 12186 : null; 12187 } 12188 } 12189 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12190 removeDataDirsLI(ps.volumeUuid, packageName); 12191 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 12192 } 12193 // writer 12194 synchronized (mPackages) { 12195 if (deletedPs != null) { 12196 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 12197 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 12198 clearDefaultBrowserIfNeeded(packageName); 12199 if (outInfo != null) { 12200 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 12201 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 12202 } 12203 updatePermissionsLPw(deletedPs.name, null, 0); 12204 if (deletedPs.sharedUser != null) { 12205 // Remove permissions associated with package. Since runtime 12206 // permissions are per user we have to kill the removed package 12207 // or packages running under the shared user of the removed 12208 // package if revoking the permissions requested only by the removed 12209 // package is successful and this causes a change in gids. 12210 for (int userId : UserManagerService.getInstance().getUserIds()) { 12211 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 12212 userId); 12213 if (userIdToKill == UserHandle.USER_ALL 12214 || userIdToKill >= UserHandle.USER_OWNER) { 12215 // If gids changed for this user, kill all affected packages. 12216 mHandler.post(new Runnable() { 12217 @Override 12218 public void run() { 12219 // This has to happen with no lock held. 12220 killSettingPackagesForUser(deletedPs, userIdToKill, 12221 KILL_APP_REASON_GIDS_CHANGED); 12222 } 12223 }); 12224 break; 12225 } 12226 } 12227 } 12228 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 12229 } 12230 // make sure to preserve per-user disabled state if this removal was just 12231 // a downgrade of a system app to the factory package 12232 if (allUserHandles != null && perUserInstalled != null) { 12233 if (DEBUG_REMOVE) { 12234 Slog.d(TAG, "Propagating install state across downgrade"); 12235 } 12236 for (int i = 0; i < allUserHandles.length; i++) { 12237 if (DEBUG_REMOVE) { 12238 Slog.d(TAG, " user " + allUserHandles[i] 12239 + " => " + perUserInstalled[i]); 12240 } 12241 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12242 } 12243 } 12244 } 12245 // can downgrade to reader 12246 if (writeSettings) { 12247 // Save settings now 12248 mSettings.writeLPr(); 12249 } 12250 } 12251 if (outInfo != null) { 12252 // A user ID was deleted here. Go through all users and remove it 12253 // from KeyStore. 12254 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 12255 } 12256 } 12257 12258 static boolean locationIsPrivileged(File path) { 12259 try { 12260 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 12261 .getCanonicalPath(); 12262 return path.getCanonicalPath().startsWith(privilegedAppDir); 12263 } catch (IOException e) { 12264 Slog.e(TAG, "Unable to access code path " + path); 12265 } 12266 return false; 12267 } 12268 12269 /* 12270 * Tries to delete system package. 12271 */ 12272 private boolean deleteSystemPackageLI(PackageSetting newPs, 12273 int[] allUserHandles, boolean[] perUserInstalled, 12274 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 12275 final boolean applyUserRestrictions 12276 = (allUserHandles != null) && (perUserInstalled != null); 12277 PackageSetting disabledPs = null; 12278 // Confirm if the system package has been updated 12279 // An updated system app can be deleted. This will also have to restore 12280 // the system pkg from system partition 12281 // reader 12282 synchronized (mPackages) { 12283 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 12284 } 12285 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 12286 + " disabledPs=" + disabledPs); 12287 if (disabledPs == null) { 12288 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 12289 return false; 12290 } else if (DEBUG_REMOVE) { 12291 Slog.d(TAG, "Deleting system pkg from data partition"); 12292 } 12293 if (DEBUG_REMOVE) { 12294 if (applyUserRestrictions) { 12295 Slog.d(TAG, "Remembering install states:"); 12296 for (int i = 0; i < allUserHandles.length; i++) { 12297 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 12298 } 12299 } 12300 } 12301 // Delete the updated package 12302 outInfo.isRemovedPackageSystemUpdate = true; 12303 if (disabledPs.versionCode < newPs.versionCode) { 12304 // Delete data for downgrades 12305 flags &= ~PackageManager.DELETE_KEEP_DATA; 12306 } else { 12307 // Preserve data by setting flag 12308 flags |= PackageManager.DELETE_KEEP_DATA; 12309 } 12310 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 12311 allUserHandles, perUserInstalled, outInfo, writeSettings); 12312 if (!ret) { 12313 return false; 12314 } 12315 // writer 12316 synchronized (mPackages) { 12317 // Reinstate the old system package 12318 mSettings.enableSystemPackageLPw(newPs.name); 12319 // Remove any native libraries from the upgraded package. 12320 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 12321 } 12322 // Install the system package 12323 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 12324 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 12325 if (locationIsPrivileged(disabledPs.codePath)) { 12326 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 12327 } 12328 12329 final PackageParser.Package newPkg; 12330 try { 12331 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 12332 } catch (PackageManagerException e) { 12333 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 12334 return false; 12335 } 12336 12337 // writer 12338 synchronized (mPackages) { 12339 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 12340 updatePermissionsLPw(newPkg.packageName, newPkg, 12341 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 12342 if (applyUserRestrictions) { 12343 if (DEBUG_REMOVE) { 12344 Slog.d(TAG, "Propagating install state across reinstall"); 12345 } 12346 for (int i = 0; i < allUserHandles.length; i++) { 12347 if (DEBUG_REMOVE) { 12348 Slog.d(TAG, " user " + allUserHandles[i] 12349 + " => " + perUserInstalled[i]); 12350 } 12351 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 12352 } 12353 // Regardless of writeSettings we need to ensure that this restriction 12354 // state propagation is persisted 12355 mSettings.writeAllUsersPackageRestrictionsLPr(); 12356 } 12357 // can downgrade to reader here 12358 if (writeSettings) { 12359 mSettings.writeLPr(); 12360 } 12361 } 12362 return true; 12363 } 12364 12365 private boolean deleteInstalledPackageLI(PackageSetting ps, 12366 boolean deleteCodeAndResources, int flags, 12367 int[] allUserHandles, boolean[] perUserInstalled, 12368 PackageRemovedInfo outInfo, boolean writeSettings) { 12369 if (outInfo != null) { 12370 outInfo.uid = ps.appId; 12371 } 12372 12373 // Delete package data from internal structures and also remove data if flag is set 12374 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 12375 12376 // Delete application code and resources 12377 if (deleteCodeAndResources && (outInfo != null)) { 12378 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 12379 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 12380 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 12381 } 12382 return true; 12383 } 12384 12385 @Override 12386 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 12387 int userId) { 12388 mContext.enforceCallingOrSelfPermission( 12389 android.Manifest.permission.DELETE_PACKAGES, null); 12390 synchronized (mPackages) { 12391 PackageSetting ps = mSettings.mPackages.get(packageName); 12392 if (ps == null) { 12393 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 12394 return false; 12395 } 12396 if (!ps.getInstalled(userId)) { 12397 // Can't block uninstall for an app that is not installed or enabled. 12398 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 12399 return false; 12400 } 12401 ps.setBlockUninstall(blockUninstall, userId); 12402 mSettings.writePackageRestrictionsLPr(userId); 12403 } 12404 return true; 12405 } 12406 12407 @Override 12408 public boolean getBlockUninstallForUser(String packageName, int userId) { 12409 synchronized (mPackages) { 12410 PackageSetting ps = mSettings.mPackages.get(packageName); 12411 if (ps == null) { 12412 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 12413 return false; 12414 } 12415 return ps.getBlockUninstall(userId); 12416 } 12417 } 12418 12419 /* 12420 * This method handles package deletion in general 12421 */ 12422 private boolean deletePackageLI(String packageName, UserHandle user, 12423 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 12424 int flags, PackageRemovedInfo outInfo, 12425 boolean writeSettings) { 12426 if (packageName == null) { 12427 Slog.w(TAG, "Attempt to delete null packageName."); 12428 return false; 12429 } 12430 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 12431 PackageSetting ps; 12432 boolean dataOnly = false; 12433 int removeUser = -1; 12434 int appId = -1; 12435 synchronized (mPackages) { 12436 ps = mSettings.mPackages.get(packageName); 12437 if (ps == null) { 12438 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12439 return false; 12440 } 12441 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 12442 && user.getIdentifier() != UserHandle.USER_ALL) { 12443 // The caller is asking that the package only be deleted for a single 12444 // user. To do this, we just mark its uninstalled state and delete 12445 // its data. If this is a system app, we only allow this to happen if 12446 // they have set the special DELETE_SYSTEM_APP which requests different 12447 // semantics than normal for uninstalling system apps. 12448 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 12449 ps.setUserState(user.getIdentifier(), 12450 COMPONENT_ENABLED_STATE_DEFAULT, 12451 false, //installed 12452 true, //stopped 12453 true, //notLaunched 12454 false, //hidden 12455 null, null, null, 12456 false, // blockUninstall 12457 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 12458 if (!isSystemApp(ps)) { 12459 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 12460 // Other user still have this package installed, so all 12461 // we need to do is clear this user's data and save that 12462 // it is uninstalled. 12463 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 12464 removeUser = user.getIdentifier(); 12465 appId = ps.appId; 12466 scheduleWritePackageRestrictionsLocked(removeUser); 12467 } else { 12468 // We need to set it back to 'installed' so the uninstall 12469 // broadcasts will be sent correctly. 12470 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 12471 ps.setInstalled(true, user.getIdentifier()); 12472 } 12473 } else { 12474 // This is a system app, so we assume that the 12475 // other users still have this package installed, so all 12476 // we need to do is clear this user's data and save that 12477 // it is uninstalled. 12478 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 12479 removeUser = user.getIdentifier(); 12480 appId = ps.appId; 12481 scheduleWritePackageRestrictionsLocked(removeUser); 12482 } 12483 } 12484 } 12485 12486 if (removeUser >= 0) { 12487 // From above, we determined that we are deleting this only 12488 // for a single user. Continue the work here. 12489 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 12490 if (outInfo != null) { 12491 outInfo.removedPackage = packageName; 12492 outInfo.removedAppId = appId; 12493 outInfo.removedUsers = new int[] {removeUser}; 12494 } 12495 mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser); 12496 removeKeystoreDataIfNeeded(removeUser, appId); 12497 schedulePackageCleaning(packageName, removeUser, false); 12498 synchronized (mPackages) { 12499 if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) { 12500 scheduleWritePackageRestrictionsLocked(removeUser); 12501 } 12502 } 12503 return true; 12504 } 12505 12506 if (dataOnly) { 12507 // Delete application data first 12508 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 12509 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 12510 return true; 12511 } 12512 12513 boolean ret = false; 12514 if (isSystemApp(ps)) { 12515 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 12516 // When an updated system application is deleted we delete the existing resources as well and 12517 // fall back to existing code in system partition 12518 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 12519 flags, outInfo, writeSettings); 12520 } else { 12521 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 12522 // Kill application pre-emptively especially for apps on sd. 12523 killApplication(packageName, ps.appId, "uninstall pkg"); 12524 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 12525 allUserHandles, perUserInstalled, 12526 outInfo, writeSettings); 12527 } 12528 12529 return ret; 12530 } 12531 12532 private final class ClearStorageConnection implements ServiceConnection { 12533 IMediaContainerService mContainerService; 12534 12535 @Override 12536 public void onServiceConnected(ComponentName name, IBinder service) { 12537 synchronized (this) { 12538 mContainerService = IMediaContainerService.Stub.asInterface(service); 12539 notifyAll(); 12540 } 12541 } 12542 12543 @Override 12544 public void onServiceDisconnected(ComponentName name) { 12545 } 12546 } 12547 12548 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 12549 final boolean mounted; 12550 if (Environment.isExternalStorageEmulated()) { 12551 mounted = true; 12552 } else { 12553 final String status = Environment.getExternalStorageState(); 12554 12555 mounted = status.equals(Environment.MEDIA_MOUNTED) 12556 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 12557 } 12558 12559 if (!mounted) { 12560 return; 12561 } 12562 12563 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 12564 int[] users; 12565 if (userId == UserHandle.USER_ALL) { 12566 users = sUserManager.getUserIds(); 12567 } else { 12568 users = new int[] { userId }; 12569 } 12570 final ClearStorageConnection conn = new ClearStorageConnection(); 12571 if (mContext.bindServiceAsUser( 12572 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 12573 try { 12574 for (int curUser : users) { 12575 long timeout = SystemClock.uptimeMillis() + 5000; 12576 synchronized (conn) { 12577 long now = SystemClock.uptimeMillis(); 12578 while (conn.mContainerService == null && now < timeout) { 12579 try { 12580 conn.wait(timeout - now); 12581 } catch (InterruptedException e) { 12582 } 12583 } 12584 } 12585 if (conn.mContainerService == null) { 12586 return; 12587 } 12588 12589 final UserEnvironment userEnv = new UserEnvironment(curUser); 12590 clearDirectory(conn.mContainerService, 12591 userEnv.buildExternalStorageAppCacheDirs(packageName)); 12592 if (allData) { 12593 clearDirectory(conn.mContainerService, 12594 userEnv.buildExternalStorageAppDataDirs(packageName)); 12595 clearDirectory(conn.mContainerService, 12596 userEnv.buildExternalStorageAppMediaDirs(packageName)); 12597 } 12598 } 12599 } finally { 12600 mContext.unbindService(conn); 12601 } 12602 } 12603 } 12604 12605 @Override 12606 public void clearApplicationUserData(final String packageName, 12607 final IPackageDataObserver observer, final int userId) { 12608 mContext.enforceCallingOrSelfPermission( 12609 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 12610 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 12611 // Queue up an async operation since the package deletion may take a little while. 12612 mHandler.post(new Runnable() { 12613 public void run() { 12614 mHandler.removeCallbacks(this); 12615 final boolean succeeded; 12616 synchronized (mInstallLock) { 12617 succeeded = clearApplicationUserDataLI(packageName, userId); 12618 } 12619 clearExternalStorageDataSync(packageName, userId, true); 12620 if (succeeded) { 12621 // invoke DeviceStorageMonitor's update method to clear any notifications 12622 DeviceStorageMonitorInternal 12623 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12624 if (dsm != null) { 12625 dsm.checkMemory(); 12626 } 12627 } 12628 if(observer != null) { 12629 try { 12630 observer.onRemoveCompleted(packageName, succeeded); 12631 } catch (RemoteException e) { 12632 Log.i(TAG, "Observer no longer exists."); 12633 } 12634 } //end if observer 12635 } //end run 12636 }); 12637 } 12638 12639 private boolean clearApplicationUserDataLI(String packageName, int userId) { 12640 if (packageName == null) { 12641 Slog.w(TAG, "Attempt to delete null packageName."); 12642 return false; 12643 } 12644 12645 // Try finding details about the requested package 12646 PackageParser.Package pkg; 12647 synchronized (mPackages) { 12648 pkg = mPackages.get(packageName); 12649 if (pkg == null) { 12650 final PackageSetting ps = mSettings.mPackages.get(packageName); 12651 if (ps != null) { 12652 pkg = ps.pkg; 12653 } 12654 } 12655 12656 if (pkg == null) { 12657 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 12658 return false; 12659 } 12660 12661 PackageSetting ps = (PackageSetting) pkg.mExtras; 12662 PermissionsState permissionsState = ps.getPermissionsState(); 12663 revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId); 12664 } 12665 12666 // Always delete data directories for package, even if we found no other 12667 // record of app. This helps users recover from UID mismatches without 12668 // resorting to a full data wipe. 12669 int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId); 12670 if (retCode < 0) { 12671 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 12672 return false; 12673 } 12674 12675 final int appId = pkg.applicationInfo.uid; 12676 removeKeystoreDataIfNeeded(userId, appId); 12677 12678 // Create a native library symlink only if we have native libraries 12679 // and if the native libraries are 32 bit libraries. We do not provide 12680 // this symlink for 64 bit libraries. 12681 if (pkg.applicationInfo.primaryCpuAbi != null && 12682 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 12683 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 12684 if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName, 12685 nativeLibPath, userId) < 0) { 12686 Slog.w(TAG, "Failed linking native library dir"); 12687 return false; 12688 } 12689 } 12690 12691 return true; 12692 } 12693 12694 12695 /** 12696 * Revokes granted runtime permissions and clears resettable flags 12697 * which are flags that can be set by a user interaction. 12698 * 12699 * @param permissionsState The permission state to reset. 12700 * @param userId The device user for which to do a reset. 12701 */ 12702 private void revokeRuntimePermissionsAndClearUserSetFlagsLocked( 12703 PermissionsState permissionsState, int userId) { 12704 final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET 12705 | PackageManager.FLAG_PERMISSION_USER_FIXED 12706 | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 12707 12708 boolean needsWrite = false; 12709 12710 for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) { 12711 BasePermission bp = mSettings.mPermissions.get(state.getName()); 12712 if (bp != null) { 12713 permissionsState.revokeRuntimePermission(bp, userId); 12714 permissionsState.updatePermissionFlags(bp, userId, userSetFlags, 0); 12715 needsWrite = true; 12716 } 12717 } 12718 12719 if (needsWrite) { 12720 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 12721 } 12722 } 12723 12724 /** 12725 * Remove entries from the keystore daemon. Will only remove it if the 12726 * {@code appId} is valid. 12727 */ 12728 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 12729 if (appId < 0) { 12730 return; 12731 } 12732 12733 final KeyStore keyStore = KeyStore.getInstance(); 12734 if (keyStore != null) { 12735 if (userId == UserHandle.USER_ALL) { 12736 for (final int individual : sUserManager.getUserIds()) { 12737 keyStore.clearUid(UserHandle.getUid(individual, appId)); 12738 } 12739 } else { 12740 keyStore.clearUid(UserHandle.getUid(userId, appId)); 12741 } 12742 } else { 12743 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 12744 } 12745 } 12746 12747 @Override 12748 public void deleteApplicationCacheFiles(final String packageName, 12749 final IPackageDataObserver observer) { 12750 mContext.enforceCallingOrSelfPermission( 12751 android.Manifest.permission.DELETE_CACHE_FILES, null); 12752 // Queue up an async operation since the package deletion may take a little while. 12753 final int userId = UserHandle.getCallingUserId(); 12754 mHandler.post(new Runnable() { 12755 public void run() { 12756 mHandler.removeCallbacks(this); 12757 final boolean succeded; 12758 synchronized (mInstallLock) { 12759 succeded = deleteApplicationCacheFilesLI(packageName, userId); 12760 } 12761 clearExternalStorageDataSync(packageName, userId, false); 12762 if (observer != null) { 12763 try { 12764 observer.onRemoveCompleted(packageName, succeded); 12765 } catch (RemoteException e) { 12766 Log.i(TAG, "Observer no longer exists."); 12767 } 12768 } //end if observer 12769 } //end run 12770 }); 12771 } 12772 12773 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 12774 if (packageName == null) { 12775 Slog.w(TAG, "Attempt to delete null packageName."); 12776 return false; 12777 } 12778 PackageParser.Package p; 12779 synchronized (mPackages) { 12780 p = mPackages.get(packageName); 12781 } 12782 if (p == null) { 12783 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12784 return false; 12785 } 12786 final ApplicationInfo applicationInfo = p.applicationInfo; 12787 if (applicationInfo == null) { 12788 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12789 return false; 12790 } 12791 int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId); 12792 if (retCode < 0) { 12793 Slog.w(TAG, "Couldn't remove cache files for package: " 12794 + packageName + " u" + userId); 12795 return false; 12796 } 12797 return true; 12798 } 12799 12800 @Override 12801 public void getPackageSizeInfo(final String packageName, int userHandle, 12802 final IPackageStatsObserver observer) { 12803 mContext.enforceCallingOrSelfPermission( 12804 android.Manifest.permission.GET_PACKAGE_SIZE, null); 12805 if (packageName == null) { 12806 throw new IllegalArgumentException("Attempt to get size of null packageName"); 12807 } 12808 12809 PackageStats stats = new PackageStats(packageName, userHandle); 12810 12811 /* 12812 * Queue up an async operation since the package measurement may take a 12813 * little while. 12814 */ 12815 Message msg = mHandler.obtainMessage(INIT_COPY); 12816 msg.obj = new MeasureParams(stats, observer); 12817 mHandler.sendMessage(msg); 12818 } 12819 12820 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 12821 PackageStats pStats) { 12822 if (packageName == null) { 12823 Slog.w(TAG, "Attempt to get size of null packageName."); 12824 return false; 12825 } 12826 PackageParser.Package p; 12827 boolean dataOnly = false; 12828 String libDirRoot = null; 12829 String asecPath = null; 12830 PackageSetting ps = null; 12831 synchronized (mPackages) { 12832 p = mPackages.get(packageName); 12833 ps = mSettings.mPackages.get(packageName); 12834 if(p == null) { 12835 dataOnly = true; 12836 if((ps == null) || (ps.pkg == null)) { 12837 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 12838 return false; 12839 } 12840 p = ps.pkg; 12841 } 12842 if (ps != null) { 12843 libDirRoot = ps.legacyNativeLibraryPathString; 12844 } 12845 if (p != null && (isExternal(p) || p.isForwardLocked())) { 12846 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 12847 if (secureContainerId != null) { 12848 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 12849 } 12850 } 12851 } 12852 String publicSrcDir = null; 12853 if(!dataOnly) { 12854 final ApplicationInfo applicationInfo = p.applicationInfo; 12855 if (applicationInfo == null) { 12856 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 12857 return false; 12858 } 12859 if (p.isForwardLocked()) { 12860 publicSrcDir = applicationInfo.getBaseResourcePath(); 12861 } 12862 } 12863 // TODO: extend to measure size of split APKs 12864 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 12865 // not just the first level. 12866 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 12867 // just the primary. 12868 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 12869 int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath, 12870 libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 12871 if (res < 0) { 12872 return false; 12873 } 12874 12875 // Fix-up for forward-locked applications in ASEC containers. 12876 if (!isExternal(p)) { 12877 pStats.codeSize += pStats.externalCodeSize; 12878 pStats.externalCodeSize = 0L; 12879 } 12880 12881 return true; 12882 } 12883 12884 12885 @Override 12886 public void addPackageToPreferred(String packageName) { 12887 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 12888 } 12889 12890 @Override 12891 public void removePackageFromPreferred(String packageName) { 12892 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 12893 } 12894 12895 @Override 12896 public List<PackageInfo> getPreferredPackages(int flags) { 12897 return new ArrayList<PackageInfo>(); 12898 } 12899 12900 private int getUidTargetSdkVersionLockedLPr(int uid) { 12901 Object obj = mSettings.getUserIdLPr(uid); 12902 if (obj instanceof SharedUserSetting) { 12903 final SharedUserSetting sus = (SharedUserSetting) obj; 12904 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 12905 final Iterator<PackageSetting> it = sus.packages.iterator(); 12906 while (it.hasNext()) { 12907 final PackageSetting ps = it.next(); 12908 if (ps.pkg != null) { 12909 int v = ps.pkg.applicationInfo.targetSdkVersion; 12910 if (v < vers) vers = v; 12911 } 12912 } 12913 return vers; 12914 } else if (obj instanceof PackageSetting) { 12915 final PackageSetting ps = (PackageSetting) obj; 12916 if (ps.pkg != null) { 12917 return ps.pkg.applicationInfo.targetSdkVersion; 12918 } 12919 } 12920 return Build.VERSION_CODES.CUR_DEVELOPMENT; 12921 } 12922 12923 @Override 12924 public void addPreferredActivity(IntentFilter filter, int match, 12925 ComponentName[] set, ComponentName activity, int userId) { 12926 addPreferredActivityInternal(filter, match, set, activity, true, userId, 12927 "Adding preferred"); 12928 } 12929 12930 private void addPreferredActivityInternal(IntentFilter filter, int match, 12931 ComponentName[] set, ComponentName activity, boolean always, int userId, 12932 String opname) { 12933 // writer 12934 int callingUid = Binder.getCallingUid(); 12935 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 12936 if (filter.countActions() == 0) { 12937 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 12938 return; 12939 } 12940 synchronized (mPackages) { 12941 if (mContext.checkCallingOrSelfPermission( 12942 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12943 != PackageManager.PERMISSION_GRANTED) { 12944 if (getUidTargetSdkVersionLockedLPr(callingUid) 12945 < Build.VERSION_CODES.FROYO) { 12946 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 12947 + callingUid); 12948 return; 12949 } 12950 mContext.enforceCallingOrSelfPermission( 12951 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12952 } 12953 12954 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 12955 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 12956 + userId + ":"); 12957 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 12958 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 12959 scheduleWritePackageRestrictionsLocked(userId); 12960 } 12961 } 12962 12963 @Override 12964 public void replacePreferredActivity(IntentFilter filter, int match, 12965 ComponentName[] set, ComponentName activity, int userId) { 12966 if (filter.countActions() != 1) { 12967 throw new IllegalArgumentException( 12968 "replacePreferredActivity expects filter to have only 1 action."); 12969 } 12970 if (filter.countDataAuthorities() != 0 12971 || filter.countDataPaths() != 0 12972 || filter.countDataSchemes() > 1 12973 || filter.countDataTypes() != 0) { 12974 throw new IllegalArgumentException( 12975 "replacePreferredActivity expects filter to have no data authorities, " + 12976 "paths, or types; and at most one scheme."); 12977 } 12978 12979 final int callingUid = Binder.getCallingUid(); 12980 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 12981 synchronized (mPackages) { 12982 if (mContext.checkCallingOrSelfPermission( 12983 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 12984 != PackageManager.PERMISSION_GRANTED) { 12985 if (getUidTargetSdkVersionLockedLPr(callingUid) 12986 < Build.VERSION_CODES.FROYO) { 12987 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 12988 + Binder.getCallingUid()); 12989 return; 12990 } 12991 mContext.enforceCallingOrSelfPermission( 12992 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12993 } 12994 12995 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 12996 if (pir != null) { 12997 // Get all of the existing entries that exactly match this filter. 12998 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 12999 if (existing != null && existing.size() == 1) { 13000 PreferredActivity cur = existing.get(0); 13001 if (DEBUG_PREFERRED) { 13002 Slog.i(TAG, "Checking replace of preferred:"); 13003 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13004 if (!cur.mPref.mAlways) { 13005 Slog.i(TAG, " -- CUR; not mAlways!"); 13006 } else { 13007 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 13008 Slog.i(TAG, " -- CUR: mSet=" 13009 + Arrays.toString(cur.mPref.mSetComponents)); 13010 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 13011 Slog.i(TAG, " -- NEW: mMatch=" 13012 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 13013 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 13014 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 13015 } 13016 } 13017 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 13018 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 13019 && cur.mPref.sameSet(set)) { 13020 // Setting the preferred activity to what it happens to be already 13021 if (DEBUG_PREFERRED) { 13022 Slog.i(TAG, "Replacing with same preferred activity " 13023 + cur.mPref.mShortComponent + " for user " 13024 + userId + ":"); 13025 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13026 } 13027 return; 13028 } 13029 } 13030 13031 if (existing != null) { 13032 if (DEBUG_PREFERRED) { 13033 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 13034 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13035 } 13036 for (int i = 0; i < existing.size(); i++) { 13037 PreferredActivity pa = existing.get(i); 13038 if (DEBUG_PREFERRED) { 13039 Slog.i(TAG, "Removing existing preferred activity " 13040 + pa.mPref.mComponent + ":"); 13041 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 13042 } 13043 pir.removeFilter(pa); 13044 } 13045 } 13046 } 13047 addPreferredActivityInternal(filter, match, set, activity, true, userId, 13048 "Replacing preferred"); 13049 } 13050 } 13051 13052 @Override 13053 public void clearPackagePreferredActivities(String packageName) { 13054 final int uid = Binder.getCallingUid(); 13055 // writer 13056 synchronized (mPackages) { 13057 PackageParser.Package pkg = mPackages.get(packageName); 13058 if (pkg == null || pkg.applicationInfo.uid != uid) { 13059 if (mContext.checkCallingOrSelfPermission( 13060 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 13061 != PackageManager.PERMISSION_GRANTED) { 13062 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 13063 < Build.VERSION_CODES.FROYO) { 13064 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 13065 + Binder.getCallingUid()); 13066 return; 13067 } 13068 mContext.enforceCallingOrSelfPermission( 13069 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13070 } 13071 } 13072 13073 int user = UserHandle.getCallingUserId(); 13074 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 13075 scheduleWritePackageRestrictionsLocked(user); 13076 } 13077 } 13078 } 13079 13080 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13081 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 13082 ArrayList<PreferredActivity> removed = null; 13083 boolean changed = false; 13084 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13085 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 13086 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13087 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 13088 continue; 13089 } 13090 Iterator<PreferredActivity> it = pir.filterIterator(); 13091 while (it.hasNext()) { 13092 PreferredActivity pa = it.next(); 13093 // Mark entry for removal only if it matches the package name 13094 // and the entry is of type "always". 13095 if (packageName == null || 13096 (pa.mPref.mComponent.getPackageName().equals(packageName) 13097 && pa.mPref.mAlways)) { 13098 if (removed == null) { 13099 removed = new ArrayList<PreferredActivity>(); 13100 } 13101 removed.add(pa); 13102 } 13103 } 13104 if (removed != null) { 13105 for (int j=0; j<removed.size(); j++) { 13106 PreferredActivity pa = removed.get(j); 13107 pir.removeFilter(pa); 13108 } 13109 changed = true; 13110 } 13111 } 13112 return changed; 13113 } 13114 13115 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 13116 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 13117 if (userId == UserHandle.USER_ALL) { 13118 if (mSettings.removeIntentFilterVerificationLPw(packageName, 13119 sUserManager.getUserIds())) { 13120 for (int oneUserId : sUserManager.getUserIds()) { 13121 scheduleWritePackageRestrictionsLocked(oneUserId); 13122 } 13123 } 13124 } else { 13125 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 13126 scheduleWritePackageRestrictionsLocked(userId); 13127 } 13128 } 13129 } 13130 13131 13132 void clearDefaultBrowserIfNeeded(String packageName) { 13133 for (int oneUserId : sUserManager.getUserIds()) { 13134 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 13135 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 13136 if (packageName.equals(defaultBrowserPackageName)) { 13137 setDefaultBrowserPackageName(null, oneUserId); 13138 } 13139 } 13140 } 13141 13142 @Override 13143 public void resetPreferredActivities(int userId) { 13144 /* TODO: Actually use userId. Why is it being passed in? */ 13145 mContext.enforceCallingOrSelfPermission( 13146 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13147 // writer 13148 synchronized (mPackages) { 13149 int user = UserHandle.getCallingUserId(); 13150 clearPackagePreferredActivitiesLPw(null, user); 13151 mSettings.readDefaultPreferredAppsLPw(this, user); 13152 scheduleWritePackageRestrictionsLocked(user); 13153 } 13154 } 13155 13156 @Override 13157 public int getPreferredActivities(List<IntentFilter> outFilters, 13158 List<ComponentName> outActivities, String packageName) { 13159 13160 int num = 0; 13161 final int userId = UserHandle.getCallingUserId(); 13162 // reader 13163 synchronized (mPackages) { 13164 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 13165 if (pir != null) { 13166 final Iterator<PreferredActivity> it = pir.filterIterator(); 13167 while (it.hasNext()) { 13168 final PreferredActivity pa = it.next(); 13169 if (packageName == null 13170 || (pa.mPref.mComponent.getPackageName().equals(packageName) 13171 && pa.mPref.mAlways)) { 13172 if (outFilters != null) { 13173 outFilters.add(new IntentFilter(pa)); 13174 } 13175 if (outActivities != null) { 13176 outActivities.add(pa.mPref.mComponent); 13177 } 13178 } 13179 } 13180 } 13181 } 13182 13183 return num; 13184 } 13185 13186 @Override 13187 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 13188 int userId) { 13189 int callingUid = Binder.getCallingUid(); 13190 if (callingUid != Process.SYSTEM_UID) { 13191 throw new SecurityException( 13192 "addPersistentPreferredActivity can only be run by the system"); 13193 } 13194 if (filter.countActions() == 0) { 13195 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 13196 return; 13197 } 13198 synchronized (mPackages) { 13199 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 13200 " :"); 13201 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 13202 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 13203 new PersistentPreferredActivity(filter, activity)); 13204 scheduleWritePackageRestrictionsLocked(userId); 13205 } 13206 } 13207 13208 @Override 13209 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 13210 int callingUid = Binder.getCallingUid(); 13211 if (callingUid != Process.SYSTEM_UID) { 13212 throw new SecurityException( 13213 "clearPackagePersistentPreferredActivities can only be run by the system"); 13214 } 13215 ArrayList<PersistentPreferredActivity> removed = null; 13216 boolean changed = false; 13217 synchronized (mPackages) { 13218 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 13219 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 13220 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 13221 .valueAt(i); 13222 if (userId != thisUserId) { 13223 continue; 13224 } 13225 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 13226 while (it.hasNext()) { 13227 PersistentPreferredActivity ppa = it.next(); 13228 // Mark entry for removal only if it matches the package name. 13229 if (ppa.mComponent.getPackageName().equals(packageName)) { 13230 if (removed == null) { 13231 removed = new ArrayList<PersistentPreferredActivity>(); 13232 } 13233 removed.add(ppa); 13234 } 13235 } 13236 if (removed != null) { 13237 for (int j=0; j<removed.size(); j++) { 13238 PersistentPreferredActivity ppa = removed.get(j); 13239 ppir.removeFilter(ppa); 13240 } 13241 changed = true; 13242 } 13243 } 13244 13245 if (changed) { 13246 scheduleWritePackageRestrictionsLocked(userId); 13247 } 13248 } 13249 } 13250 13251 /** 13252 * Non-Binder method, support for the backup/restore mechanism: write the 13253 * full set of preferred activities in its canonical XML format. Returns true 13254 * on success; false otherwise. 13255 */ 13256 @Override 13257 public byte[] getPreferredActivityBackup(int userId) { 13258 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13259 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 13260 } 13261 13262 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 13263 try { 13264 final XmlSerializer serializer = new FastXmlSerializer(); 13265 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 13266 serializer.startDocument(null, true); 13267 serializer.startTag(null, TAG_PREFERRED_BACKUP); 13268 13269 synchronized (mPackages) { 13270 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 13271 } 13272 13273 serializer.endTag(null, TAG_PREFERRED_BACKUP); 13274 serializer.endDocument(); 13275 serializer.flush(); 13276 } catch (Exception e) { 13277 if (DEBUG_BACKUP) { 13278 Slog.e(TAG, "Unable to write preferred activities for backup", e); 13279 } 13280 return null; 13281 } 13282 13283 return dataStream.toByteArray(); 13284 } 13285 13286 @Override 13287 public void restorePreferredActivities(byte[] backup, int userId) { 13288 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 13289 throw new SecurityException("Only the system may call restorePreferredActivities()"); 13290 } 13291 13292 try { 13293 final XmlPullParser parser = Xml.newPullParser(); 13294 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 13295 13296 int type; 13297 while ((type = parser.next()) != XmlPullParser.START_TAG 13298 && type != XmlPullParser.END_DOCUMENT) { 13299 } 13300 if (type != XmlPullParser.START_TAG) { 13301 // oops didn't find a start tag?! 13302 if (DEBUG_BACKUP) { 13303 Slog.e(TAG, "Didn't find start tag during restore"); 13304 } 13305 return; 13306 } 13307 13308 // this is supposed to be TAG_PREFERRED_BACKUP 13309 if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) { 13310 if (DEBUG_BACKUP) { 13311 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 13312 } 13313 return; 13314 } 13315 13316 // skip interfering stuff, then we're aligned with the backing implementation 13317 while ((type = parser.next()) == XmlPullParser.TEXT) { } 13318 synchronized (mPackages) { 13319 mSettings.readPreferredActivitiesLPw(parser, userId); 13320 } 13321 } catch (Exception e) { 13322 if (DEBUG_BACKUP) { 13323 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 13324 } 13325 } 13326 } 13327 13328 @Override 13329 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 13330 int sourceUserId, int targetUserId, int flags) { 13331 mContext.enforceCallingOrSelfPermission( 13332 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13333 int callingUid = Binder.getCallingUid(); 13334 enforceOwnerRights(ownerPackage, callingUid); 13335 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13336 if (intentFilter.countActions() == 0) { 13337 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 13338 return; 13339 } 13340 synchronized (mPackages) { 13341 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 13342 ownerPackage, targetUserId, flags); 13343 CrossProfileIntentResolver resolver = 13344 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13345 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 13346 // We have all those whose filter is equal. Now checking if the rest is equal as well. 13347 if (existing != null) { 13348 int size = existing.size(); 13349 for (int i = 0; i < size; i++) { 13350 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 13351 return; 13352 } 13353 } 13354 } 13355 resolver.addFilter(newFilter); 13356 scheduleWritePackageRestrictionsLocked(sourceUserId); 13357 } 13358 } 13359 13360 @Override 13361 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 13362 mContext.enforceCallingOrSelfPermission( 13363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13364 int callingUid = Binder.getCallingUid(); 13365 enforceOwnerRights(ownerPackage, callingUid); 13366 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 13367 synchronized (mPackages) { 13368 CrossProfileIntentResolver resolver = 13369 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 13370 ArraySet<CrossProfileIntentFilter> set = 13371 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 13372 for (CrossProfileIntentFilter filter : set) { 13373 if (filter.getOwnerPackage().equals(ownerPackage)) { 13374 resolver.removeFilter(filter); 13375 } 13376 } 13377 scheduleWritePackageRestrictionsLocked(sourceUserId); 13378 } 13379 } 13380 13381 // Enforcing that callingUid is owning pkg on userId 13382 private void enforceOwnerRights(String pkg, int callingUid) { 13383 // The system owns everything. 13384 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 13385 return; 13386 } 13387 int callingUserId = UserHandle.getUserId(callingUid); 13388 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 13389 if (pi == null) { 13390 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 13391 + callingUserId); 13392 } 13393 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 13394 throw new SecurityException("Calling uid " + callingUid 13395 + " does not own package " + pkg); 13396 } 13397 } 13398 13399 @Override 13400 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 13401 Intent intent = new Intent(Intent.ACTION_MAIN); 13402 intent.addCategory(Intent.CATEGORY_HOME); 13403 13404 final int callingUserId = UserHandle.getCallingUserId(); 13405 List<ResolveInfo> list = queryIntentActivities(intent, null, 13406 PackageManager.GET_META_DATA, callingUserId); 13407 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 13408 true, false, false, callingUserId); 13409 13410 allHomeCandidates.clear(); 13411 if (list != null) { 13412 for (ResolveInfo ri : list) { 13413 allHomeCandidates.add(ri); 13414 } 13415 } 13416 return (preferred == null || preferred.activityInfo == null) 13417 ? null 13418 : new ComponentName(preferred.activityInfo.packageName, 13419 preferred.activityInfo.name); 13420 } 13421 13422 @Override 13423 public void setApplicationEnabledSetting(String appPackageName, 13424 int newState, int flags, int userId, String callingPackage) { 13425 if (!sUserManager.exists(userId)) return; 13426 if (callingPackage == null) { 13427 callingPackage = Integer.toString(Binder.getCallingUid()); 13428 } 13429 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 13430 } 13431 13432 @Override 13433 public void setComponentEnabledSetting(ComponentName componentName, 13434 int newState, int flags, int userId) { 13435 if (!sUserManager.exists(userId)) return; 13436 setEnabledSetting(componentName.getPackageName(), 13437 componentName.getClassName(), newState, flags, userId, null); 13438 } 13439 13440 private void setEnabledSetting(final String packageName, String className, int newState, 13441 final int flags, int userId, String callingPackage) { 13442 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 13443 || newState == COMPONENT_ENABLED_STATE_ENABLED 13444 || newState == COMPONENT_ENABLED_STATE_DISABLED 13445 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 13446 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 13447 throw new IllegalArgumentException("Invalid new component state: " 13448 + newState); 13449 } 13450 PackageSetting pkgSetting; 13451 final int uid = Binder.getCallingUid(); 13452 final int permission = mContext.checkCallingOrSelfPermission( 13453 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13454 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 13455 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13456 boolean sendNow = false; 13457 boolean isApp = (className == null); 13458 String componentName = isApp ? packageName : className; 13459 int packageUid = -1; 13460 ArrayList<String> components; 13461 13462 // writer 13463 synchronized (mPackages) { 13464 pkgSetting = mSettings.mPackages.get(packageName); 13465 if (pkgSetting == null) { 13466 if (className == null) { 13467 throw new IllegalArgumentException( 13468 "Unknown package: " + packageName); 13469 } 13470 throw new IllegalArgumentException( 13471 "Unknown component: " + packageName 13472 + "/" + className); 13473 } 13474 // Allow root and verify that userId is not being specified by a different user 13475 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 13476 throw new SecurityException( 13477 "Permission Denial: attempt to change component state from pid=" 13478 + Binder.getCallingPid() 13479 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 13480 } 13481 if (className == null) { 13482 // We're dealing with an application/package level state change 13483 if (pkgSetting.getEnabled(userId) == newState) { 13484 // Nothing to do 13485 return; 13486 } 13487 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 13488 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 13489 // Don't care about who enables an app. 13490 callingPackage = null; 13491 } 13492 pkgSetting.setEnabled(newState, userId, callingPackage); 13493 // pkgSetting.pkg.mSetEnabled = newState; 13494 } else { 13495 // We're dealing with a component level state change 13496 // First, verify that this is a valid class name. 13497 PackageParser.Package pkg = pkgSetting.pkg; 13498 if (pkg == null || !pkg.hasComponentClassName(className)) { 13499 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 13500 throw new IllegalArgumentException("Component class " + className 13501 + " does not exist in " + packageName); 13502 } else { 13503 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 13504 + className + " does not exist in " + packageName); 13505 } 13506 } 13507 switch (newState) { 13508 case COMPONENT_ENABLED_STATE_ENABLED: 13509 if (!pkgSetting.enableComponentLPw(className, userId)) { 13510 return; 13511 } 13512 break; 13513 case COMPONENT_ENABLED_STATE_DISABLED: 13514 if (!pkgSetting.disableComponentLPw(className, userId)) { 13515 return; 13516 } 13517 break; 13518 case COMPONENT_ENABLED_STATE_DEFAULT: 13519 if (!pkgSetting.restoreComponentLPw(className, userId)) { 13520 return; 13521 } 13522 break; 13523 default: 13524 Slog.e(TAG, "Invalid new component state: " + newState); 13525 return; 13526 } 13527 } 13528 scheduleWritePackageRestrictionsLocked(userId); 13529 components = mPendingBroadcasts.get(userId, packageName); 13530 final boolean newPackage = components == null; 13531 if (newPackage) { 13532 components = new ArrayList<String>(); 13533 } 13534 if (!components.contains(componentName)) { 13535 components.add(componentName); 13536 } 13537 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 13538 sendNow = true; 13539 // Purge entry from pending broadcast list if another one exists already 13540 // since we are sending one right away. 13541 mPendingBroadcasts.remove(userId, packageName); 13542 } else { 13543 if (newPackage) { 13544 mPendingBroadcasts.put(userId, packageName, components); 13545 } 13546 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 13547 // Schedule a message 13548 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 13549 } 13550 } 13551 } 13552 13553 long callingId = Binder.clearCallingIdentity(); 13554 try { 13555 if (sendNow) { 13556 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 13557 sendPackageChangedBroadcast(packageName, 13558 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 13559 } 13560 } finally { 13561 Binder.restoreCallingIdentity(callingId); 13562 } 13563 } 13564 13565 private void sendPackageChangedBroadcast(String packageName, 13566 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 13567 if (DEBUG_INSTALL) 13568 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 13569 + componentNames); 13570 Bundle extras = new Bundle(4); 13571 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 13572 String nameList[] = new String[componentNames.size()]; 13573 componentNames.toArray(nameList); 13574 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 13575 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 13576 extras.putInt(Intent.EXTRA_UID, packageUid); 13577 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 13578 new int[] {UserHandle.getUserId(packageUid)}); 13579 } 13580 13581 @Override 13582 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 13583 if (!sUserManager.exists(userId)) return; 13584 final int uid = Binder.getCallingUid(); 13585 final int permission = mContext.checkCallingOrSelfPermission( 13586 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 13587 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 13588 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 13589 // writer 13590 synchronized (mPackages) { 13591 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 13592 allowedByPermission, uid, userId)) { 13593 scheduleWritePackageRestrictionsLocked(userId); 13594 } 13595 } 13596 } 13597 13598 @Override 13599 public String getInstallerPackageName(String packageName) { 13600 // reader 13601 synchronized (mPackages) { 13602 return mSettings.getInstallerPackageNameLPr(packageName); 13603 } 13604 } 13605 13606 @Override 13607 public int getApplicationEnabledSetting(String packageName, int userId) { 13608 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13609 int uid = Binder.getCallingUid(); 13610 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 13611 // reader 13612 synchronized (mPackages) { 13613 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 13614 } 13615 } 13616 13617 @Override 13618 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 13619 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 13620 int uid = Binder.getCallingUid(); 13621 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 13622 // reader 13623 synchronized (mPackages) { 13624 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 13625 } 13626 } 13627 13628 @Override 13629 public void enterSafeMode() { 13630 enforceSystemOrRoot("Only the system can request entering safe mode"); 13631 13632 if (!mSystemReady) { 13633 mSafeMode = true; 13634 } 13635 } 13636 13637 @Override 13638 public void systemReady() { 13639 mSystemReady = true; 13640 13641 // Read the compatibilty setting when the system is ready. 13642 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 13643 mContext.getContentResolver(), 13644 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 13645 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 13646 if (DEBUG_SETTINGS) { 13647 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 13648 } 13649 13650 synchronized (mPackages) { 13651 // Verify that all of the preferred activity components actually 13652 // exist. It is possible for applications to be updated and at 13653 // that point remove a previously declared activity component that 13654 // had been set as a preferred activity. We try to clean this up 13655 // the next time we encounter that preferred activity, but it is 13656 // possible for the user flow to never be able to return to that 13657 // situation so here we do a sanity check to make sure we haven't 13658 // left any junk around. 13659 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 13660 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 13661 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 13662 removed.clear(); 13663 for (PreferredActivity pa : pir.filterSet()) { 13664 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 13665 removed.add(pa); 13666 } 13667 } 13668 if (removed.size() > 0) { 13669 for (int r=0; r<removed.size(); r++) { 13670 PreferredActivity pa = removed.get(r); 13671 Slog.w(TAG, "Removing dangling preferred activity: " 13672 + pa.mPref.mComponent); 13673 pir.removeFilter(pa); 13674 } 13675 mSettings.writePackageRestrictionsLPr( 13676 mSettings.mPreferredActivities.keyAt(i)); 13677 } 13678 } 13679 } 13680 sUserManager.systemReady(); 13681 13682 // Kick off any messages waiting for system ready 13683 if (mPostSystemReadyMessages != null) { 13684 for (Message msg : mPostSystemReadyMessages) { 13685 msg.sendToTarget(); 13686 } 13687 mPostSystemReadyMessages = null; 13688 } 13689 13690 // Watch for external volumes that come and go over time 13691 final StorageManager storage = mContext.getSystemService(StorageManager.class); 13692 storage.registerListener(mStorageListener); 13693 13694 mInstallerService.systemReady(); 13695 mPackageDexOptimizer.systemReady(); 13696 } 13697 13698 @Override 13699 public boolean isSafeMode() { 13700 return mSafeMode; 13701 } 13702 13703 @Override 13704 public boolean hasSystemUidErrors() { 13705 return mHasSystemUidErrors; 13706 } 13707 13708 static String arrayToString(int[] array) { 13709 StringBuffer buf = new StringBuffer(128); 13710 buf.append('['); 13711 if (array != null) { 13712 for (int i=0; i<array.length; i++) { 13713 if (i > 0) buf.append(", "); 13714 buf.append(array[i]); 13715 } 13716 } 13717 buf.append(']'); 13718 return buf.toString(); 13719 } 13720 13721 static class DumpState { 13722 public static final int DUMP_LIBS = 1 << 0; 13723 public static final int DUMP_FEATURES = 1 << 1; 13724 public static final int DUMP_RESOLVERS = 1 << 2; 13725 public static final int DUMP_PERMISSIONS = 1 << 3; 13726 public static final int DUMP_PACKAGES = 1 << 4; 13727 public static final int DUMP_SHARED_USERS = 1 << 5; 13728 public static final int DUMP_MESSAGES = 1 << 6; 13729 public static final int DUMP_PROVIDERS = 1 << 7; 13730 public static final int DUMP_VERIFIERS = 1 << 8; 13731 public static final int DUMP_PREFERRED = 1 << 9; 13732 public static final int DUMP_PREFERRED_XML = 1 << 10; 13733 public static final int DUMP_KEYSETS = 1 << 11; 13734 public static final int DUMP_VERSION = 1 << 12; 13735 public static final int DUMP_INSTALLS = 1 << 13; 13736 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14; 13737 public static final int DUMP_DOMAIN_PREFERRED = 1 << 15; 13738 13739 public static final int OPTION_SHOW_FILTERS = 1 << 0; 13740 13741 private int mTypes; 13742 13743 private int mOptions; 13744 13745 private boolean mTitlePrinted; 13746 13747 private SharedUserSetting mSharedUser; 13748 13749 public boolean isDumping(int type) { 13750 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 13751 return true; 13752 } 13753 13754 return (mTypes & type) != 0; 13755 } 13756 13757 public void setDump(int type) { 13758 mTypes |= type; 13759 } 13760 13761 public boolean isOptionEnabled(int option) { 13762 return (mOptions & option) != 0; 13763 } 13764 13765 public void setOptionEnabled(int option) { 13766 mOptions |= option; 13767 } 13768 13769 public boolean onTitlePrinted() { 13770 final boolean printed = mTitlePrinted; 13771 mTitlePrinted = true; 13772 return printed; 13773 } 13774 13775 public boolean getTitlePrinted() { 13776 return mTitlePrinted; 13777 } 13778 13779 public void setTitlePrinted(boolean enabled) { 13780 mTitlePrinted = enabled; 13781 } 13782 13783 public SharedUserSetting getSharedUser() { 13784 return mSharedUser; 13785 } 13786 13787 public void setSharedUser(SharedUserSetting user) { 13788 mSharedUser = user; 13789 } 13790 } 13791 13792 @Override 13793 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 13794 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 13795 != PackageManager.PERMISSION_GRANTED) { 13796 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 13797 + Binder.getCallingPid() 13798 + ", uid=" + Binder.getCallingUid() 13799 + " without permission " 13800 + android.Manifest.permission.DUMP); 13801 return; 13802 } 13803 13804 DumpState dumpState = new DumpState(); 13805 boolean fullPreferred = false; 13806 boolean checkin = false; 13807 13808 String packageName = null; 13809 13810 int opti = 0; 13811 while (opti < args.length) { 13812 String opt = args[opti]; 13813 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 13814 break; 13815 } 13816 opti++; 13817 13818 if ("-a".equals(opt)) { 13819 // Right now we only know how to print all. 13820 } else if ("-h".equals(opt)) { 13821 pw.println("Package manager dump options:"); 13822 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 13823 pw.println(" --checkin: dump for a checkin"); 13824 pw.println(" -f: print details of intent filters"); 13825 pw.println(" -h: print this help"); 13826 pw.println(" cmd may be one of:"); 13827 pw.println(" l[ibraries]: list known shared libraries"); 13828 pw.println(" f[ibraries]: list device features"); 13829 pw.println(" k[eysets]: print known keysets"); 13830 pw.println(" r[esolvers]: dump intent resolvers"); 13831 pw.println(" perm[issions]: dump permissions"); 13832 pw.println(" pref[erred]: print preferred package settings"); 13833 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 13834 pw.println(" prov[iders]: dump content providers"); 13835 pw.println(" p[ackages]: dump installed packages"); 13836 pw.println(" s[hared-users]: dump shared user IDs"); 13837 pw.println(" m[essages]: print collected runtime messages"); 13838 pw.println(" v[erifiers]: print package verifier info"); 13839 pw.println(" version: print database version info"); 13840 pw.println(" write: write current settings now"); 13841 pw.println(" <package.name>: info about given package"); 13842 pw.println(" installs: details about install sessions"); 13843 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 13844 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 13845 return; 13846 } else if ("--checkin".equals(opt)) { 13847 checkin = true; 13848 } else if ("-f".equals(opt)) { 13849 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13850 } else { 13851 pw.println("Unknown argument: " + opt + "; use -h for help"); 13852 } 13853 } 13854 13855 // Is the caller requesting to dump a particular piece of data? 13856 if (opti < args.length) { 13857 String cmd = args[opti]; 13858 opti++; 13859 // Is this a package name? 13860 if ("android".equals(cmd) || cmd.contains(".")) { 13861 packageName = cmd; 13862 // When dumping a single package, we always dump all of its 13863 // filter information since the amount of data will be reasonable. 13864 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 13865 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 13866 dumpState.setDump(DumpState.DUMP_LIBS); 13867 } else if ("f".equals(cmd) || "features".equals(cmd)) { 13868 dumpState.setDump(DumpState.DUMP_FEATURES); 13869 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 13870 dumpState.setDump(DumpState.DUMP_RESOLVERS); 13871 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 13872 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 13873 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 13874 dumpState.setDump(DumpState.DUMP_PREFERRED); 13875 } else if ("preferred-xml".equals(cmd)) { 13876 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 13877 if (opti < args.length && "--full".equals(args[opti])) { 13878 fullPreferred = true; 13879 opti++; 13880 } 13881 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 13882 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 13883 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 13884 dumpState.setDump(DumpState.DUMP_PACKAGES); 13885 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 13886 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 13887 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 13888 dumpState.setDump(DumpState.DUMP_PROVIDERS); 13889 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 13890 dumpState.setDump(DumpState.DUMP_MESSAGES); 13891 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 13892 dumpState.setDump(DumpState.DUMP_VERIFIERS); 13893 } else if ("i".equals(cmd) || "ifv".equals(cmd) 13894 || "intent-filter-verifiers".equals(cmd)) { 13895 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 13896 } else if ("version".equals(cmd)) { 13897 dumpState.setDump(DumpState.DUMP_VERSION); 13898 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 13899 dumpState.setDump(DumpState.DUMP_KEYSETS); 13900 } else if ("installs".equals(cmd)) { 13901 dumpState.setDump(DumpState.DUMP_INSTALLS); 13902 } else if ("write".equals(cmd)) { 13903 synchronized (mPackages) { 13904 mSettings.writeLPr(); 13905 pw.println("Settings written."); 13906 return; 13907 } 13908 } 13909 } 13910 13911 if (checkin) { 13912 pw.println("vers,1"); 13913 } 13914 13915 // reader 13916 synchronized (mPackages) { 13917 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 13918 if (!checkin) { 13919 if (dumpState.onTitlePrinted()) 13920 pw.println(); 13921 pw.println("Database versions:"); 13922 pw.print(" SDK Version:"); 13923 pw.print(" internal="); 13924 pw.print(mSettings.mInternalSdkPlatform); 13925 pw.print(" external="); 13926 pw.println(mSettings.mExternalSdkPlatform); 13927 pw.print(" DB Version:"); 13928 pw.print(" internal="); 13929 pw.print(mSettings.mInternalDatabaseVersion); 13930 pw.print(" external="); 13931 pw.println(mSettings.mExternalDatabaseVersion); 13932 } 13933 } 13934 13935 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 13936 if (!checkin) { 13937 if (dumpState.onTitlePrinted()) 13938 pw.println(); 13939 pw.println("Verifiers:"); 13940 pw.print(" Required: "); 13941 pw.print(mRequiredVerifierPackage); 13942 pw.print(" (uid="); 13943 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 13944 pw.println(")"); 13945 } else if (mRequiredVerifierPackage != null) { 13946 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 13947 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 13948 } 13949 } 13950 13951 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 13952 packageName == null) { 13953 if (mIntentFilterVerifierComponent != null) { 13954 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 13955 if (!checkin) { 13956 if (dumpState.onTitlePrinted()) 13957 pw.println(); 13958 pw.println("Intent Filter Verifier:"); 13959 pw.print(" Using: "); 13960 pw.print(verifierPackageName); 13961 pw.print(" (uid="); 13962 pw.print(getPackageUid(verifierPackageName, 0)); 13963 pw.println(")"); 13964 } else if (verifierPackageName != null) { 13965 pw.print("ifv,"); pw.print(verifierPackageName); 13966 pw.print(","); pw.println(getPackageUid(verifierPackageName, 0)); 13967 } 13968 } else { 13969 pw.println(); 13970 pw.println("No Intent Filter Verifier available!"); 13971 } 13972 } 13973 13974 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 13975 boolean printedHeader = false; 13976 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 13977 while (it.hasNext()) { 13978 String name = it.next(); 13979 SharedLibraryEntry ent = mSharedLibraries.get(name); 13980 if (!checkin) { 13981 if (!printedHeader) { 13982 if (dumpState.onTitlePrinted()) 13983 pw.println(); 13984 pw.println("Libraries:"); 13985 printedHeader = true; 13986 } 13987 pw.print(" "); 13988 } else { 13989 pw.print("lib,"); 13990 } 13991 pw.print(name); 13992 if (!checkin) { 13993 pw.print(" -> "); 13994 } 13995 if (ent.path != null) { 13996 if (!checkin) { 13997 pw.print("(jar) "); 13998 pw.print(ent.path); 13999 } else { 14000 pw.print(",jar,"); 14001 pw.print(ent.path); 14002 } 14003 } else { 14004 if (!checkin) { 14005 pw.print("(apk) "); 14006 pw.print(ent.apk); 14007 } else { 14008 pw.print(",apk,"); 14009 pw.print(ent.apk); 14010 } 14011 } 14012 pw.println(); 14013 } 14014 } 14015 14016 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 14017 if (dumpState.onTitlePrinted()) 14018 pw.println(); 14019 if (!checkin) { 14020 pw.println("Features:"); 14021 } 14022 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 14023 while (it.hasNext()) { 14024 String name = it.next(); 14025 if (!checkin) { 14026 pw.print(" "); 14027 } else { 14028 pw.print("feat,"); 14029 } 14030 pw.println(name); 14031 } 14032 } 14033 14034 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 14035 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 14036 : "Activity Resolver Table:", " ", packageName, 14037 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14038 dumpState.setTitlePrinted(true); 14039 } 14040 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 14041 : "Receiver Resolver Table:", " ", packageName, 14042 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14043 dumpState.setTitlePrinted(true); 14044 } 14045 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 14046 : "Service Resolver Table:", " ", packageName, 14047 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14048 dumpState.setTitlePrinted(true); 14049 } 14050 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 14051 : "Provider Resolver Table:", " ", packageName, 14052 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 14053 dumpState.setTitlePrinted(true); 14054 } 14055 } 14056 14057 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 14058 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 14059 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 14060 int user = mSettings.mPreferredActivities.keyAt(i); 14061 if (pir.dump(pw, 14062 dumpState.getTitlePrinted() 14063 ? "\nPreferred Activities User " + user + ":" 14064 : "Preferred Activities User " + user + ":", " ", 14065 packageName, true, false)) { 14066 dumpState.setTitlePrinted(true); 14067 } 14068 } 14069 } 14070 14071 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 14072 pw.flush(); 14073 FileOutputStream fout = new FileOutputStream(fd); 14074 BufferedOutputStream str = new BufferedOutputStream(fout); 14075 XmlSerializer serializer = new FastXmlSerializer(); 14076 try { 14077 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 14078 serializer.startDocument(null, true); 14079 serializer.setFeature( 14080 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 14081 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 14082 serializer.endDocument(); 14083 serializer.flush(); 14084 } catch (IllegalArgumentException e) { 14085 pw.println("Failed writing: " + e); 14086 } catch (IllegalStateException e) { 14087 pw.println("Failed writing: " + e); 14088 } catch (IOException e) { 14089 pw.println("Failed writing: " + e); 14090 } 14091 } 14092 14093 if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) { 14094 pw.println(); 14095 int count = mSettings.mPackages.size(); 14096 if (count == 0) { 14097 pw.println("No domain preferred apps!"); 14098 pw.println(); 14099 } else { 14100 final String prefix = " "; 14101 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 14102 if (allPackageSettings.size() == 0) { 14103 pw.println("No domain preferred apps!"); 14104 pw.println(); 14105 } else { 14106 pw.println("Domain preferred apps status:"); 14107 pw.println(); 14108 count = 0; 14109 for (PackageSetting ps : allPackageSettings) { 14110 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14111 if (ivi == null || ivi.getPackageName() == null) continue; 14112 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14113 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14114 pw.println(prefix + "Status: " + ivi.getStatusString()); 14115 pw.println(); 14116 count++; 14117 } 14118 if (count == 0) { 14119 pw.println(prefix + "No domain preferred app status!"); 14120 pw.println(); 14121 } 14122 for (int userId : sUserManager.getUserIds()) { 14123 pw.println("Domain preferred apps for User " + userId + ":"); 14124 pw.println(); 14125 count = 0; 14126 for (PackageSetting ps : allPackageSettings) { 14127 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 14128 if (ivi == null || ivi.getPackageName() == null) { 14129 continue; 14130 } 14131 final int status = ps.getDomainVerificationStatusForUser(userId); 14132 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 14133 continue; 14134 } 14135 pw.println(prefix + "Package Name: " + ivi.getPackageName()); 14136 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 14137 String statusStr = IntentFilterVerificationInfo. 14138 getStatusStringFromValue(status); 14139 pw.println(prefix + "Status: " + statusStr); 14140 pw.println(); 14141 count++; 14142 } 14143 if (count == 0) { 14144 pw.println(prefix + "No domain preferred apps!"); 14145 pw.println(); 14146 } 14147 } 14148 } 14149 } 14150 } 14151 14152 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 14153 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 14154 if (packageName == null) { 14155 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 14156 if (iperm == 0) { 14157 if (dumpState.onTitlePrinted()) 14158 pw.println(); 14159 pw.println("AppOp Permissions:"); 14160 } 14161 pw.print(" AppOp Permission "); 14162 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 14163 pw.println(":"); 14164 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 14165 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 14166 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 14167 } 14168 } 14169 } 14170 } 14171 14172 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 14173 boolean printedSomething = false; 14174 for (PackageParser.Provider p : mProviders.mProviders.values()) { 14175 if (packageName != null && !packageName.equals(p.info.packageName)) { 14176 continue; 14177 } 14178 if (!printedSomething) { 14179 if (dumpState.onTitlePrinted()) 14180 pw.println(); 14181 pw.println("Registered ContentProviders:"); 14182 printedSomething = true; 14183 } 14184 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 14185 pw.print(" "); pw.println(p.toString()); 14186 } 14187 printedSomething = false; 14188 for (Map.Entry<String, PackageParser.Provider> entry : 14189 mProvidersByAuthority.entrySet()) { 14190 PackageParser.Provider p = entry.getValue(); 14191 if (packageName != null && !packageName.equals(p.info.packageName)) { 14192 continue; 14193 } 14194 if (!printedSomething) { 14195 if (dumpState.onTitlePrinted()) 14196 pw.println(); 14197 pw.println("ContentProvider Authorities:"); 14198 printedSomething = true; 14199 } 14200 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 14201 pw.print(" "); pw.println(p.toString()); 14202 if (p.info != null && p.info.applicationInfo != null) { 14203 final String appInfo = p.info.applicationInfo.toString(); 14204 pw.print(" applicationInfo="); pw.println(appInfo); 14205 } 14206 } 14207 } 14208 14209 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 14210 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 14211 } 14212 14213 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 14214 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 14215 } 14216 14217 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 14218 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 14219 } 14220 14221 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 14222 // XXX should handle packageName != null by dumping only install data that 14223 // the given package is involved with. 14224 if (dumpState.onTitlePrinted()) pw.println(); 14225 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 14226 } 14227 14228 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 14229 if (dumpState.onTitlePrinted()) pw.println(); 14230 mSettings.dumpReadMessagesLPr(pw, dumpState); 14231 14232 pw.println(); 14233 pw.println("Package warning messages:"); 14234 BufferedReader in = null; 14235 String line = null; 14236 try { 14237 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14238 while ((line = in.readLine()) != null) { 14239 if (line.contains("ignored: updated version")) continue; 14240 pw.println(line); 14241 } 14242 } catch (IOException ignored) { 14243 } finally { 14244 IoUtils.closeQuietly(in); 14245 } 14246 } 14247 14248 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 14249 BufferedReader in = null; 14250 String line = null; 14251 try { 14252 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 14253 while ((line = in.readLine()) != null) { 14254 if (line.contains("ignored: updated version")) continue; 14255 pw.print("msg,"); 14256 pw.println(line); 14257 } 14258 } catch (IOException ignored) { 14259 } finally { 14260 IoUtils.closeQuietly(in); 14261 } 14262 } 14263 } 14264 } 14265 14266 // ------- apps on sdcard specific code ------- 14267 static final boolean DEBUG_SD_INSTALL = false; 14268 14269 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 14270 14271 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 14272 14273 private boolean mMediaMounted = false; 14274 14275 static String getEncryptKey() { 14276 try { 14277 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 14278 SD_ENCRYPTION_KEYSTORE_NAME); 14279 if (sdEncKey == null) { 14280 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 14281 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 14282 if (sdEncKey == null) { 14283 Slog.e(TAG, "Failed to create encryption keys"); 14284 return null; 14285 } 14286 } 14287 return sdEncKey; 14288 } catch (NoSuchAlgorithmException nsae) { 14289 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 14290 return null; 14291 } catch (IOException ioe) { 14292 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 14293 return null; 14294 } 14295 } 14296 14297 /* 14298 * Update media status on PackageManager. 14299 */ 14300 @Override 14301 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 14302 int callingUid = Binder.getCallingUid(); 14303 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 14304 throw new SecurityException("Media status can only be updated by the system"); 14305 } 14306 // reader; this apparently protects mMediaMounted, but should probably 14307 // be a different lock in that case. 14308 synchronized (mPackages) { 14309 Log.i(TAG, "Updating external media status from " 14310 + (mMediaMounted ? "mounted" : "unmounted") + " to " 14311 + (mediaStatus ? "mounted" : "unmounted")); 14312 if (DEBUG_SD_INSTALL) 14313 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 14314 + ", mMediaMounted=" + mMediaMounted); 14315 if (mediaStatus == mMediaMounted) { 14316 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 14317 : 0, -1); 14318 mHandler.sendMessage(msg); 14319 return; 14320 } 14321 mMediaMounted = mediaStatus; 14322 } 14323 // Queue up an async operation since the package installation may take a 14324 // little while. 14325 mHandler.post(new Runnable() { 14326 public void run() { 14327 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 14328 } 14329 }); 14330 } 14331 14332 /** 14333 * Called by MountService when the initial ASECs to scan are available. 14334 * Should block until all the ASEC containers are finished being scanned. 14335 */ 14336 public void scanAvailableAsecs() { 14337 updateExternalMediaStatusInner(true, false, false); 14338 if (mShouldRestoreconData) { 14339 SELinuxMMAC.setRestoreconDone(); 14340 mShouldRestoreconData = false; 14341 } 14342 } 14343 14344 /* 14345 * Collect information of applications on external media, map them against 14346 * existing containers and update information based on current mount status. 14347 * Please note that we always have to report status if reportStatus has been 14348 * set to true especially when unloading packages. 14349 */ 14350 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 14351 boolean externalStorage) { 14352 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 14353 int[] uidArr = EmptyArray.INT; 14354 14355 final String[] list = PackageHelper.getSecureContainerList(); 14356 if (ArrayUtils.isEmpty(list)) { 14357 Log.i(TAG, "No secure containers found"); 14358 } else { 14359 // Process list of secure containers and categorize them 14360 // as active or stale based on their package internal state. 14361 14362 // reader 14363 synchronized (mPackages) { 14364 for (String cid : list) { 14365 // Leave stages untouched for now; installer service owns them 14366 if (PackageInstallerService.isStageName(cid)) continue; 14367 14368 if (DEBUG_SD_INSTALL) 14369 Log.i(TAG, "Processing container " + cid); 14370 String pkgName = getAsecPackageName(cid); 14371 if (pkgName == null) { 14372 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 14373 continue; 14374 } 14375 if (DEBUG_SD_INSTALL) 14376 Log.i(TAG, "Looking for pkg : " + pkgName); 14377 14378 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14379 if (ps == null) { 14380 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 14381 continue; 14382 } 14383 14384 /* 14385 * Skip packages that are not external if we're unmounting 14386 * external storage. 14387 */ 14388 if (externalStorage && !isMounted && !isExternal(ps)) { 14389 continue; 14390 } 14391 14392 final AsecInstallArgs args = new AsecInstallArgs(cid, 14393 getAppDexInstructionSets(ps), ps.isForwardLocked()); 14394 // The package status is changed only if the code path 14395 // matches between settings and the container id. 14396 if (ps.codePathString != null 14397 && ps.codePathString.startsWith(args.getCodePath())) { 14398 if (DEBUG_SD_INSTALL) { 14399 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 14400 + " at code path: " + ps.codePathString); 14401 } 14402 14403 // We do have a valid package installed on sdcard 14404 processCids.put(args, ps.codePathString); 14405 final int uid = ps.appId; 14406 if (uid != -1) { 14407 uidArr = ArrayUtils.appendInt(uidArr, uid); 14408 } 14409 } else { 14410 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 14411 + ps.codePathString); 14412 } 14413 } 14414 } 14415 14416 Arrays.sort(uidArr); 14417 } 14418 14419 // Process packages with valid entries. 14420 if (isMounted) { 14421 if (DEBUG_SD_INSTALL) 14422 Log.i(TAG, "Loading packages"); 14423 loadMediaPackages(processCids, uidArr); 14424 startCleaningPackages(); 14425 mInstallerService.onSecureContainersAvailable(); 14426 } else { 14427 if (DEBUG_SD_INSTALL) 14428 Log.i(TAG, "Unloading packages"); 14429 unloadMediaPackages(processCids, uidArr, reportStatus); 14430 } 14431 } 14432 14433 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14434 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 14435 final int size = infos.size(); 14436 final String[] packageNames = new String[size]; 14437 final int[] packageUids = new int[size]; 14438 for (int i = 0; i < size; i++) { 14439 final ApplicationInfo info = infos.get(i); 14440 packageNames[i] = info.packageName; 14441 packageUids[i] = info.uid; 14442 } 14443 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 14444 finishedReceiver); 14445 } 14446 14447 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14448 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14449 sendResourcesChangedBroadcast(mediaStatus, replacing, 14450 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 14451 } 14452 14453 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 14454 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 14455 int size = pkgList.length; 14456 if (size > 0) { 14457 // Send broadcasts here 14458 Bundle extras = new Bundle(); 14459 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 14460 if (uidArr != null) { 14461 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 14462 } 14463 if (replacing) { 14464 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 14465 } 14466 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 14467 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 14468 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 14469 } 14470 } 14471 14472 /* 14473 * Look at potentially valid container ids from processCids If package 14474 * information doesn't match the one on record or package scanning fails, 14475 * the cid is added to list of removeCids. We currently don't delete stale 14476 * containers. 14477 */ 14478 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 14479 ArrayList<String> pkgList = new ArrayList<String>(); 14480 Set<AsecInstallArgs> keys = processCids.keySet(); 14481 14482 for (AsecInstallArgs args : keys) { 14483 String codePath = processCids.get(args); 14484 if (DEBUG_SD_INSTALL) 14485 Log.i(TAG, "Loading container : " + args.cid); 14486 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14487 try { 14488 // Make sure there are no container errors first. 14489 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 14490 Slog.e(TAG, "Failed to mount cid : " + args.cid 14491 + " when installing from sdcard"); 14492 continue; 14493 } 14494 // Check code path here. 14495 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 14496 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 14497 + " does not match one in settings " + codePath); 14498 continue; 14499 } 14500 // Parse package 14501 int parseFlags = mDefParseFlags; 14502 if (args.isExternalAsec()) { 14503 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 14504 } 14505 if (args.isFwdLocked()) { 14506 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 14507 } 14508 14509 synchronized (mInstallLock) { 14510 PackageParser.Package pkg = null; 14511 try { 14512 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 14513 } catch (PackageManagerException e) { 14514 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 14515 } 14516 // Scan the package 14517 if (pkg != null) { 14518 /* 14519 * TODO why is the lock being held? doPostInstall is 14520 * called in other places without the lock. This needs 14521 * to be straightened out. 14522 */ 14523 // writer 14524 synchronized (mPackages) { 14525 retCode = PackageManager.INSTALL_SUCCEEDED; 14526 pkgList.add(pkg.packageName); 14527 // Post process args 14528 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 14529 pkg.applicationInfo.uid); 14530 } 14531 } else { 14532 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 14533 } 14534 } 14535 14536 } finally { 14537 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 14538 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 14539 } 14540 } 14541 } 14542 // writer 14543 synchronized (mPackages) { 14544 // If the platform SDK has changed since the last time we booted, 14545 // we need to re-grant app permission to catch any new ones that 14546 // appear. This is really a hack, and means that apps can in some 14547 // cases get permissions that the user didn't initially explicitly 14548 // allow... it would be nice to have some better way to handle 14549 // this situation. 14550 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 14551 if (regrantPermissions) 14552 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 14553 + mSdkVersion + "; regranting permissions for external storage"); 14554 mSettings.mExternalSdkPlatform = mSdkVersion; 14555 14556 // Make sure group IDs have been assigned, and any permission 14557 // changes in other apps are accounted for 14558 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 14559 | (regrantPermissions 14560 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 14561 : 0)); 14562 14563 mSettings.updateExternalDatabaseVersion(); 14564 14565 // can downgrade to reader 14566 // Persist settings 14567 mSettings.writeLPr(); 14568 } 14569 // Send a broadcast to let everyone know we are done processing 14570 if (pkgList.size() > 0) { 14571 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 14572 } 14573 } 14574 14575 /* 14576 * Utility method to unload a list of specified containers 14577 */ 14578 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 14579 // Just unmount all valid containers. 14580 for (AsecInstallArgs arg : cidArgs) { 14581 synchronized (mInstallLock) { 14582 arg.doPostDeleteLI(false); 14583 } 14584 } 14585 } 14586 14587 /* 14588 * Unload packages mounted on external media. This involves deleting package 14589 * data from internal structures, sending broadcasts about diabled packages, 14590 * gc'ing to free up references, unmounting all secure containers 14591 * corresponding to packages on external media, and posting a 14592 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 14593 * that we always have to post this message if status has been requested no 14594 * matter what. 14595 */ 14596 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 14597 final boolean reportStatus) { 14598 if (DEBUG_SD_INSTALL) 14599 Log.i(TAG, "unloading media packages"); 14600 ArrayList<String> pkgList = new ArrayList<String>(); 14601 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 14602 final Set<AsecInstallArgs> keys = processCids.keySet(); 14603 for (AsecInstallArgs args : keys) { 14604 String pkgName = args.getPackageName(); 14605 if (DEBUG_SD_INSTALL) 14606 Log.i(TAG, "Trying to unload pkg : " + pkgName); 14607 // Delete package internally 14608 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14609 synchronized (mInstallLock) { 14610 boolean res = deletePackageLI(pkgName, null, false, null, null, 14611 PackageManager.DELETE_KEEP_DATA, outInfo, false); 14612 if (res) { 14613 pkgList.add(pkgName); 14614 } else { 14615 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 14616 failedList.add(args); 14617 } 14618 } 14619 } 14620 14621 // reader 14622 synchronized (mPackages) { 14623 // We didn't update the settings after removing each package; 14624 // write them now for all packages. 14625 mSettings.writeLPr(); 14626 } 14627 14628 // We have to absolutely send UPDATED_MEDIA_STATUS only 14629 // after confirming that all the receivers processed the ordered 14630 // broadcast when packages get disabled, force a gc to clean things up. 14631 // and unload all the containers. 14632 if (pkgList.size() > 0) { 14633 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 14634 new IIntentReceiver.Stub() { 14635 public void performReceive(Intent intent, int resultCode, String data, 14636 Bundle extras, boolean ordered, boolean sticky, 14637 int sendingUser) throws RemoteException { 14638 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 14639 reportStatus ? 1 : 0, 1, keys); 14640 mHandler.sendMessage(msg); 14641 } 14642 }); 14643 } else { 14644 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 14645 keys); 14646 mHandler.sendMessage(msg); 14647 } 14648 } 14649 14650 private void loadPrivatePackages(VolumeInfo vol) { 14651 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 14652 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 14653 synchronized (mInstallLock) { 14654 synchronized (mPackages) { 14655 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14656 for (PackageSetting ps : packages) { 14657 final PackageParser.Package pkg; 14658 try { 14659 pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null); 14660 loaded.add(pkg.applicationInfo); 14661 } catch (PackageManagerException e) { 14662 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 14663 } 14664 } 14665 14666 // TODO: regrant any permissions that changed based since original install 14667 14668 mSettings.writeLPr(); 14669 } 14670 } 14671 14672 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 14673 sendResourcesChangedBroadcast(true, false, loaded, null); 14674 } 14675 14676 private void unloadPrivatePackages(VolumeInfo vol) { 14677 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 14678 synchronized (mInstallLock) { 14679 synchronized (mPackages) { 14680 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid); 14681 for (PackageSetting ps : packages) { 14682 if (ps.pkg == null) continue; 14683 14684 final ApplicationInfo info = ps.pkg.applicationInfo; 14685 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 14686 if (deletePackageLI(ps.name, null, false, null, null, 14687 PackageManager.DELETE_KEEP_DATA, outInfo, false)) { 14688 unloaded.add(info); 14689 } else { 14690 Slog.w(TAG, "Failed to unload " + ps.codePath); 14691 } 14692 } 14693 14694 mSettings.writeLPr(); 14695 } 14696 } 14697 14698 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 14699 sendResourcesChangedBroadcast(false, false, unloaded, null); 14700 } 14701 14702 private void unfreezePackage(String packageName) { 14703 synchronized (mPackages) { 14704 final PackageSetting ps = mSettings.mPackages.get(packageName); 14705 if (ps != null) { 14706 ps.frozen = false; 14707 } 14708 } 14709 } 14710 14711 @Override 14712 public int movePackage(final String packageName, final String volumeUuid) { 14713 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14714 14715 final int moveId = mNextMoveId.getAndIncrement(); 14716 try { 14717 movePackageInternal(packageName, volumeUuid, moveId); 14718 } catch (PackageManagerException e) { 14719 Slog.w(TAG, "Failed to move " + packageName, e); 14720 mMoveCallbacks.notifyStatusChanged(moveId, 14721 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14722 } 14723 return moveId; 14724 } 14725 14726 private void movePackageInternal(final String packageName, final String volumeUuid, 14727 final int moveId) throws PackageManagerException { 14728 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 14729 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14730 final PackageManager pm = mContext.getPackageManager(); 14731 14732 final boolean currentAsec; 14733 final String currentVolumeUuid; 14734 final File codeFile; 14735 final String installerPackageName; 14736 final String packageAbiOverride; 14737 final int appId; 14738 final String seinfo; 14739 final String label; 14740 14741 // reader 14742 synchronized (mPackages) { 14743 final PackageParser.Package pkg = mPackages.get(packageName); 14744 final PackageSetting ps = mSettings.mPackages.get(packageName); 14745 if (pkg == null || ps == null) { 14746 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 14747 } 14748 14749 if (pkg.applicationInfo.isSystemApp()) { 14750 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 14751 "Cannot move system application"); 14752 } 14753 14754 if (Objects.equals(ps.volumeUuid, volumeUuid)) { 14755 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14756 "Package already moved to " + volumeUuid); 14757 } 14758 14759 final File probe = new File(pkg.codePath); 14760 final File probeOat = new File(probe, "oat"); 14761 if (!probe.isDirectory() || !probeOat.isDirectory()) { 14762 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14763 "Move only supported for modern cluster style installs"); 14764 } 14765 14766 if (ps.frozen) { 14767 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 14768 "Failed to move already frozen package"); 14769 } 14770 ps.frozen = true; 14771 14772 currentAsec = pkg.applicationInfo.isForwardLocked() 14773 || pkg.applicationInfo.isExternalAsec(); 14774 currentVolumeUuid = ps.volumeUuid; 14775 codeFile = new File(pkg.codePath); 14776 installerPackageName = ps.installerPackageName; 14777 packageAbiOverride = ps.cpuAbiOverrideString; 14778 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 14779 seinfo = pkg.applicationInfo.seinfo; 14780 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 14781 } 14782 14783 // Now that we're guarded by frozen state, kill app during move 14784 killApplication(packageName, appId, "move pkg"); 14785 14786 final Bundle extras = new Bundle(); 14787 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 14788 extras.putString(Intent.EXTRA_TITLE, label); 14789 mMoveCallbacks.notifyCreated(moveId, extras); 14790 14791 int installFlags; 14792 final boolean moveCompleteApp; 14793 final File measurePath; 14794 14795 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 14796 installFlags = INSTALL_INTERNAL; 14797 moveCompleteApp = !currentAsec; 14798 measurePath = Environment.getDataAppDirectory(volumeUuid); 14799 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 14800 installFlags = INSTALL_EXTERNAL; 14801 moveCompleteApp = false; 14802 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 14803 } else { 14804 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 14805 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 14806 || !volume.isMountedWritable()) { 14807 unfreezePackage(packageName); 14808 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14809 "Move location not mounted private volume"); 14810 } 14811 14812 Preconditions.checkState(!currentAsec); 14813 14814 installFlags = INSTALL_INTERNAL; 14815 moveCompleteApp = true; 14816 measurePath = Environment.getDataAppDirectory(volumeUuid); 14817 } 14818 14819 final PackageStats stats = new PackageStats(null, -1); 14820 synchronized (mInstaller) { 14821 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 14822 unfreezePackage(packageName); 14823 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14824 "Failed to measure package size"); 14825 } 14826 } 14827 14828 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 14829 + stats.dataSize); 14830 14831 final long startFreeBytes = measurePath.getFreeSpace(); 14832 final long sizeBytes; 14833 if (moveCompleteApp) { 14834 sizeBytes = stats.codeSize + stats.dataSize; 14835 } else { 14836 sizeBytes = stats.codeSize; 14837 } 14838 14839 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 14840 unfreezePackage(packageName); 14841 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 14842 "Not enough free space to move"); 14843 } 14844 14845 mMoveCallbacks.notifyStatusChanged(moveId, 10); 14846 14847 final CountDownLatch installedLatch = new CountDownLatch(1); 14848 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 14849 @Override 14850 public void onUserActionRequired(Intent intent) throws RemoteException { 14851 throw new IllegalStateException(); 14852 } 14853 14854 @Override 14855 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 14856 Bundle extras) throws RemoteException { 14857 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 14858 + PackageManager.installStatusToString(returnCode, msg)); 14859 14860 installedLatch.countDown(); 14861 14862 // Regardless of success or failure of the move operation, 14863 // always unfreeze the package 14864 unfreezePackage(packageName); 14865 14866 final int status = PackageManager.installStatusToPublicStatus(returnCode); 14867 switch (status) { 14868 case PackageInstaller.STATUS_SUCCESS: 14869 mMoveCallbacks.notifyStatusChanged(moveId, 14870 PackageManager.MOVE_SUCCEEDED); 14871 break; 14872 case PackageInstaller.STATUS_FAILURE_STORAGE: 14873 mMoveCallbacks.notifyStatusChanged(moveId, 14874 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 14875 break; 14876 default: 14877 mMoveCallbacks.notifyStatusChanged(moveId, 14878 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 14879 break; 14880 } 14881 } 14882 }; 14883 14884 final MoveInfo move; 14885 if (moveCompleteApp) { 14886 // Kick off a thread to report progress estimates 14887 new Thread() { 14888 @Override 14889 public void run() { 14890 while (true) { 14891 try { 14892 if (installedLatch.await(1, TimeUnit.SECONDS)) { 14893 break; 14894 } 14895 } catch (InterruptedException ignored) { 14896 } 14897 14898 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 14899 final int progress = 10 + (int) MathUtils.constrain( 14900 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 14901 mMoveCallbacks.notifyStatusChanged(moveId, progress); 14902 } 14903 } 14904 }.start(); 14905 14906 final String dataAppName = codeFile.getName(); 14907 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 14908 dataAppName, appId, seinfo); 14909 } else { 14910 move = null; 14911 } 14912 14913 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 14914 14915 final Message msg = mHandler.obtainMessage(INIT_COPY); 14916 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 14917 msg.obj = new InstallParams(origin, move, installObserver, installFlags, 14918 installerPackageName, volumeUuid, null, user, packageAbiOverride); 14919 mHandler.sendMessage(msg); 14920 } 14921 14922 @Override 14923 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 14924 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 14925 14926 final int realMoveId = mNextMoveId.getAndIncrement(); 14927 final Bundle extras = new Bundle(); 14928 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 14929 mMoveCallbacks.notifyCreated(realMoveId, extras); 14930 14931 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 14932 @Override 14933 public void onCreated(int moveId, Bundle extras) { 14934 // Ignored 14935 } 14936 14937 @Override 14938 public void onStatusChanged(int moveId, int status, long estMillis) { 14939 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 14940 } 14941 }; 14942 14943 final StorageManager storage = mContext.getSystemService(StorageManager.class); 14944 storage.setPrimaryStorageUuid(volumeUuid, callback); 14945 return realMoveId; 14946 } 14947 14948 @Override 14949 public int getMoveStatus(int moveId) { 14950 mContext.enforceCallingOrSelfPermission( 14951 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14952 return mMoveCallbacks.mLastStatus.get(moveId); 14953 } 14954 14955 @Override 14956 public void registerMoveCallback(IPackageMoveObserver callback) { 14957 mContext.enforceCallingOrSelfPermission( 14958 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14959 mMoveCallbacks.register(callback); 14960 } 14961 14962 @Override 14963 public void unregisterMoveCallback(IPackageMoveObserver callback) { 14964 mContext.enforceCallingOrSelfPermission( 14965 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 14966 mMoveCallbacks.unregister(callback); 14967 } 14968 14969 @Override 14970 public boolean setInstallLocation(int loc) { 14971 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 14972 null); 14973 if (getInstallLocation() == loc) { 14974 return true; 14975 } 14976 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 14977 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 14978 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 14979 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 14980 return true; 14981 } 14982 return false; 14983 } 14984 14985 @Override 14986 public int getInstallLocation() { 14987 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14988 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 14989 PackageHelper.APP_INSTALL_AUTO); 14990 } 14991 14992 /** Called by UserManagerService */ 14993 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 14994 mDirtyUsers.remove(userHandle); 14995 mSettings.removeUserLPw(userHandle); 14996 mPendingBroadcasts.remove(userHandle); 14997 if (mInstaller != null) { 14998 // Technically, we shouldn't be doing this with the package lock 14999 // held. However, this is very rare, and there is already so much 15000 // other disk I/O going on, that we'll let it slide for now. 15001 final StorageManager storage = StorageManager.from(mContext); 15002 final List<VolumeInfo> vols = storage.getVolumes(); 15003 for (VolumeInfo vol : vols) { 15004 if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) { 15005 final String volumeUuid = vol.getFsUuid(); 15006 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 15007 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 15008 } 15009 } 15010 } 15011 mUserNeedsBadging.delete(userHandle); 15012 removeUnusedPackagesLILPw(userManager, userHandle); 15013 } 15014 15015 /** 15016 * We're removing userHandle and would like to remove any downloaded packages 15017 * that are no longer in use by any other user. 15018 * @param userHandle the user being removed 15019 */ 15020 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 15021 final boolean DEBUG_CLEAN_APKS = false; 15022 int [] users = userManager.getUserIdsLPr(); 15023 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 15024 while (psit.hasNext()) { 15025 PackageSetting ps = psit.next(); 15026 if (ps.pkg == null) { 15027 continue; 15028 } 15029 final String packageName = ps.pkg.packageName; 15030 // Skip over if system app 15031 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15032 continue; 15033 } 15034 if (DEBUG_CLEAN_APKS) { 15035 Slog.i(TAG, "Checking package " + packageName); 15036 } 15037 boolean keep = false; 15038 for (int i = 0; i < users.length; i++) { 15039 if (users[i] != userHandle && ps.getInstalled(users[i])) { 15040 keep = true; 15041 if (DEBUG_CLEAN_APKS) { 15042 Slog.i(TAG, " Keeping package " + packageName + " for user " 15043 + users[i]); 15044 } 15045 break; 15046 } 15047 } 15048 if (!keep) { 15049 if (DEBUG_CLEAN_APKS) { 15050 Slog.i(TAG, " Removing package " + packageName); 15051 } 15052 mHandler.post(new Runnable() { 15053 public void run() { 15054 deletePackageX(packageName, userHandle, 0); 15055 } //end run 15056 }); 15057 } 15058 } 15059 } 15060 15061 /** Called by UserManagerService */ 15062 void createNewUserLILPw(int userHandle, File path) { 15063 if (mInstaller != null) { 15064 mInstaller.createUserConfig(userHandle); 15065 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 15066 } 15067 } 15068 15069 void newUserCreatedLILPw(int userHandle) { 15070 // Adding a user requires updating runtime permissions for system apps. 15071 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 15072 } 15073 15074 @Override 15075 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 15076 mContext.enforceCallingOrSelfPermission( 15077 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15078 "Only package verification agents can read the verifier device identity"); 15079 15080 synchronized (mPackages) { 15081 return mSettings.getVerifierDeviceIdentityLPw(); 15082 } 15083 } 15084 15085 @Override 15086 public void setPermissionEnforced(String permission, boolean enforced) { 15087 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 15088 if (READ_EXTERNAL_STORAGE.equals(permission)) { 15089 synchronized (mPackages) { 15090 if (mSettings.mReadExternalStorageEnforced == null 15091 || mSettings.mReadExternalStorageEnforced != enforced) { 15092 mSettings.mReadExternalStorageEnforced = enforced; 15093 mSettings.writeLPr(); 15094 } 15095 } 15096 // kill any non-foreground processes so we restart them and 15097 // grant/revoke the GID. 15098 final IActivityManager am = ActivityManagerNative.getDefault(); 15099 if (am != null) { 15100 final long token = Binder.clearCallingIdentity(); 15101 try { 15102 am.killProcessesBelowForeground("setPermissionEnforcement"); 15103 } catch (RemoteException e) { 15104 } finally { 15105 Binder.restoreCallingIdentity(token); 15106 } 15107 } 15108 } else { 15109 throw new IllegalArgumentException("No selective enforcement for " + permission); 15110 } 15111 } 15112 15113 @Override 15114 @Deprecated 15115 public boolean isPermissionEnforced(String permission) { 15116 return true; 15117 } 15118 15119 @Override 15120 public boolean isStorageLow() { 15121 final long token = Binder.clearCallingIdentity(); 15122 try { 15123 final DeviceStorageMonitorInternal 15124 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 15125 if (dsm != null) { 15126 return dsm.isMemoryLow(); 15127 } else { 15128 return false; 15129 } 15130 } finally { 15131 Binder.restoreCallingIdentity(token); 15132 } 15133 } 15134 15135 @Override 15136 public IPackageInstaller getPackageInstaller() { 15137 return mInstallerService; 15138 } 15139 15140 private boolean userNeedsBadging(int userId) { 15141 int index = mUserNeedsBadging.indexOfKey(userId); 15142 if (index < 0) { 15143 final UserInfo userInfo; 15144 final long token = Binder.clearCallingIdentity(); 15145 try { 15146 userInfo = sUserManager.getUserInfo(userId); 15147 } finally { 15148 Binder.restoreCallingIdentity(token); 15149 } 15150 final boolean b; 15151 if (userInfo != null && userInfo.isManagedProfile()) { 15152 b = true; 15153 } else { 15154 b = false; 15155 } 15156 mUserNeedsBadging.put(userId, b); 15157 return b; 15158 } 15159 return mUserNeedsBadging.valueAt(index); 15160 } 15161 15162 @Override 15163 public KeySet getKeySetByAlias(String packageName, String alias) { 15164 if (packageName == null || alias == null) { 15165 return null; 15166 } 15167 synchronized(mPackages) { 15168 final PackageParser.Package pkg = mPackages.get(packageName); 15169 if (pkg == null) { 15170 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15171 throw new IllegalArgumentException("Unknown package: " + packageName); 15172 } 15173 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15174 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 15175 } 15176 } 15177 15178 @Override 15179 public KeySet getSigningKeySet(String packageName) { 15180 if (packageName == null) { 15181 return null; 15182 } 15183 synchronized(mPackages) { 15184 final PackageParser.Package pkg = mPackages.get(packageName); 15185 if (pkg == null) { 15186 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15187 throw new IllegalArgumentException("Unknown package: " + packageName); 15188 } 15189 if (pkg.applicationInfo.uid != Binder.getCallingUid() 15190 && Process.SYSTEM_UID != Binder.getCallingUid()) { 15191 throw new SecurityException("May not access signing KeySet of other apps."); 15192 } 15193 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15194 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 15195 } 15196 } 15197 15198 @Override 15199 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 15200 if (packageName == null || ks == null) { 15201 return false; 15202 } 15203 synchronized(mPackages) { 15204 final PackageParser.Package pkg = mPackages.get(packageName); 15205 if (pkg == null) { 15206 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15207 throw new IllegalArgumentException("Unknown package: " + packageName); 15208 } 15209 IBinder ksh = ks.getToken(); 15210 if (ksh instanceof KeySetHandle) { 15211 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15212 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 15213 } 15214 return false; 15215 } 15216 } 15217 15218 @Override 15219 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 15220 if (packageName == null || ks == null) { 15221 return false; 15222 } 15223 synchronized(mPackages) { 15224 final PackageParser.Package pkg = mPackages.get(packageName); 15225 if (pkg == null) { 15226 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 15227 throw new IllegalArgumentException("Unknown package: " + packageName); 15228 } 15229 IBinder ksh = ks.getToken(); 15230 if (ksh instanceof KeySetHandle) { 15231 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15232 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 15233 } 15234 return false; 15235 } 15236 } 15237 15238 public void getUsageStatsIfNoPackageUsageInfo() { 15239 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 15240 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 15241 if (usm == null) { 15242 throw new IllegalStateException("UsageStatsManager must be initialized"); 15243 } 15244 long now = System.currentTimeMillis(); 15245 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 15246 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 15247 String packageName = entry.getKey(); 15248 PackageParser.Package pkg = mPackages.get(packageName); 15249 if (pkg == null) { 15250 continue; 15251 } 15252 UsageStats usage = entry.getValue(); 15253 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 15254 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 15255 } 15256 } 15257 } 15258 15259 /** 15260 * Check and throw if the given before/after packages would be considered a 15261 * downgrade. 15262 */ 15263 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 15264 throws PackageManagerException { 15265 if (after.versionCode < before.mVersionCode) { 15266 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15267 "Update version code " + after.versionCode + " is older than current " 15268 + before.mVersionCode); 15269 } else if (after.versionCode == before.mVersionCode) { 15270 if (after.baseRevisionCode < before.baseRevisionCode) { 15271 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15272 "Update base revision code " + after.baseRevisionCode 15273 + " is older than current " + before.baseRevisionCode); 15274 } 15275 15276 if (!ArrayUtils.isEmpty(after.splitNames)) { 15277 for (int i = 0; i < after.splitNames.length; i++) { 15278 final String splitName = after.splitNames[i]; 15279 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 15280 if (j != -1) { 15281 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 15282 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 15283 "Update split " + splitName + " revision code " 15284 + after.splitRevisionCodes[i] + " is older than current " 15285 + before.splitRevisionCodes[j]); 15286 } 15287 } 15288 } 15289 } 15290 } 15291 } 15292 15293 private static class MoveCallbacks extends Handler { 15294 private static final int MSG_CREATED = 1; 15295 private static final int MSG_STATUS_CHANGED = 2; 15296 15297 private final RemoteCallbackList<IPackageMoveObserver> 15298 mCallbacks = new RemoteCallbackList<>(); 15299 15300 private final SparseIntArray mLastStatus = new SparseIntArray(); 15301 15302 public MoveCallbacks(Looper looper) { 15303 super(looper); 15304 } 15305 15306 public void register(IPackageMoveObserver callback) { 15307 mCallbacks.register(callback); 15308 } 15309 15310 public void unregister(IPackageMoveObserver callback) { 15311 mCallbacks.unregister(callback); 15312 } 15313 15314 @Override 15315 public void handleMessage(Message msg) { 15316 final SomeArgs args = (SomeArgs) msg.obj; 15317 final int n = mCallbacks.beginBroadcast(); 15318 for (int i = 0; i < n; i++) { 15319 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 15320 try { 15321 invokeCallback(callback, msg.what, args); 15322 } catch (RemoteException ignored) { 15323 } 15324 } 15325 mCallbacks.finishBroadcast(); 15326 args.recycle(); 15327 } 15328 15329 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 15330 throws RemoteException { 15331 switch (what) { 15332 case MSG_CREATED: { 15333 callback.onCreated(args.argi1, (Bundle) args.arg2); 15334 break; 15335 } 15336 case MSG_STATUS_CHANGED: { 15337 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 15338 break; 15339 } 15340 } 15341 } 15342 15343 private void notifyCreated(int moveId, Bundle extras) { 15344 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 15345 15346 final SomeArgs args = SomeArgs.obtain(); 15347 args.argi1 = moveId; 15348 args.arg2 = extras; 15349 obtainMessage(MSG_CREATED, args).sendToTarget(); 15350 } 15351 15352 private void notifyStatusChanged(int moveId, int status) { 15353 notifyStatusChanged(moveId, status, -1); 15354 } 15355 15356 private void notifyStatusChanged(int moveId, int status, long estMillis) { 15357 Slog.v(TAG, "Move " + moveId + " status " + status); 15358 15359 final SomeArgs args = SomeArgs.obtain(); 15360 args.argi1 = moveId; 15361 args.argi2 = status; 15362 args.arg3 = estMillis; 15363 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 15364 15365 synchronized (mLastStatus) { 15366 mLastStatus.put(moveId, status); 15367 } 15368 } 15369 } 15370 15371 private final class OnPermissionChangeListeners extends Handler { 15372 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 15373 15374 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 15375 new RemoteCallbackList<>(); 15376 15377 public OnPermissionChangeListeners(Looper looper) { 15378 super(looper); 15379 } 15380 15381 @Override 15382 public void handleMessage(Message msg) { 15383 switch (msg.what) { 15384 case MSG_ON_PERMISSIONS_CHANGED: { 15385 final int uid = msg.arg1; 15386 handleOnPermissionsChanged(uid); 15387 } break; 15388 } 15389 } 15390 15391 public void addListenerLocked(IOnPermissionsChangeListener listener) { 15392 mPermissionListeners.register(listener); 15393 15394 } 15395 15396 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 15397 mPermissionListeners.unregister(listener); 15398 } 15399 15400 public void onPermissionsChanged(int uid) { 15401 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 15402 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 15403 } 15404 } 15405 15406 private void handleOnPermissionsChanged(int uid) { 15407 final int count = mPermissionListeners.beginBroadcast(); 15408 try { 15409 for (int i = 0; i < count; i++) { 15410 IOnPermissionsChangeListener callback = mPermissionListeners 15411 .getBroadcastItem(i); 15412 try { 15413 callback.onPermissionsChanged(uid); 15414 } catch (RemoteException e) { 15415 Log.e(TAG, "Permission listener is dead", e); 15416 } 15417 } 15418 } finally { 15419 mPermissionListeners.finishBroadcast(); 15420 } 15421 } 15422 } 15423} 15424